save data if sensor is on some floor

This commit is contained in:
David Senoner 2025-06-12 22:46:07 +02:00
parent fae128bc1b
commit b4f6fbd648
Signed by: kada49
GPG key ID: 92BABE6B7E63C6CA
5 changed files with 24 additions and 5 deletions

View file

@ -34,7 +34,7 @@ export const sensors = pgTable("sensors", {
});
export const sensorData = pgTable("sensor_data", {
uuid: uuid().primaryKey(),
uuid: uuid().primaryKey().defaultRandom(),
sensor: text("sensor")
.references(() => sensors.id)
.notNull(),
@ -42,5 +42,5 @@ export const sensorData = pgTable("sensor_data", {
humidity: real().notNull(),
pressure: real().notNull(),
altitude: real().notNull(),
time: timestamp().notNull().defaultNow(),
time: timestamp({ withTimezone: true, mode: "date" }).notNull().defaultNow(),
});

View file

@ -194,7 +194,9 @@
const number = await response.json();
console.log(number);
chartData = [];
chartData = number.map((obj) => {
return { date: new Date(obj.date), desktop: obj.temp, mobile: obj.pressure };
});
}
});
</script>

View file

@ -2,7 +2,7 @@ import { db } from "$lib/server/db";
import * as table from "$lib/server/db/schema"
export const GET = async () => {
const data = await db.select({ sensor: table.sensorData.sensor }).from(table.sensorData);
const data = await db.select({ date: table.sensorData.time, temp: table.sensorData.temperature, pressure: table.sensorData.pressure }).from(table.sensorData);
console.log(data);
return new Response(JSON.stringify(data), {

View file

@ -81,6 +81,9 @@ export const actions = {
try {
const deviceData = JSON.parse(devices);
deviceData.forEach(async (dev) => {
await db.insert(table.sensors).values({ id: dev.id, user: event.locals.session.userId });
});
// Check if floor exists
const exists = await db

View file

@ -1,5 +1,8 @@
// src/routes/mqtt/+server.js
import { db } from "$lib/server/db";
import * as table from "$lib/server/db/schema";
import { connectedDevices, deviceSensorData, getCurrentDevices } from "$lib/server/mqtt-devices.js";
import { eq } from "drizzle-orm";
import mqtt from "mqtt";
import { writable } from "svelte/store";
@ -114,7 +117,7 @@ function connectMqtt() {
});
});
client.on("message", (topic, message) => {
client.on("message", async (topic, message) => {
const payload = message.toString();
console.log(`Received message from topic "${topic}": ${payload}`);
latestMessage.set(payload); // Update the Svelte store
@ -130,6 +133,17 @@ function connectMqtt() {
if (sensorData) {
console.log(`Parsed sensor data:`, sensorData);
updateDevice(deviceId, sensorData);
const devices = await db.select().from(table.sensors).where(eq(table.sensors.id, deviceId));
if (devices.length == 1)
await db
.insert(table.sensorData)
.values({
sensor: deviceId,
temperature: sensorData.temperature,
humidity: sensorData.humidity,
altitude: sensorData.altitude,
pressure: sensorData.pressure,
});
} else {
// Still update device as online even if data parsing failed
updateDevice(deviceId);