import config from "../config.js"; import { Device, Patch, WateringSession } from "../db/models/index.js"; import { formatClientPatches } from "./patches.js"; import { getOrCreateWaterTank } from "./waterTank.js"; import { formatPowerStateForClient, getOrCreatePowerState, } from "./powerState.js"; function mapWateringSessions(recentSessions) { return { activeWateringSessions: recentSessions.filter((s) => !s.endedAt), recentWateringSessions: recentSessions.map((s) => ({ ...s, id: s._id.toString(), deviceId: s.deviceId?.toString() ?? null, _id: undefined, })), }; } export async function getDeviceState() { const tid = config.device?.ttnApplicationId?.trim(); const did = config.device?.ttnDeviceId?.trim(); if (!tid || !did) { return { device: null }; } const device = await Device.findOne({ ttnApplicationId: tid, ttnDeviceId: did, }).lean(); if (!device) { return { device: null }; } const patchList = await Patch.find({ deviceId: device._id }) .populate({ path: "images", select: "blurHash contentType" }) .lean(); const id = device._id.toString(); return { device: { ...device, id, _id: undefined, patches: formatClientPatches(patchList), }, }; } export async function getWaterTankState() { const tank = await getOrCreateWaterTank(); return { level: tank.level, updatedAt: tank.updatedAt, }; } export async function getPowerStatePayload() { const power = await getOrCreatePowerState(); return formatPowerStateForClient(power); } export async function getWateringSessionsState() { const recentSessions = await WateringSession.find() .sort({ startedAt: -1 }) .limit(20) .lean(); return mapWateringSessions(recentSessions); } /** @param {string} patchId logical patch id (client `patch.id` / Mongo `patchId`) */ export async function getPatchState(patchId) { if (!patchId) return null; const p = await Patch.findOne({ patchId }) .populate({ path: "images", select: "blurHash contentType" }) .lean(); if (!p) return null; return formatClientPatches([p])[0]; }