feat(rfid): work on the readers and there functions

This commit is contained in:
2025-03-27 21:08:05 -05:00
parent f9f68ce969
commit b5de6445b3
9 changed files with 275 additions and 134 deletions

View File

@@ -2,6 +2,13 @@
* 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. * 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) => { export const noRead = async (reader: string) => {
console.log(`${reader} just had a no read please check for a tag and manually trigger a read.`); createLog(
"error",
"rfid",
"rifd",
`${reader} just had a no read please check for a tag and manually trigger a read.`
);
}; };

View File

@@ -29,15 +29,18 @@ export const readTags = async (reader: string) => {
// get the auth token // get the auth token
ip = readers.find((r) => r.reader === reader)?.readerIP as string; ip = readers.find((r) => r.reader === reader)?.readerIP as string;
// start the read
startRead();
// start the read
};
const getReaderToken = async () => {
try { try {
const res = await axios.get(`https://${ip}/cloud/localRestLogin`, { const res = await axios.get(`https://${ip}/cloud/localRestLogin`, {
headers: { Authorization: `Basic ${authData}` }, headers: { Authorization: `Basic ${authData}` },
}); });
token = res.data.message; token = res.data.message;
// start the read
startRead();
} catch (error: any) { } catch (error: any) {
console.log(error);
createLog( createLog(
"error", "error",
"rfid", "rfid",
@@ -45,11 +48,10 @@ export const readTags = async (reader: string) => {
`There was an error Getting the token the read: ${error.response?.data.message}` `There was an error Getting the token the read: ${error.response?.data.message}`
); );
} }
// start the read
}; };
const startRead = async () => { const startRead = async () => {
await getReaderToken();
try { try {
const res = await axios.put( const res = await axios.put(
`https://${ip}/cloud/start`, `https://${ip}/cloud/start`,
@@ -64,12 +66,12 @@ const startRead = async () => {
if (res.status === 200) { if (res.status === 200) {
setTimeout(() => { setTimeout(() => {
stopRead(); stopRead();
}, 5 * 1000); }, 2 * 1000);
} }
// stop after 5 seconds // stop after 5 seconds
} catch (error: any) { } catch (error: any) {
if (error.response.data.code === 3) { if (error.response?.data.code === 3) {
stopRead(); stopRead();
setTimeout(() => { setTimeout(() => {
startRead(); startRead();
@@ -79,11 +81,13 @@ const startRead = async () => {
"error", "error",
"rfid", "rfid",
"rfid", "rfid",
`There was an error Starting the read: ${error.response.data.message}` `There was an error Starting the read: ${error.response?.data.message}`
); );
} }
}; };
const stopRead = async () => {
export const stopRead = async () => {
await getReaderToken();
try { try {
const res = await axios.put( const res = await axios.put(
`https://${ip}/cloud/stop`, `https://${ip}/cloud/stop`,
@@ -97,7 +101,7 @@ const stopRead = async () => {
"error", "error",
"rfid", "rfid",
"rfid", "rfid",
`There was an error Stopping the read: ${error.response.data.message}` `There was an error Stopping the read: ${JSON.stringify(error)}`
); );
} }
}; };

View File

@@ -17,11 +17,27 @@ export const newHeartBeat = async (reader: string) => {
.update(rfidReaders) .update(rfidReaders)
.set({ lastHeartBeat: sql`NOW()` }) .set({ lastHeartBeat: sql`NOW()` })
.where(eq(rfidReaders.reader, reader)); .where(eq(rfidReaders.reader, reader));
createLog("info", "rfid", "rfid", `${reader} just updated its heatBeat.`); createLog(
return {success: true, message: `${reader} just updated its heatBeat.`}; "debug",
"rfid",
"rfid",
`${reader} just updated its heatBeat.`
);
return {
success: true,
message: `${reader} just updated its heatBeat.`,
};
} catch (error) { } catch (error) {
createLog("error", "rfid", "rfid", `${reader} encountered an error while updating the heatbeat, ${error}`); createLog(
return {success: false, message: `${reader} encountered an error while updating the heatbeat, ${error}`}; "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}`,
};
} }
}; };
@@ -34,11 +50,27 @@ export const badRead = async (reader: string) => {
.update(rfidReaders) .update(rfidReaders)
.set({ lastTrigger: sql`NOW()`, lastTriggerGood: false }) .set({ lastTrigger: sql`NOW()`, lastTriggerGood: false })
.where(eq(rfidReaders.reader, reader)); .where(eq(rfidReaders.reader, reader));
createLog("info", "rfid", "rfid", `${reader} just Triggered a bad read.`); createLog(
return {success: true, message: `${reader} just Triggered a bad read.`}; "info",
"rfid",
"rfid",
`${reader} just Triggered a bad read.`
);
return {
success: true,
message: `${reader} just Triggered a bad read.`,
};
} catch (error) { } catch (error) {
createLog("error", "rfid", "rfid", `${reader} encountered an error while updating the heatbeat, ${error}`); createLog(
return {success: false, message: `${reader} encountered an error while updating the heatbeat, ${error}`}; "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}`,
};
} }
}; };
@@ -51,10 +83,26 @@ export const goodRead = async (reader: string) => {
.update(rfidReaders) .update(rfidReaders)
.set({ lastTrigger: sql`NOW()`, lastTriggerGood: true }) .set({ lastTrigger: sql`NOW()`, lastTriggerGood: true })
.where(eq(rfidReaders.reader, reader)); .where(eq(rfidReaders.reader, reader));
createLog("info", "rfid", "rfid", `${reader} just Triggered a good read.`); createLog(
return {success: true, message: `${reader} just Triggered a good read.`}; "info",
"rfid",
"rfid",
`${reader} just Triggered a good read.`
);
return {
success: true,
message: `${reader} just Triggered a good read.`,
};
} catch (error) { } catch (error) {
createLog("error", "rfid", "rfid", `${reader} encountered an error while updating the heatbeat, ${error}`); createLog(
return {success: false, message: `${reader} encountered an error while updating the heatbeat, ${error}`}; "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

@@ -8,6 +8,12 @@ import type { TagData } from "../tagData.js";
import { tagStuff } from "../tags/crudTag.js"; import { tagStuff } from "../tags/crudTag.js";
export const station3Tags = async (tagData: TagData[]) => { export const station3Tags = async (tagData: TagData[]) => {
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 // make sure we only have one tag or dont update
if (tagData.length != 1) { if (tagData.length != 1) {
createLog( createLog(

View File

@@ -8,17 +8,46 @@ import { labelingProcess } from "../../../ocp/controller/labeling/labelProcess.j
import type { TagData } from "../tagData.js"; import type { TagData } from "../tagData.js";
import { tagStuff } from "../tags/crudTag.js"; import { tagStuff } from "../tags/crudTag.js";
import { sendEmail } from "../../../notifications/controller/sendMail.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 { eq } from "drizzle-orm";
export const wrapperStuff = async (tagData: TagData[]) => { export const wrapperStuff = async (tagData: any) => {
if (tagData[0]?.lastareaIn === "NeedsChecked") { console.log("WrapperTag", 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.`
);
const tag = { ...tagData[0], runningNr: 0 };
//tagStuff([tag]);
monitorChecks();
} else {
if (!tagData) {
createLog("error", "rfid", "rfid", `No tagData was grabbed.`);
monitorChecks();
}
const { data: tagdata, error: tagError } = await tryCatch(
db.select().from(rfidTags).where(eq(rfidTags.tag, tagData[0].tag))
);
if (tagError) {
return {
success: false,
message: `There was an error getting the tag data for ${tagData[0].tag}.`,
};
}
const checkTag: any = tagdata;
if (checkTag[0]?.lastareaIn === "NeedsChecked") {
createLog( createLog(
"error", "error",
"rfid", "rfid",
"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.` `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.`
); );
// just making sure we clear out the running number if one really came over.
for (let i = 0; i < tagData.length; i++) { for (let i = 0; i < tagData.length; i++) {
const tag = { ...tagData[i], runningNr: 0 }; const tag = { ...tagData[i], runningNr: 0 };
tagStuff([tag]); tagStuff([tag]);
@@ -30,47 +59,20 @@ export const wrapperStuff = async (tagData: TagData[]) => {
"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.", "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.",
}; };
} }
if (tagData.length != 1) { const lines = checkTag[0]?.lastareaIn.includes("line3");
createLog(
"error",
"rfid",
"rfid",
`There are ${tagData.length} tags and this ${tagData[0].reader} only allows 1 tag to create a label.`
);
const tag = { ...tagData[0], runningNr: 0 };
tagStuff([tag]);
monitorChecks();
} else {
if (!tagData) {
createLog("error", "rfid", "rfid", `No tagData was grabbed.`);
monitorChecks();
}
const tagdata = await tagStuff(tagData);
/**
* we want to make sure this pallet came from a line as its last spot if not we need to have a manual check.
*/
const lines = tagdata[0]?.lastareaIn.includes("line3");
if (!lines) { if (!lines) {
createLog( createLog(
"error", "error",
"rfid", "rfid",
"rfid", "rfid",
`${tagdata[0].tag}, Did not come from a line please check the pallet and manually print the label.` `${tagData[0].tag}, Did not come from a line please check the pallet and manually print the label.`
); );
monitorChecks(); monitorChecks();
return { return {
success: false, success: false,
message: `${tagdata[0].tag}, Did not come from a line please check the pallet and manually print the label.`, message: `${tagData[0].tag}, Did not come from a line please check the pallet and manually print the label.`,
}; };
// when we manually run again we want to make sure we read from the 3rd antenna this way we do not get the wrong info.
// more testing will need to be done on this.
} }
// check if a running number exists
if (lines[0].runningNumber) { if (lines[0].runningNumber) {
createLog( createLog(
"info", "info",
@@ -83,12 +85,10 @@ export const wrapperStuff = async (tagData: TagData[]) => {
"info", "info",
"rfid", "rfid",
"rfid", "rfid",
`A new label will be created and linked to this ${tagdata[0].tag} tag` `A new label will be created and linked to this ${tagData[0].tag} tag`
); );
// get the actaul line number from the last area in
const lineNum = parseInt( const lineNum = parseInt(
tagdata[0]?.lastareaIn.repalceAll("line3", "") checkTag[0]?.lastareaIn.repalceAll("line3", "")
); );
createLog( createLog(
"info", "info",
@@ -96,17 +96,16 @@ export const wrapperStuff = async (tagData: TagData[]) => {
"rfid", "rfid",
`Line to be checked for printing: ${lineNum}` `Line to be checked for printing: ${lineNum}`
); );
const genlabel = await labelingProcess({ const genlabel = await labelingProcess({
line: lineNum.toString(), line: lineNum.toString(),
}); });
if (genlabel?.success) { if (genlabel?.success) {
// update the tag and add the label into it
const createPrintData = { const createPrintData = {
...tagData[0], ...tagData[0],
runnungNr: parseInt(genlabel.data?.SSCC.slice(10, -1)), runnungNr: parseInt(genlabel.data?.SSCC.slice(10, -1)),
}; };
tagStuff([createPrintData]);
} }
} }
} }

View File

@@ -15,6 +15,9 @@ export const tagData = async (data: TagData[]) => {
* We will always update a tag * We will always update a tag
*/ */
if (monitorTagsdata.includes(data[0].tag)) {
}
// dyco wall makes sure we have 10 tags // dyco wall makes sure we have 10 tags
const station1 = data.some((n) => n.reader.includes("reader1")); const station1 = data.some((n) => n.reader.includes("reader1"));
@@ -44,3 +47,21 @@ export const tagData = async (data: TagData[]) => {
wrapperStuff(data); 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

@@ -2,7 +2,11 @@ import {db} from "../../../../../database/dbclient.js";
import { rfidTags } from "../../../../../database/schema/rfidTags.js"; import { rfidTags } from "../../../../../database/schema/rfidTags.js";
import { createLog } from "../../../logger/logger.js"; import { createLog } from "../../../logger/logger.js";
export const manualTag = async (tag: string, area: string) => { export const manualTag = async (
tag: string,
area: string,
runningNr?: any | null
) => {
/** /**
* we only allow tags to be manually added from the wrappers * we only allow tags to be manually added from the wrappers
*/ */
@@ -20,17 +24,33 @@ export const manualTag = async (tag: string, area: string) => {
}; };
try { try {
// insert the tag with the onConflict update the tag // insert the tag with the onConflict update the tag
const tag = await db.insert(rfidTags).values(newTag).returning({ const tag = await db
.insert(rfidTags)
.values(newTag)
.returning({
tag: rfidTags.tag, tag: rfidTags.tag,
runningNumber: rfidTags.runningNumber, runningNumber: runningNr ? runningNr : rfidTags.runningNumber,
counts: rfidTags.counts, counts: rfidTags.counts,
lastareaIn: rfidTags.lastareaIn, lastareaIn: rfidTags.lastareaIn,
}); });
createLog("info", "rfid", "rfid", `Tags were just added, and label printed.`); createLog(
"info",
"rfid",
"rfid",
`Tags were just added, and label printed.`
);
// do the label thing here // do the label thing here
return {success: true, message: `${tagString} was just added, and label printed.`, data: tag}; return {
success: true,
message: `${tagString} was just added, and label printed.`,
data: tag,
};
} catch (error) { } catch (error) {
createLog("error", "rfid", "rfid", `${JSON.stringify(error)}`); createLog("error", "rfid", "rfid", `${JSON.stringify(error)}`);
return {success: false, message: `Error creating a new tag`, data: error}; return {
success: false,
message: `Error creating a new tag`,
data: error,
};
} }
}; };

View File

@@ -38,26 +38,42 @@ app.openapi(
if (body.type === "heartbeat") { if (body.type === "heartbeat") {
const heart = await newHeartBeat(reader); const heart = await newHeartBeat(reader);
return c.json({success: heart.success, message: heart.message}, 200); return c.json(
{ success: heart.success, message: heart.message },
200
);
} }
if (body.type === "gpi" && body.data.state === "HIGH") { if (body.type === "gpi" && body.data.state === "HIGH") {
const eventTimestamp = new Date(body.timestamp).getTime(); // Convert ISO timestamp to milliseconds const eventTimestamp = new Date(body.timestamp).getTime(); // Convert ISO timestamp to milliseconds
if (eventTimestamp - lastGpiTimestamp > 5 * 1000) { if (eventTimestamp - lastGpiTimestamp > 30 * 1000) {
// Check if it's been more than 2ms // Check if it's been more than 2ms
lastGpiTimestamp = eventTimestamp; // Update last seen timestamp lastGpiTimestamp = eventTimestamp; // Update last seen timestamp
createLog("info", "rfid", "rfid", `${reader} is reading a tag.`); createLog(
"info",
"rfid",
"rfid",
`${reader} is reading a tag.`
);
await readTags(reader); await readTags(reader);
} else { } else {
createLog("info", "rfid", "rfid", `A new trigger from ${reader} was to soon`); createLog(
"info",
"rfid",
"rfid",
`A new trigger from ${reader} was to soon`
);
lastGpiTimestamp = eventTimestamp; lastGpiTimestamp = eventTimestamp;
} }
//console.log(body); //console.log(body);
} }
return c.json({success: true, message: `New info from ${reader}`}, 200); return c.json(
{ success: true, message: `New info from ${reader}` },
200
);
} }
); );

View File

@@ -5,6 +5,9 @@ import {tagData} from "../controller/tagData.js";
import { responses } from "../../../globalUtils/routeDefs/responses.js"; import { responses } from "../../../globalUtils/routeDefs/responses.js";
import { noRead } from "../controller/noRead.js"; import { noRead } from "../controller/noRead.js";
import { badRead, goodRead } from "../controller/readerControl.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";
const app = new OpenAPIHono(); const app = new OpenAPIHono();
@@ -34,14 +37,24 @@ app.openapi(
}), }),
async (c) => { async (c) => {
const { reader } = c.req.valid("param"); const { reader } = c.req.valid("param");
createLog("info", "rfid", "rfid", `${reader} is sending us data.`);
let tagdata: any = []; let tagdata: any = [];
const body = await c.req.json(); const { data: body, error: bodyError } = await tryCatch(c.req.json());
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}`); //console.log(`Tag: ${Buffer.from(body.idHex, "hex").toString("utf-8")}, ${body[key].data.idHex}`);
for (let i = 0; i < body.length; i++) { for (let i = 0; i < body.length; i++) {
const tag = Buffer.from(body[i].data.idHex, "hex").toString("utf-8"); 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)); //console.log("Raw value:", body[i].data.peakRssi, "Parsed:", parseInt(body[i].data.peakRssi));
if (tag.includes("ALPLA") && parseInt(body[i].data.peakRssi) < -50) { if (
tag.includes("ALPLA") &&
parseInt(body[i].data.peakRssi) < -50
) {
tagdata = [ tagdata = [
...tagdata, ...tagdata,
{ {
@@ -59,11 +72,18 @@ app.openapi(
if (tagdata.length === 0) { if (tagdata.length === 0) {
noRead(reader); noRead(reader);
badRead(reader); badRead(reader);
return c.json({success: false, message: `There were no tags scanned.`}, 200); return c.json(
{ success: false, message: `There were no tags scanned.` },
200
);
} else { } else {
tagData(tagdata); tagData(tagdata);
goodRead(reader); goodRead(reader);
return c.json({success: true, message: `New info from ${reader}`}, 200);
return c.json(
{ success: true, message: `New info from ${reader}` },
200
);
} }
} }
); );