feat(lstv2 move): moved lstv2 into this app to keep them combined and easier to maintain
This commit is contained in:
34
lstV2/server/services/rfid/controller/addReader.ts
Normal file
34
lstV2/server/services/rfid/controller/addReader.ts
Normal 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}`};
|
||||
}
|
||||
};
|
||||
21
lstV2/server/services/rfid/controller/getReaders.ts
Normal file
21
lstV2/server/services/rfid/controller/getReaders.ts
Normal 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);
|
||||
};
|
||||
29
lstV2/server/services/rfid/controller/noRead.ts
Normal file
29
lstV2/server/services/rfid/controller/noRead.ts
Normal 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;
|
||||
}
|
||||
};
|
||||
113
lstV2/server/services/rfid/controller/readTags.ts
Normal file
113
lstV2/server/services/rfid/controller/readTags.ts
Normal 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}`
|
||||
);
|
||||
}
|
||||
};
|
||||
148
lstV2/server/services/rfid/controller/readerControl.ts
Normal file
148
lstV2/server/services/rfid/controller/readerControl.ts
Normal 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}`,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* we will monitor shipped out pallets every hour if they get shipped out
|
||||
*/
|
||||
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* station 1 will just check for 10 tags
|
||||
*/
|
||||
@@ -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
|
||||
*
|
||||
*/
|
||||
68
lstV2/server/services/rfid/controller/stations/station3.ts
Normal file
68
lstV2/server/services/rfid/controller/stations/station3.ts
Normal 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."
|
||||
);
|
||||
}
|
||||
};
|
||||
214
lstV2/server/services/rfid/controller/stations/wrappers.ts
Normal file
214
lstV2/server/services/rfid/controller/stations/wrappers.ts
Normal 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;
|
||||
// }
|
||||
68
lstV2/server/services/rfid/controller/tagData.ts
Normal file
68
lstV2/server/services/rfid/controller/tagData.ts
Normal 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();
|
||||
}
|
||||
};
|
||||
108
lstV2/server/services/rfid/controller/tags/crudTag.ts
Normal file
108
lstV2/server/services/rfid/controller/tags/crudTag.ts
Normal 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 };
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
63
lstV2/server/services/rfid/controller/tags/manualTag.ts
Normal file
63
lstV2/server/services/rfid/controller/tags/manualTag.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
};
|
||||
33
lstV2/server/services/rfid/rfidService.ts
Normal file
33
lstV2/server/services/rfid/rfidService.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { OpenAPIHono } from "@hono/zod-openapi";
|
||||
|
||||
import mgtEvents from "./route/mgtEvents.js";
|
||||
import tagInfo from "./route/tagInfo.js";
|
||||
import addReader from "./route/addReader.js";
|
||||
import updateReader from "./route/updateReader.js";
|
||||
import manualTrigger from "./route/manualTagRead.js";
|
||||
import getReaders from "./route/getReaders.js";
|
||||
import resetRatio from "./route/resetRatio.js";
|
||||
import { monitorRfidTags } from "./utils/monitorTags.js";
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
const routes = [
|
||||
mgtEvents,
|
||||
tagInfo,
|
||||
addReader,
|
||||
updateReader,
|
||||
manualTrigger,
|
||||
getReaders,
|
||||
resetRatio,
|
||||
] as const;
|
||||
|
||||
// app.route("/server", modules);
|
||||
const appRoutes = routes.forEach((route) => {
|
||||
app.route("/rfid", route);
|
||||
});
|
||||
|
||||
// monitor every 5 min tags older than 6 hours to remove the line they were so we reduce the risk of them being labeled with the wrong info
|
||||
setInterval(() => {
|
||||
monitorRfidTags();
|
||||
}, 5 * 1000 * 60);
|
||||
|
||||
export default app;
|
||||
64
lstV2/server/services/rfid/route/addReader.ts
Normal file
64
lstV2/server/services/rfid/route/addReader.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
|
||||
import { addReader } from "../controller/addReader.js";
|
||||
import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
|
||||
import { responses } from "../../../globalUtils/routeDefs/responses.js";
|
||||
import type { User } from "../../../types/users.js";
|
||||
import { verify } from "hono/jwt";
|
||||
import { apiHit } from "../../../globalUtils/apiHits.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
export const ReaderBody = z.object({
|
||||
reader: z.string().openapi({ example: "wrapper1" }),
|
||||
readerIP: z.string().openapi({ example: "192.168.1.52" }),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["rfid"],
|
||||
summary: "Add new reader",
|
||||
method: "post",
|
||||
path: "/addreader",
|
||||
middleware: authMiddleware,
|
||||
description: "Adding in a new reader to add to the network.",
|
||||
request: {
|
||||
body: { content: { "application/json": { schema: ReaderBody } } },
|
||||
},
|
||||
responses: responses(),
|
||||
}),
|
||||
async (c) => {
|
||||
const body = await c.req.json();
|
||||
const authHeader = c.req.header("Authorization");
|
||||
apiHit(c, { endpoint: "/addreader", lastBody: body });
|
||||
const token = authHeader?.split("Bearer ")[1] || "";
|
||||
let user: User;
|
||||
|
||||
try {
|
||||
const payload = await verify(token, process.env.JWT_SECRET!);
|
||||
user = payload.user as User;
|
||||
} catch (error) {
|
||||
return c.json({ message: "Unauthorized" }, 401);
|
||||
}
|
||||
|
||||
try {
|
||||
const addingReader = await addReader(body, user);
|
||||
return c.json(
|
||||
{
|
||||
success: addingReader.success,
|
||||
message: addingReader.message,
|
||||
},
|
||||
200
|
||||
);
|
||||
} catch (error) {
|
||||
return c.json(
|
||||
{
|
||||
success: false,
|
||||
message: `${body.name} encountered an error while trying to be added`,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
43
lstV2/server/services/rfid/route/getReaders.ts
Normal file
43
lstV2/server/services/rfid/route/getReaders.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
|
||||
import { addReader } from "../controller/addReader.js";
|
||||
import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
|
||||
import { responses } from "../../../globalUtils/routeDefs/responses.js";
|
||||
import type { User } from "../../../types/users.js";
|
||||
|
||||
import { apiHit } from "../../../globalUtils/apiHits.js";
|
||||
import { tryCatch } from "../../../globalUtils/tryCatch.js";
|
||||
import { getReaders } from "../controller/getReaders.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
export const ReaderBody = z.object({
|
||||
reader: z.string().openapi({ example: "wrapper1" }),
|
||||
readerIP: z.string().openapi({ example: "192.168.1.52" }),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["rfid"],
|
||||
summary: "Get readers",
|
||||
method: "get",
|
||||
path: "/getreaders",
|
||||
responses: responses(),
|
||||
}),
|
||||
async (c: any) => {
|
||||
apiHit(c, { endpoint: "/getreaders" });
|
||||
|
||||
const { data, error } = await tryCatch(getReaders());
|
||||
|
||||
if (error) {
|
||||
return c.json({
|
||||
error,
|
||||
});
|
||||
}
|
||||
|
||||
return c.json({
|
||||
data,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
57
lstV2/server/services/rfid/route/manualTagEnter.ts
Normal file
57
lstV2/server/services/rfid/route/manualTagEnter.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
//http://usday1vms006:4000/api/v1/zebra/wrapper1
|
||||
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
|
||||
import { responses } from "../../../globalUtils/routeDefs/responses.js";
|
||||
import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
|
||||
import { manualTag } from "../controller/tags/manualTag.js";
|
||||
import { apiHit } from "../../../globalUtils/apiHits.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
const RequestBody = z.object({
|
||||
tagNumber: z.string().openapi({ example: "2541" }),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["rfid"],
|
||||
summary: "Post a manual Tag",
|
||||
method: "post",
|
||||
path: "/manualtag",
|
||||
middleware: authMiddleware,
|
||||
request: {
|
||||
body: { content: { "application/json": { schema: RequestBody } } },
|
||||
},
|
||||
responses: responses(),
|
||||
}),
|
||||
async (c) => {
|
||||
const body =
|
||||
(await c.req.json()) ??
|
||||
c.json(
|
||||
{
|
||||
success: false,
|
||||
message: `Please check that you are sending over a json object`,
|
||||
},
|
||||
400
|
||||
);
|
||||
|
||||
apiHit(c, { endpoint: "/manualtag" });
|
||||
try {
|
||||
const tag = await manualTag(body.tag, body.area);
|
||||
return c.json(
|
||||
{ success: tag.success, message: tag.message, data: tag.data },
|
||||
200
|
||||
);
|
||||
} catch (error) {
|
||||
return c.json(
|
||||
{
|
||||
success: true,
|
||||
message: `There was an error with entering a new tag`,
|
||||
error,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
47
lstV2/server/services/rfid/route/manualTagRead.ts
Normal file
47
lstV2/server/services/rfid/route/manualTagRead.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
//http://usday1vms006:4000/api/v1/zebra/wrapper1
|
||||
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
|
||||
import { responses } from "../../../globalUtils/routeDefs/responses.js";
|
||||
import { readTags } from "../controller/readTags.js";
|
||||
import { apiHit } from "../../../globalUtils/apiHits.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
const ParamsSchema = z.object({
|
||||
reader: z
|
||||
.string()
|
||||
.min(3)
|
||||
.openapi({
|
||||
param: {
|
||||
name: "reader",
|
||||
in: "path",
|
||||
},
|
||||
example: "1212121",
|
||||
}),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["rfid"],
|
||||
summary: "Manual triggers the read function",
|
||||
method: "post",
|
||||
path: "/manualtrigger/{reader}",
|
||||
request: {
|
||||
params: ParamsSchema,
|
||||
},
|
||||
responses: responses(),
|
||||
}),
|
||||
async (c) => {
|
||||
const { reader } = c.req.valid("param");
|
||||
const manualTrigger = await readTags(reader);
|
||||
apiHit(c, { endpoint: `/manualtrigger/${reader}` });
|
||||
return c.json(
|
||||
{
|
||||
success: true,
|
||||
message: `A Manaul trigger was done on ${reader}`,
|
||||
},
|
||||
200
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
81
lstV2/server/services/rfid/route/mgtEvents.ts
Normal file
81
lstV2/server/services/rfid/route/mgtEvents.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
//http://usday1vms006:4000/api/v1/zebra/wrapper1
|
||||
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
|
||||
import { readTags } from "../controller/readTags.js";
|
||||
import { createLog } from "../../logger/logger.js";
|
||||
import { responses } from "../../../globalUtils/routeDefs/responses.js";
|
||||
import { newHeartBeat } from "../controller/readerControl.js";
|
||||
import { apiHit } from "../../../globalUtils/apiHits.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
let lastGpiTimestamp = 0;
|
||||
|
||||
const ParamsSchema = z.object({
|
||||
reader: z
|
||||
.string()
|
||||
.min(3)
|
||||
.openapi({
|
||||
param: {
|
||||
name: "reader",
|
||||
in: "path",
|
||||
},
|
||||
example: "1212121",
|
||||
}),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["rfid"],
|
||||
summary: "Post info from the reader",
|
||||
method: "post",
|
||||
path: "/mgtevents/{reader}",
|
||||
request: {
|
||||
params: ParamsSchema,
|
||||
},
|
||||
responses: responses(),
|
||||
}),
|
||||
async (c) => {
|
||||
const { reader } = c.req.valid("param");
|
||||
const body = await c.req.json();
|
||||
apiHit(c, { endpoint: `/mgtevents/${reader}` });
|
||||
if (body.type === "heartbeat") {
|
||||
const heart = await newHeartBeat(reader);
|
||||
return c.json(
|
||||
{ success: heart.success, message: heart.message },
|
||||
200
|
||||
);
|
||||
}
|
||||
|
||||
if (body.type === "gpi" && body.data.state === "HIGH") {
|
||||
const eventTimestamp = new Date(body.timestamp).getTime(); // Convert ISO timestamp to milliseconds
|
||||
if (eventTimestamp - lastGpiTimestamp > 30 * 1000) {
|
||||
// Check if it's been more than 2ms
|
||||
lastGpiTimestamp = eventTimestamp; // Update last seen timestamp
|
||||
|
||||
createLog(
|
||||
"info",
|
||||
"rfid",
|
||||
"rfid",
|
||||
`${reader} is reading a tag.`
|
||||
);
|
||||
await readTags(reader);
|
||||
} else {
|
||||
createLog(
|
||||
"debug",
|
||||
"rfid",
|
||||
"rfid",
|
||||
`A new trigger from ${reader} was to soon`
|
||||
);
|
||||
lastGpiTimestamp = eventTimestamp;
|
||||
}
|
||||
|
||||
//console.log(body);
|
||||
}
|
||||
|
||||
return c.json(
|
||||
{ success: true, message: `New info from ${reader}` },
|
||||
200
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
54
lstV2/server/services/rfid/route/resetRatio.ts
Normal file
54
lstV2/server/services/rfid/route/resetRatio.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
|
||||
import { addReader } from "../controller/addReader.js";
|
||||
import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
|
||||
import { responses } from "../../../globalUtils/routeDefs/responses.js";
|
||||
import type { User } from "../../../types/users.js";
|
||||
import { verify } from "hono/jwt";
|
||||
import { apiHit } from "../../../globalUtils/apiHits.js";
|
||||
import { resetRatios } from "../controller/readerControl.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
export const ReaderBody = z.object({
|
||||
reader: z.string().openapi({ example: "wrapper1" }),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["rfid"],
|
||||
summary: "Resets the ratio on the reader",
|
||||
method: "post",
|
||||
path: "/resetRatio",
|
||||
//middleware: authMiddleware,
|
||||
//description: "Adding in a new reader to add to the network.",
|
||||
request: {
|
||||
body: { content: { "application/json": { schema: ReaderBody } } },
|
||||
},
|
||||
responses: responses(),
|
||||
}),
|
||||
async (c) => {
|
||||
const body = await c.req.json();
|
||||
apiHit(c, { endpoint: "/resetRatio", lastBody: body });
|
||||
|
||||
try {
|
||||
const reset = await resetRatios(body.reader);
|
||||
return c.json(
|
||||
{
|
||||
success: reset.success,
|
||||
message: reset.message,
|
||||
},
|
||||
200
|
||||
);
|
||||
} catch (error) {
|
||||
return c.json(
|
||||
{
|
||||
success: false,
|
||||
message: `${body.name} encountered an error while trying to reset the readers ratio`,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
98
lstV2/server/services/rfid/route/tagInfo.ts
Normal file
98
lstV2/server/services/rfid/route/tagInfo.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
//http://usday1vms006:4000/api/v1/zebra/wrapper1
|
||||
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
|
||||
import { ConsoleLogWriter } from "drizzle-orm";
|
||||
import { tagData } from "../controller/tagData.js";
|
||||
import { responses } from "../../../globalUtils/routeDefs/responses.js";
|
||||
import { clearNoReadTimer, noRead } from "../controller/noRead.js";
|
||||
import { badRead, goodRead } from "../controller/readerControl.js";
|
||||
import { createLog } from "../../logger/logger.js";
|
||||
import { tryCatch } from "../../../globalUtils/tryCatch.js";
|
||||
import { stopRead } from "../controller/readTags.js";
|
||||
import { apiHit } from "../../../globalUtils/apiHits.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
const ParamsSchema = z.object({
|
||||
reader: z
|
||||
.string()
|
||||
.min(3)
|
||||
.openapi({
|
||||
param: {
|
||||
name: "reader",
|
||||
in: "path",
|
||||
},
|
||||
example: "1212121",
|
||||
}),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["rfid"],
|
||||
summary: "Tag info posted from the reader.",
|
||||
method: "post",
|
||||
path: "/taginfo/{reader}",
|
||||
request: {
|
||||
params: ParamsSchema,
|
||||
},
|
||||
responses: responses(),
|
||||
}),
|
||||
async (c) => {
|
||||
const { reader } = c.req.valid("param");
|
||||
createLog("info", "rfid", "rfid", `${reader} is sending us data.`);
|
||||
let tagdata: any = [];
|
||||
const { data: body, error: bodyError } = await tryCatch(c.req.json());
|
||||
apiHit(c, { endpoint: `/taginfo/${reader}`, lastBody: body });
|
||||
if (bodyError) {
|
||||
return c.json({ success: false, message: "missing data" }, 400);
|
||||
}
|
||||
//console.log(`Tag: ${Buffer.from(body.idHex, "hex").toString("utf-8")}, ${body[key].data.idHex}`);
|
||||
|
||||
for (let i = 0; i < body.length; i++) {
|
||||
const tag = Buffer.from(body[i].data.idHex, "hex").toString(
|
||||
"utf-8"
|
||||
);
|
||||
// console.log(
|
||||
// "Raw value:",
|
||||
// body[i].data.peakRssi,
|
||||
// "Parsed:",
|
||||
// parseInt(body[i].data.peakRssi)
|
||||
// );
|
||||
if (
|
||||
tag.includes("ALPLA") &&
|
||||
parseInt(body[i].data.peakRssi) < -30
|
||||
) {
|
||||
tagdata = [
|
||||
...tagdata,
|
||||
{
|
||||
tagHex: body[i].data.idHex,
|
||||
reader: reader,
|
||||
tag: tag,
|
||||
timeStamp: body[i].timestamp,
|
||||
antenna: body[i].data.antenna,
|
||||
tagStrength: body[i].data.peakRssi,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if (tagdata.length === 0) {
|
||||
// noRead(reader);
|
||||
// badRead(reader);
|
||||
return c.json(
|
||||
{ success: false, message: `There were no tags scanned.` },
|
||||
200
|
||||
);
|
||||
} else {
|
||||
tagData(tagdata);
|
||||
goodRead(reader);
|
||||
clearNoReadTimer();
|
||||
|
||||
return c.json(
|
||||
{ success: true, message: `New info from ${reader}` },
|
||||
200
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
65
lstV2/server/services/rfid/route/updateReader.ts
Normal file
65
lstV2/server/services/rfid/route/updateReader.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
|
||||
import { addReader } from "../controller/addReader.js";
|
||||
import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
|
||||
import { responses } from "../../../globalUtils/routeDefs/responses.js";
|
||||
import type { User } from "../../../types/users.js";
|
||||
import { verify } from "hono/jwt";
|
||||
import { apiHit } from "../../../globalUtils/apiHits.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
export const ReaderBody = z.object({
|
||||
reader: z.string().openapi({ example: "wrapper1" }),
|
||||
readerIP: z.string().openapi({ example: "192.168.1.52" }),
|
||||
active: z.boolean().optional().openapi({ example: true }),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["rfid"],
|
||||
summary: "Add new reader",
|
||||
method: "patch",
|
||||
path: "/updatereader",
|
||||
middleware: authMiddleware,
|
||||
description: "Updates the reader data..",
|
||||
request: {
|
||||
body: { content: { "application/json": { schema: ReaderBody } } },
|
||||
},
|
||||
responses: responses(),
|
||||
}),
|
||||
async (c) => {
|
||||
const body = await c.req.json();
|
||||
const authHeader = c.req.header("Authorization");
|
||||
apiHit(c, { endpoint: `/updatereader`, lastBody: body });
|
||||
const token = authHeader?.split("Bearer ")[1] || "";
|
||||
let user: User;
|
||||
|
||||
try {
|
||||
const payload = await verify(token, process.env.JWT_SECRET!);
|
||||
user = payload.user as User;
|
||||
} catch (error) {
|
||||
return c.json({ message: "Unauthorized" }, 401);
|
||||
}
|
||||
|
||||
try {
|
||||
const addingReader = await addReader(body, user);
|
||||
return c.json(
|
||||
{
|
||||
success: addingReader.success,
|
||||
message: addingReader.message,
|
||||
},
|
||||
200
|
||||
);
|
||||
} catch (error) {
|
||||
return c.json(
|
||||
{
|
||||
success: false,
|
||||
message: `${body.name} encountered an error while trying to be added`,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
22
lstV2/server/services/rfid/utils/monitorTags.ts
Normal file
22
lstV2/server/services/rfid/utils/monitorTags.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { and, lt, ne, sql } from "drizzle-orm";
|
||||
import { db } from "../../../../database/dbclient.js";
|
||||
import { rfidTags } from "../../../../database/schema/rfidTags.js";
|
||||
import { tryCatch } from "../../../globalUtils/tryCatch.js";
|
||||
|
||||
/**
|
||||
* This will monitor tags that are older than 6hours and are still linked to a line.
|
||||
* it will then remove the line from the last area in as we will asume it dose not exist.
|
||||
*/
|
||||
export const monitorRfidTags = async () => {
|
||||
const { data, error } = await tryCatch(
|
||||
db
|
||||
.update(rfidTags)
|
||||
.set({ lastareaIn: "miss scanned" })
|
||||
.where(
|
||||
and(
|
||||
ne(rfidTags.lastareaIn, "wrapper1"), // not equal to 'wrapper1'
|
||||
lt(rfidTags.lastRead, sql`NOW() - INTERVAL '6 hours'`) // older than 6 hours)
|
||||
)
|
||||
)
|
||||
);
|
||||
};
|
||||
19
lstV2/server/services/rfid/utils/rateLimit.ts
Normal file
19
lstV2/server/services/rfid/utils/rateLimit.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
const lastRunMap = new Map();
|
||||
|
||||
/**
|
||||
* Returns true if the function with a given key was called within the last `seconds`.
|
||||
* @param {string} key - Unique key to track cooldown per function/context.
|
||||
* @param {number} seconds - Cooldown in seconds.
|
||||
* @returns {boolean} - true if should skip (still in cooldown), false if allowed.
|
||||
*/
|
||||
export function shouldSkipByCooldown(key: any, seconds: any) {
|
||||
const now = Date.now();
|
||||
const cooldown = seconds * 1000;
|
||||
|
||||
if (lastRunMap.has(key) && now - lastRunMap.get(key) < cooldown) {
|
||||
return true;
|
||||
}
|
||||
|
||||
lastRunMap.set(key, now);
|
||||
return false;
|
||||
}
|
||||
Reference in New Issue
Block a user