feat(lstv2 move): moved lstv2 into this app to keep them combined and easier to maintain

This commit is contained in:
2025-09-19 22:22:05 -05:00
parent caf2315191
commit e4477402ad
847 changed files with 165801 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
import {z} from "zod";
import {createLog} from "../../logger/logger.js";
import {db} from "../../../../database/dbclient.js";
import {rfidReaders} from "../../../../database/schema/rfidReaders.js";
const ReaderData = z.object({
reader: z.string(),
readerIP: z.string(),
});
type ReaderData = z.infer<typeof ReaderData>;
export const addReader = async (data: ReaderData, user: any) => {
/**
* add a new reader with name and ip.
*/
ReaderData.parse(data);
if (!data.reader && !data.readerIP) {
createLog("error", user.username, "rfid", "Missing data please check that you have both a name and ip.");
return {success: false, message: "Missing data please check that you have both a name and ip."};
}
// try to add the reader
try {
await db.insert(rfidReaders).values(data).onConflictDoUpdate({target: rfidReaders.reader, set: data});
createLog("info", user.username, "rfid", `Just added ${data.reader}.`);
return {success: true, message: `${data.reader} was just added.`};
} catch (error) {
createLog("error", user.username, "rfid", `there was an error adding ${data.reader}, ${error}`);
return {success: false, message: `${data.reader} encountered and error: ${error}`};
}
};

View File

@@ -0,0 +1,21 @@
import { db } from "../../../../database/dbclient.js";
import { rfidReaders } from "../../../../database/schema/rfidReaders.js";
import { returnRes } from "../../../globalUtils/routeDefs/returnRes.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
export const getReaders = async () => {
const { data, error } = await tryCatch(db.select().from(rfidReaders));
if (error) {
return returnRes(
false,
"There was an error getting the Readers",
"rfid",
"rfid",
"error",
error
);
}
return returnRes(true, "Current readers", "rfid", "rfid", "info", data);
};

View File

@@ -0,0 +1,29 @@
/**
* For a no read we just want to put up a notification to the rfid dashboard stating this reader did not respond with any tag data.
*/
import { createLog } from "../../logger/logger.js";
export const noRead = async (reader: string) => {
createLog(
"error",
"rfid",
"rfid",
`${reader} just had a no read please check for a tag and manually trigger a read.`
);
};
// noReadTimer.js
let timeout: any = null;
export const startNoReadTimer = (onTimeout: any, ms = 10000) => {
clearNoReadTimer(); // Always clear any previous timer
timeout = setTimeout(onTimeout, ms);
};
export const clearNoReadTimer = () => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
};

View File

@@ -0,0 +1,113 @@
import axios from "axios";
import { createLog } from "../../logger/logger.js";
import { db } from "../../../../database/dbclient.js";
import { rfidReaders } from "../../../../database/schema/rfidReaders.js";
import { eq } from "drizzle-orm";
import { noRead, startNoReadTimer } from "./noRead.js";
import { badRead } from "./readerControl.js";
const authData = btoa("admin:Zebra123!");
let token: string;
let ip: string;
export const readTags = async (reader: string) => {
/**
* Start the read for x seconds then auto stop it
*/
createLog("info", "rfid", "rfid", `Read was just triggered from ${reader}`);
const readers = await db
.select()
.from(rfidReaders)
.where(eq(rfidReaders.active, true));
if (readers.length === 0) {
createLog(
"error",
"rfid",
"rfid",
`There are no active readers right now maybe one forgot to be activated`
);
return;
}
// get the auth token
ip = readers.find((r) => r.reader === reader)?.readerIP as string;
// start the read
startRead(reader, ip);
// start the read
};
const getReaderToken = async () => {
try {
const res = await axios.get(`https://${ip}/cloud/localRestLogin`, {
headers: { Authorization: `Basic ${authData}` },
});
token = res.data.message;
} catch (error: any) {
createLog(
"error",
"rfid",
"rfid",
`There was an error Getting the token the read: ${error.response?.data.message}`
);
}
};
const startRead = async (reader: string, ip: string) => {
await getReaderToken();
try {
const res = await axios.put(
`https://${ip}/cloud/start`,
{},
{
headers: { Authorization: `Bearer ${token}` },
}
);
//console.log(res.data);
if (res.status === 200) {
// start the no read timer
startNoReadTimer(() => {
noRead(reader);
badRead(reader);
});
setTimeout(() => {
stopRead(reader, ip);
}, 5 * 1000);
}
// stop after 5 seconds
} catch (error: any) {
if (error.response?.data.code === 3) {
stopRead(reader, ip);
setTimeout(() => {
startRead(reader, ip);
}, 2 * 1000);
}
createLog(
"error",
"rfid",
"rfid",
`There was an error Starting the read: ${error.response?.data.message}`
);
}
};
export const stopRead = async (reader: string, ip: string) => {
await getReaderToken();
try {
const res = await axios.put(
`https://${ip}/cloud/stop`,
{},
{
headers: { Authorization: `Bearer ${token}` },
}
);
} catch (error: any) {
createLog(
"error",
"rfid",
"rfid",
`There was an error Stopping the read on ${reader}`
);
}
};

View File

@@ -0,0 +1,148 @@
/**
* While in production we will monitor the readers if we have not gotten a heartbeat in the last 5 min we will send a reboot command along with an email.
*/
import { eq, sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { rfidReaders } from "../../../../database/schema/rfidReaders.js";
import { createLog } from "../../logger/logger.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
export const newHeartBeat = async (reader: string) => {
/**
* When a heat beat is sent over for a reader we want to update the reader.
*/
try {
const heatBeat = await db
.update(rfidReaders)
.set({ lastHeartBeat: sql`NOW()` })
.where(eq(rfidReaders.reader, reader));
createLog(
"debug",
"rfid",
"rfid",
`${reader} just updated its heatBeat.`
);
return {
success: true,
message: `${reader} just updated its heatBeat.`,
};
} catch (error) {
createLog(
"error",
"rfid",
"rfid",
`${reader} encountered an error while updating the heatbeat, ${error}`
);
return {
success: false,
message: `${reader} encountered an error while updating the heatbeat, ${error}`,
};
}
};
export const badRead = async (reader: string) => {
/**
* When we have a bad read we want to make sure the reader shows this was well.
*/
try {
const badRead = await db
.update(rfidReaders)
.set({
lastTrigger: sql`NOW()`,
lastTriggerGood: false,
lastTagScanned: null,
badReads: sql`${rfidReaders.badReads} + 1`,
})
.where(eq(rfidReaders.reader, reader));
createLog(
"info",
"rfid",
"rfid",
`${reader} just Triggered a bad read.`
);
return {
success: true,
message: `${reader} just Triggered a bad read.`,
};
} catch (error) {
createLog(
"error",
"rfid",
"rfid",
`${reader} encountered an error while updating the heatbeat, ${error}`
);
return {
success: false,
message: `${reader} encountered an error while updating the heatbeat, ${error}`,
};
}
};
export const resetRatios = async (reader: string) => {
const { error } = await tryCatch(
db
.update(rfidReaders)
.set({
goodReads: 0,
badReads: 0,
})
.where(eq(rfidReaders.reader, reader))
);
if (error) {
createLog(
"error",
"rfid",
"rfid",
`${reader} encountered an error resetting the data.`
);
return {
success: false,
message: `${reader} encountered an error resetting the data.`,
};
}
createLog("info", "rfid", "rfid", `${reader} just had the tag data reset.`);
return {
success: true,
message: `${reader} just had the tag data reset.`,
};
};
export const goodRead = async (reader: string) => {
/**
* When we have a bad read we want to make sure the reader shows this was well.
*/
try {
const goodRead = await db
.update(rfidReaders)
.set({
lastTrigger: sql`NOW()`,
lastTriggerGood: true,
goodReads: sql`${rfidReaders.goodReads} + 1`,
})
.where(eq(rfidReaders.reader, reader));
createLog(
"info",
"rfid",
"rfid",
`${reader} just Triggered a good read.`
);
return {
success: true,
message: `${reader} just Triggered a good read.`,
};
} catch (error) {
createLog(
"error",
"rfid",
"rfid",
`${reader} encountered an error while updating the heatbeat, ${error}`
);
return {
success: false,
message: `${reader} encountered an error while updating the heatbeat, ${error}`,
};
}
};

View File

@@ -0,0 +1,3 @@
/**
* we will monitor shipped out pallets every hour if they get shipped out
*/

View File

@@ -0,0 +1,3 @@
/**
* station 1 will just check for 10 tags
*/

View File

@@ -0,0 +1,4 @@
/**
* we will have 3 reader points here station2.1 will require 10 tags, 2.2 and 2.3 will require 1
*
*/

View File

@@ -0,0 +1,68 @@
/**
* Phase 1 we link the tag to the line only the line3.x where x is the line number
* Phase 2 we will generate a label to be reprinted at staion 4
*/
import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { rfidReaders } from "../../../../../database/schema/rfidReaders.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import type { TagData } from "../tagData.js";
import { tagStuff } from "../tags/crudTag.js";
export const station3Tags = async (tagData: TagData[]) => {
/**
* Add the new tag to the reader so we know what was really here
*/
const { error } = await tryCatch(
db
.update(rfidReaders)
.set({ lastTagScanned: tagData[0].tag })
.where(eq(rfidReaders.reader, tagData[0].reader))
);
if (error) {
createLog(
"error",
"rfid",
"rfid",
`${tagData[0].reader} encountered and error adding ${tagData[0].tag}.`
);
}
createLog(
"info",
"rfid",
"rfid",
`${tagData[0].reader} has a ${tagData[0].tag} will post it :)`
);
// make sure we only have one tag or dont update
if (tagData.length != 1) {
createLog(
"error",
"rfid",
"rfid",
`There are ${tagData.length} tags, and ${tagData[0].reader} only allows 1 tag to create a label.`
);
// get tag data
for (let i = 0; i < tagData.length; i++) {
const tag = {
...tagData[i],
runningNr: 0,
lastareaIn: "NeedsChecked",
};
tagStuff([tag]);
}
} else {
//console.log("Generate the label and link it to the tag.");
const tag = { ...tagData[0], runningNr: 0 };
const tagdata = await tagStuff([tag]);
createLog(
"debug",
"rfid",
"rfid",
"Generate a label and link it to this tag."
);
}
};

View File

@@ -0,0 +1,214 @@
/**
* Phase 1 we will just follow the logic of printing a label when we are told requested to based on this tag.
* Phase 2 we will just reprint the tag that was generated at the line
*/
import os from "os";
import { createLog } from "../../../logger/logger.js";
import { labelingProcess } from "../../../ocp/controller/labeling/labelProcess.js";
import type { TagData } from "../tagData.js";
import { tagStuff } from "../tags/crudTag.js";
import { sendEmail } from "../../../notifications/controller/sendMail.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { db } from "../../../../../database/dbclient.js";
import { rfidTags } from "../../../../../database/schema/rfidTags.js";
import { and, eq, gte, ne, sql } from "drizzle-orm";
import { rfidReaders } from "../../../../../database/schema/rfidReaders.js";
import { shouldSkipByCooldown } from "../../utils/rateLimit.js";
import { autoLabelCreated } from "../../../ocp/controller/labeling/labelRatio.js";
export const wrapperStuff = async (tagData: any) => {
console.log("WrapperTag", tagData[0].tag);
if (shouldSkipByCooldown("wrapperDouble Scan", 10)) return;
// update the reader with the last tag read.
const { error } = await tryCatch(
db
.update(rfidReaders)
.set({ lastTagScanned: tagData[0].tag })
.where(eq(rfidReaders.reader, tagData[0].reader))
);
if (error) {
createLog(
"error",
"rfid",
"rfid",
`${tagData[0].reader} encountered and error adding ${tagData[0].tag}.`
);
}
if (tagData.length != 1) {
createLog(
"error",
"rfid",
"rfid",
`There are ${tagData.length} tags and this ${
tagData[0].reader
} only allows 1 tag to create a label: tag ${tagData
.map((o: any) => `${o.tag}`)
.join(",\n ")}`
);
const tag = { ...tagData[0], runningNr: 0 };
//tagStuff([tag]);
monitorChecks();
return;
} else {
if (!tagData) {
createLog("error", "rfid", "rfid", `No tagData was grabbed.`);
monitorChecks();
}
const { data: tagdata, error: tagError } = await tryCatch(
db
.select()
.from(rfidTags)
.where(
and(
eq(rfidTags.tag, tagData[0].tag),
gte(
rfidTags.lastRead,
sql.raw(`NOW() - INTERVAL '6 hours'`)
),
ne(rfidTags.lastareaIn, "wrapper1")
)
)
);
console.log("DB Data:", tagdata);
if (tagError) {
return {
success: false,
message: `There was an error getting the tag data for ${tagData[0].tag}.`,
};
}
const checkTag: any = tagdata;
if (checkTag.length === 0) {
createLog(
"error",
"rfid",
"rfid",
`${tagData[0].tag} is not currently registered to a line please validate the pallet and manually print.`
);
return {
success: false,
message:
"There is no tag in the system please manually print..",
};
}
if (checkTag[0]?.lastareaIn === "NeedsChecked") {
createLog(
"error",
"rfid",
"rfid",
`The tags on this pallet need to be checked as it was flagged as more than 1 tag number. please validate and looks at both sides.`
);
for (let i = 0; i < tagData.length; i++) {
const tag = { ...tagData[i], runningNr: 0 };
tagStuff([tag]);
}
monitorChecks();
return {
success: false,
message:
"The tags on this pallet need to be checked as it was flagged as more than 1 tag number. please validate and looks at both sides.",
};
}
const lines = checkTag[0]?.lastareaIn.includes("line3");
if (!lines) {
createLog(
"error",
"rfid",
"rfid",
`${tagData[0].tag}, Did not come from a line please check the pallet and manually print the label.`
);
tagStuff(tagData);
monitorChecks();
return {
success: false,
message: `${tagData[0].tag}, Did not come from a line please check the pallet and manually print the label.`,
};
}
if (lines[0]?.runningNumber) {
createLog(
"info",
"rfid",
"rfid",
`Reprint label ${lines[0]?.runningNumber}`
);
} else {
createLog(
"info",
"rfid",
"rfid",
`A new label will be created and linked to this ${tagData[0].tag} tag`
);
const lineNum = parseInt(
checkTag[0]?.lastareaIn.replace("line3.", "")
);
createLog(
"info",
"rfid",
"rfid",
`Line to be checked for printing: ${lineNum}`
);
const genlabel = await labelingProcess({
line: lineNum.toString(),
});
autoLabelCreated();
console.log(genlabel);
if (genlabel?.success) {
const createPrintData = {
...tagData[0],
runnungNumber: parseInt(genlabel.data?.SSCC.slice(10, -1)),
};
tagStuff([createPrintData]);
}
}
}
};
export const monitorErrorTags: any = [];
const monitorChecks = () => {
/**
* If we have to check more than 10 tags in an hour send an email to alert everyone.
*/
const now = new Date(Date.now()).getTime();
monitorErrorTags.push({ timestamp: now });
// remove if creater than 1 hour
const removalTiming = now - 1 * 60 * 60 * 1000; // 1 hour
while (
monitorErrorTags > 0 &&
monitorErrorTags[0].timestamp < removalTiming
) {
monitorErrorTags.shift();
}
if (monitorErrorTags > 10) {
// send the email.
const emailData = {
email: "blake.matthes@alpla.com", // should be moved to the db so it can be reused.
subject: `${os.hostname()} has had ${monitorErrorTags}.`,
template: "toManyManualPrints",
context: {
count: monitorErrorTags,
hours: "1",
},
};
sendEmail(emailData);
}
};
// if (
// !Array.isArray(tagdata) &&
// tagdata?.some((n: any) => n.lastareaIn.includes("line3"))
// ) {
// createLog(
// "error",
// "rfid",
// "rfid",
// `Data passed over is not an array.`
// );
// return;
// }

View File

@@ -0,0 +1,68 @@
import { station3Tags } from "./stations/station3.js";
import { wrapperStuff } from "./stations/wrappers.js";
export type TagData = {
tagHex: string;
reader: string;
tag: string;
timeStamp: Date;
antenna: number;
tagStrength: number;
lastareaIn?: string;
runningNumber?: number;
};
export const tagData = async (data: TagData[]) => {
/**
* We will always update a tag
*/
if (monitorTagsdata.includes(data[0].tag)) {
}
// dyco wall makes sure we have 10 tags
const station1 = data.some((n) => n.reader.includes("reader1"));
// by the dyco infeed
const station2 = data.some((n) => n.reader.includes("station2"));
// at the end of each line
const station3 = data.some((n) => n.reader.includes("line3"));
// at the wrapper
const wrappers = data.some((n) => n.reader.includes("wrapper"));
// station checks
if (station1 && data.length != 10) {
console.log(`There are only ${data.length}`);
}
if (station2) {
console.log(`There are only ${data.length}`);
}
if (station3) {
station3Tags(data);
}
if (wrappers) {
wrapperStuff(data);
}
};
const monitorTagsdata: any = [];
const monitorTags = (tag: string) => {
/**
* If we have to check more than 10 tags in an hour send an email to alert everyone.
*/
const now = new Date(Date.now()).getTime();
monitorTagsdata.push({ timestamp: now, tag: tag });
// remove if creater than 1 hour
const removalTiming = now - 2 * 60 * 1000; // 2 min
while (
monitorTagsdata > 0 &&
monitorTagsdata[0].timestamp < removalTiming
) {
monitorTagsdata.shift();
}
};

View File

@@ -0,0 +1,108 @@
import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { rfidTags } from "../../../../../database/schema/rfidTags.js";
import type { TagData } from "../tagData.js";
import { createLog } from "../../../logger/logger.js";
type ReturnTag = {
success: boolean;
tag: any;
error: any;
};
export const tagStuff = async (tagData: TagData[]): Promise<any> => {
const tags = await db.select().from(rfidTags);
// look through each tag and either add it to the db or update the area and other relevent data.
for (let i = 0; i < tagData.length; i++) {
// check if the tag already exists
const tag = tags.filter((n) => n.tagHex === tagData[i].tagHex);
if (tag.length === 0) {
// add new tag
const newTag = {
tagHex: tagData[i].tagHex,
tag: tagData[i].tag,
lastRead: new Date(tagData[i].timeStamp),
counts: [{ area: tagData[i].reader, timesHere: 1 }], //jsonb("counts").notNull(), //.default([{area: 1, timesHere: 5}]).notNull(),
lastareaIn: tagData[i].reader,
antenna: tagData[i].antenna,
tagStrength: tagData[i].tagStrength,
runningNumber: tagData[i].runningNumber
? tagData[i].runningNumber
: null,
};
try {
// insert the tag with the onConflict update the tag
const tag = await db
.insert(rfidTags)
.values(newTag)
.onConflictDoUpdate({
target: rfidTags.tagHex,
set: newTag,
})
.returning({
tag: rfidTags.tag,
runningNumber: rfidTags.runningNumber,
counts: rfidTags.counts,
lastareaIn: rfidTags.lastareaIn,
});
createLog("info", "rfid", "rfid", `Tags were jusdt updated.`);
return { success: true, tag };
} catch (error) {
createLog("error", "rfid", "rfid", `${JSON.stringify(error)}`);
return { success: false, error };
}
} else {
// update tag
//console.log("Updating existing tag");
// make sure we actually have an array here
const countsArray =
(tag[0]?.counts as { area: string; timesHere: number }[]) ?? [];
// check if the reader exists on the array
const areaExists = countsArray.some(
(t) => t.area === tagData[0].reader
);
// run the update on the array
const updateCount = areaExists
? countsArray.map((t) => {
if (t.area === tagData[0].reader) {
return { ...t, timesHere: t.timesHere + 1 };
} else {
return {
...t,
area: tagData[i].reader,
timesHere: 1,
};
}
})
: [...countsArray, { area: tagData[i].reader, timesHere: 1 }];
const updateTag = {
lastRead: new Date(tagData[i].timeStamp),
counts: updateCount, //jsonb("counts").notNull(), //.default([{area: 1, timesHere: 5}]).notNull(),
lastareaIn: tagData[i].reader,
antenna: tagData[i].antenna,
tagStrength: tagData[i].tagStrength,
};
try {
await db
.update(rfidTags)
.set(updateTag)
.where(eq(rfidTags.tagHex, tagData[0].tagHex))
.returning({
tag: rfidTags.tag,
runningNumber: rfidTags.runningNumber,
counts: rfidTags.counts,
lastareaIn: rfidTags.lastareaIn,
});
createLog("info", "rfid", "rfid", `Tags were jusdt updated.`);
return { success: true, tag };
} catch (error) {
createLog("error", "rfid", "rfid", `${JSON.stringify(error)}`);
return { success: false, error };
}
}
}
};

View File

@@ -0,0 +1,63 @@
import { db } from "../../../../../database/dbclient.js";
import { rfidTags } from "../../../../../database/schema/rfidTags.js";
import { createLog } from "../../../logger/logger.js";
export const manualTag = async (
tag: string,
area: string,
runningNr?: any | null
) => {
/**
* we only allow tags to be manually added from the wrappers
*/
// create the proper string
const number = tag.toString().padStart(9, "0");
const tagString = `ALPLA${number}`;
const newTag = {
tagHex: Buffer.from(tagString, "utf8").toString("hex").toUpperCase(),
tag: tagString,
lastRead: new Date(Date.now()),
counts: [{ area: area, timesHere: 1 }], //jsonb("counts").notNull(), //.default([{area: 1, timesHere: 5}]).notNull(),
lastareaIn: area,
antenna: 0,
tagStrength: -1,
};
try {
// insert the tag with the onConflict update the tag
const tag = await db
.insert(rfidTags)
.values(newTag)
.returning({
tag: rfidTags.tag,
runningNumber: runningNr ? runningNr : rfidTags.runningNumber,
counts: rfidTags.counts,
lastareaIn: rfidTags.lastareaIn,
})
.onConflictDoUpdate({
target: rfidTags.tagHex,
set: {
lastRead: new Date(Date.now()),
lastareaIn: area,
},
});
createLog(
"info",
"rfid",
"rfid",
`Tags were just added, and label printed.`
);
// do the label thing here
return {
success: true,
message: `${tagString} was just added, and label printed.`,
data: tag,
};
} catch (error) {
createLog("error", "rfid", "rfid", `${JSON.stringify(error)}`);
return {
success: false,
message: `Error creating a new tag`,
data: error,
};
}
};