TempMonitor/src/routes/(app)/[slug]/+page.server.ts
2025-06-12 20:36:14 +02:00

76 lines
2.5 KiB
TypeScript

import { db } from "$lib/server/db";
import * as table from "$lib/server/db/schema";
import { eq } from "drizzle-orm";
import type { PageServerLoad } from "./$types";
import { connect } from "mqtt";
import { getDeviceSensorData } from "$lib/server/mqtt-devices.js";
export const load: PageServerLoad = async ({ params }) => {
// Convert slug to number for floor lookup
const floorNumber = Number(params.slug);
// First check if we have a saved floor configuration in the floors table
const floorData = await db.select({
floor: table.floors.floor,
url: table.floors.url
}).from(table.floors).where(eq(table.floors.floor, floorNumber));
if (floorData.length > 0 && floorData[0].url && floorData[0].url !== "/") {
try {
// Try to parse the saved configuration
const config = JSON.parse(floorData[0].url);
// Add real sensor data to devices
if (config.devices) {
config.devices = config.devices.map(device => {
const sensorData = getDeviceSensorData(device.id);
return {
...device,
sensorData: sensorData
};
});
}
return {
slug: params.slug,
floorConfig: config,
hasConfig: true
};
} catch (e) {
console.error("Error parsing floor configuration:", e);
}
}
// Fallback to the old canvas drawing system
const floor_cnt = await db.select({ floor: table.plans.floor, json: table.plans.plan }).from(table.plans).where(eq(table.plans.floor, params.slug));
if (floor_cnt.length == 0) {
await db.insert(table.plans).values({ floor: params.slug, plan: {
"regions": [
{ "start": { "x": 100, "y": 100 }, "end": { "x": 400, "y": 100 } },
{ "start": { "x": 400, "y": 100 }, "end": { "x": 400, "y": 300 } },
{ "start": { "x": 400, "y": 300 }, "end": { "x": 100, "y": 300 } },
{ "start": { "x": 100, "y": 300 }, "end": { "x": 100, "y": 100 } }
],
"doors": [
{ "location": { "x": 240, "y": 100 }, "width": 50, "rotation": 0 }
],
"furnitures": [
{
"minBound": { "x": 150, "y": 150 },
"maxBound": { "x": 200, "y": 200 },
"equipName": "Table",
"xPlacement": 150,
"yPlacement": 150,
"rotation": 0
}
]
}});
}
const floor_ = await db.select({ floor: table.plans.floor, json: table.plans.plan }).from(table.plans).where(eq(table.plans.floor, params.slug));
return {
slug: params.slug,
floor: floor_,
hasConfig: false
};
};