Scaffold Phase 1 hvac app — NewBook-driven room TRV heating scheduler
Ports the state machine, retry/backoff, and guest-override detection from the retired homeassistant-newbook-heating-component, without depending on Home Assistant. Backend (Fastify/pg) + frontend (React/Vite/TS) following standard stack conventions; LXC 128 (127 was already taken by utilities). MHI/Midea/Daikin/boiler drivers and the shared MQTT broker (LXC 104) are later phases/infra, not included here. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
commit
276c04f8c6
42 changed files with 5461 additions and 0 deletions
57
backend/src/auth.js
Normal file
57
backend/src/auth.js
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { jwtVerify } from 'jose'
|
||||
import { isOnsite } from './ip-check.js'
|
||||
|
||||
const APP_SLUG = process.env.APP_SLUG || 'hvac'
|
||||
const secret = new TextEncoder().encode(process.env.CENTRAL_AUTH_SECRET || '')
|
||||
|
||||
export async function requireAuth(request, reply) {
|
||||
const token = request.cookies?.hnf_session
|
||||
if (!token) return reply.status(401).send({ error: 'Not authenticated' })
|
||||
|
||||
let payload
|
||||
try {
|
||||
const { payload: p } = await jwtVerify(token, secret)
|
||||
payload = p
|
||||
} catch {
|
||||
return reply.status(401).send({ error: 'Invalid session' })
|
||||
}
|
||||
|
||||
if (!payload.apps?.includes(APP_SLUG)) {
|
||||
return reply.status(403).send({ error: 'No permission for this app' })
|
||||
}
|
||||
|
||||
if (!payload.offsite_allowed) {
|
||||
const clientIP = request.headers['x-real-ip'] || request.ip
|
||||
if (!(await isOnsite(clientIP))) {
|
||||
return reply.status(403).send({ error: 'Access restricted to site network' })
|
||||
}
|
||||
}
|
||||
|
||||
const prefix = `${APP_SLUG}:`
|
||||
let caps
|
||||
if (Array.isArray(payload.caps)) {
|
||||
caps = payload.caps.filter(c => c.startsWith(prefix)).map(c => c.slice(prefix.length))
|
||||
} else {
|
||||
// Legacy token — grant view-only until re-login
|
||||
caps = ['view']
|
||||
}
|
||||
|
||||
request.user = {
|
||||
email: payload.sub,
|
||||
name: payload.name,
|
||||
is_admin: payload.is_admin ?? false,
|
||||
caps,
|
||||
}
|
||||
}
|
||||
|
||||
export function hasCap(request, cap) {
|
||||
return request.user?.is_admin === true || request.user?.caps?.includes(cap) === true
|
||||
}
|
||||
|
||||
export function requireCap(cap) {
|
||||
return async (request, reply) => {
|
||||
if (!hasCap(request, cap)) {
|
||||
return reply.status(403).send({ error: `Missing capability: ${cap}` })
|
||||
}
|
||||
}
|
||||
}
|
||||
148
backend/src/db.js
Normal file
148
backend/src/db.js
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
import pg from 'pg'
|
||||
|
||||
const { Pool } = pg
|
||||
export const pool = new Pool({ connectionString: process.env.DATABASE_URL })
|
||||
|
||||
export async function initDb() {
|
||||
await pool.query(`
|
||||
-- Generic key/value config store (hk-planner/maintenance pattern) — holds
|
||||
-- excluded_site_ids, poll_interval_minutes, maintenance integration URL/key, etc.
|
||||
CREATE TABLE IF NOT EXISTS config (
|
||||
key TEXT PRIMARY KEY,
|
||||
value JSONB NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Zones: rooms (synced from NewBook) and public areas (manual, Phase 3 control).
|
||||
-- Single table for the whole device lifetime — Phase 2/3 aircon-specific columns
|
||||
-- (cool setpoint, fan mode) land here later as nullable ADD COLUMNs, not a new table.
|
||||
CREATE TABLE IF NOT EXISTS zones (
|
||||
id SERIAL PRIMARY KEY,
|
||||
zone_type TEXT NOT NULL DEFAULT 'room', -- room | public_area
|
||||
source TEXT NOT NULL DEFAULT 'manual', -- newbook | manual
|
||||
newbook_site_id TEXT UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE, -- soft-deactivate on NewBook sync, never hard delete
|
||||
occupied_temp NUMERIC(4,1) NOT NULL DEFAULT 22.0,
|
||||
vacant_temp NUMERIC(4,1) NOT NULL DEFAULT 16.0,
|
||||
heating_offset_min INT NOT NULL DEFAULT 120, -- minutes before arrival to start heating
|
||||
cooling_offset_min INT NOT NULL DEFAULT -30, -- minutes after departure to stop (negative = before checkout)
|
||||
auto_mode BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
sync_valves BOOLEAN NOT NULL DEFAULT TRUE, -- sync guest setpoint changes across valves in the same zone
|
||||
exclude_bathroom BOOLEAN NOT NULL DEFAULT TRUE, -- bathroom valve excluded from guest-adjustment sync
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Device mapping — one row per physical device, assigned to a zone by staff via
|
||||
-- the Devices onboarding flow (never auto-mapped from device naming conventions).
|
||||
CREATE TABLE IF NOT EXISTS zone_devices (
|
||||
id SERIAL PRIMARY KEY,
|
||||
zone_id INT REFERENCES zones(id) ON DELETE SET NULL,
|
||||
device_type TEXT NOT NULL, -- shelly_trv | mhi_modbus | midea | daikin | home_assistant
|
||||
external_ref TEXT NOT NULL, -- MAC / Modbus address / LAN device ID / HA entity_id
|
||||
discovered_name TEXT, -- raw name/label from the device — display-only, never parsed
|
||||
location TEXT, -- bedroom / bathroom / living / free text, set by staff
|
||||
maintenance_asset_id INT, -- set once "Create asset in Maintenance" succeeds (Phase 1: stub, always NULL)
|
||||
last_seen TIMESTAMPTZ,
|
||||
battery_pct INT,
|
||||
health_state TEXT NOT NULL DEFAULT 'healthy', -- healthy | degraded | poor | unresponsive | calibration_error
|
||||
wifi_rssi INT,
|
||||
current_target_temp NUMERIC(4,1),
|
||||
target_origin TEXT, -- automation | guest | pending | unknown (Shelly source field)
|
||||
device_ip TEXT, -- for the HTTP wake-up fallback
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS zone_devices_zone_idx ON zone_devices (zone_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS zone_devices_type_ref_idx ON zone_devices (device_type, external_ref);
|
||||
|
||||
-- Two photo slots per device (device photo + serial/model plate) — same pattern
|
||||
-- as maintenance's task_photos: multipart + sharp, uploads_data volume.
|
||||
CREATE TABLE IF NOT EXISTS device_photos (
|
||||
id SERIAL PRIMARY KEY,
|
||||
device_id INT NOT NULL REFERENCES zone_devices(id) ON DELETE CASCADE,
|
||||
file_name TEXT NOT NULL,
|
||||
file_path TEXT NOT NULL,
|
||||
mime_type TEXT,
|
||||
file_size INT,
|
||||
photo_type TEXT NOT NULL DEFAULT 'device', -- device | serial_plate
|
||||
uploaded_by TEXT,
|
||||
uploaded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS device_photos_device_idx ON device_photos (device_id);
|
||||
|
||||
-- Minimal, TTL'd booking cache — room-planner style (no full booking mirror).
|
||||
-- Kept per-zone so a NewBook fetch failure can fall back to the last successful
|
||||
-- read instead of treating "fetch failed" as "no booking" (fail-safe requirement).
|
||||
CREATE TABLE IF NOT EXISTS booking_cache (
|
||||
zone_id INT PRIMARY KEY REFERENCES zones(id) ON DELETE CASCADE,
|
||||
booking_data JSONB,
|
||||
fetched_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Persisted current room state — survives backend restarts, and lets the
|
||||
-- scheduler apply setpoints only at state *transitions* (never poll-and-reassert
|
||||
-- during 'occupied', which would stomp guest button/WS adjustments).
|
||||
CREATE TABLE IF NOT EXISTS zone_state (
|
||||
zone_id INT PRIMARY KEY REFERENCES zones(id) ON DELETE CASCADE,
|
||||
room_state TEXT NOT NULL DEFAULT 'vacant', -- vacant | booked | heating_up | occupied | cooling_down
|
||||
last_booking_status TEXT,
|
||||
last_transition_at TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Rolling log of state transitions, manual overrides, sync runs and errors.
|
||||
CREATE TABLE IF NOT EXISTS activity_log (
|
||||
id SERIAL PRIMARY KEY,
|
||||
zone_id INT REFERENCES zones(id) ON DELETE CASCADE,
|
||||
event_type TEXT NOT NULL, -- transition | override | sync | device_command | error
|
||||
from_state TEXT,
|
||||
to_state TEXT,
|
||||
note TEXT,
|
||||
source TEXT NOT NULL DEFAULT 'scheduler', -- scheduler | manual | sync
|
||||
user_email TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS activity_log_zone_idx ON activity_log (zone_id, created_at DESC);
|
||||
`)
|
||||
|
||||
await seedDefaults()
|
||||
}
|
||||
|
||||
async function seedDefaults() {
|
||||
const defaults = {
|
||||
excluded_site_ids: [],
|
||||
poll_interval_minutes: 10, // matches the old integration's DEFAULT_SCAN_INTERVAL
|
||||
default_arrival_time: '15:00:00',
|
||||
default_departure_time: '10:00:00',
|
||||
maintenance_url: '',
|
||||
maintenance_api_key: '',
|
||||
}
|
||||
for (const [key, value] of Object.entries(defaults)) {
|
||||
await pool.query(
|
||||
`INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`,
|
||||
[key, JSON.stringify(value)]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getConfig(key, fallback = null) {
|
||||
const { rows } = await pool.query('SELECT value FROM config WHERE key = $1', [key])
|
||||
return rows.length ? rows[0].value : fallback
|
||||
}
|
||||
|
||||
export async function setConfig(key, value) {
|
||||
await pool.query(
|
||||
`INSERT INTO config (key, value, updated_at) VALUES ($1, $2, NOW())
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`,
|
||||
[key, JSON.stringify(value)]
|
||||
)
|
||||
}
|
||||
|
||||
export async function logActivity(zoneId, eventType, { fromState, toState, note, source = 'scheduler', userEmail } = {}) {
|
||||
await pool.query(
|
||||
`INSERT INTO activity_log (zone_id, event_type, from_state, to_state, note, source, user_email)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
|
||||
[zoneId, eventType, fromState || null, toState || null, note || null, source, userEmail || null]
|
||||
)
|
||||
}
|
||||
57
backend/src/index.js
Normal file
57
backend/src/index.js
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import Fastify from 'fastify'
|
||||
import cookie from '@fastify/cookie'
|
||||
import cors from '@fastify/cors'
|
||||
import multipart from '@fastify/multipart'
|
||||
import staticFiles from '@fastify/static'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { dirname, join } from 'path'
|
||||
import { initDb } from './db.js'
|
||||
import { connect as connectMqtt } from './lib/mqtt.js'
|
||||
import { startScheduler } from './lib/scheduler.js'
|
||||
import { zoneRoutes } from './routes/zones.js'
|
||||
import { deviceRoutes } from './routes/devices.js'
|
||||
import { statusRoutes } from './routes/status.js'
|
||||
import { overrideRoutes } from './routes/override.js'
|
||||
import { configRoutes } from './routes/config.js'
|
||||
import { settingsRoutes } from './routes/settings.js'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const UPLOADS_DIR = join(__dirname, '..', 'uploads')
|
||||
|
||||
const app = Fastify({ logger: true, trustProxy: true })
|
||||
const startedAt = Date.now()
|
||||
|
||||
await app.register(cookie)
|
||||
await app.register(cors, {
|
||||
origin: process.env.CORS_ORIGIN || false,
|
||||
credentials: true,
|
||||
})
|
||||
await app.register(multipart, { limits: { fileSize: 10 * 1024 * 1024 } })
|
||||
await app.register(staticFiles, {
|
||||
root: UPLOADS_DIR,
|
||||
prefix: '/api/uploads/',
|
||||
decorateReply: false,
|
||||
})
|
||||
|
||||
app.get('/health', async () => ({ status: 'healthy', version: process.env.BUILD_VERSION || String(startedAt) }))
|
||||
|
||||
await app.register(zoneRoutes)
|
||||
await app.register(deviceRoutes, { uploadsDir: UPLOADS_DIR })
|
||||
await app.register(statusRoutes)
|
||||
await app.register(overrideRoutes)
|
||||
await app.register(configRoutes)
|
||||
await app.register(settingsRoutes)
|
||||
|
||||
try {
|
||||
await initDb()
|
||||
|
||||
// MQTT broker (shared infra, LXC 104) may not exist yet — connect() handles that
|
||||
// gracefully with its own backoff and never blocks startup.
|
||||
connectMqtt().catch(err => app.log.warn(`MQTT connect failed at startup: ${err.message}`))
|
||||
|
||||
await startScheduler()
|
||||
await app.listen({ port: 3001, host: '0.0.0.0' })
|
||||
} catch (err) {
|
||||
app.log.error(err)
|
||||
process.exit(1)
|
||||
}
|
||||
80
backend/src/ip-check.js
Normal file
80
backend/src/ip-check.js
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import dns from 'dns/promises'
|
||||
|
||||
const raw = (process.env.OFFICE_IP_CHECK || 'disabled').trim()
|
||||
const matchers = raw.split(',').map(s => s.trim()).filter(Boolean)
|
||||
|
||||
const TTL = 5 * 60 * 1000
|
||||
const cache = new Map()
|
||||
|
||||
const PUBLIC_IP_URLS = [
|
||||
'https://api.ipify.org',
|
||||
'https://ifconfig.co/ip',
|
||||
'https://icanhazip.com',
|
||||
]
|
||||
|
||||
function normalizeIP(ip) {
|
||||
return ip?.startsWith('::ffff:') ? ip.slice(7) : ip
|
||||
}
|
||||
|
||||
function isIPv4(s) {
|
||||
return /^\d{1,3}(\.\d{1,3}){3}$/.test(s)
|
||||
}
|
||||
|
||||
function ipInCidr(ip, cidr) {
|
||||
const [range, bits] = cidr.split('/')
|
||||
if (!isIPv4(ip) || !isIPv4(range)) return false
|
||||
const mask = ~(2 ** (32 - parseInt(bits)) - 1) >>> 0
|
||||
const toInt = s => s.split('.').reduce((a, o) => (a << 8) + parseInt(o), 0) >>> 0
|
||||
return (toInt(ip) & mask) === (toInt(range) & mask)
|
||||
}
|
||||
|
||||
async function fetchPublicIP() {
|
||||
for (const url of PUBLIC_IP_URLS) {
|
||||
try {
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(() => ctrl.abort(), 4000)
|
||||
const res = await fetch(url, { signal: ctrl.signal })
|
||||
clearTimeout(timer)
|
||||
if (!res.ok) continue
|
||||
const ip = (await res.text()).trim()
|
||||
if (isIPv4(ip)) return ip
|
||||
} catch {
|
||||
// try next
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function resolveDynamic(key, resolver) {
|
||||
const hit = cache.get(key)
|
||||
if (hit && Date.now() < hit.expiry) return hit.ip
|
||||
const ip = await resolver()
|
||||
if (ip) {
|
||||
cache.set(key, { ip, expiry: Date.now() + TTL })
|
||||
return ip
|
||||
}
|
||||
return hit ? hit.ip : null
|
||||
}
|
||||
|
||||
export async function isOnsite(requestIP) {
|
||||
if (matchers.length === 0 || matchers.includes('disabled')) return true
|
||||
const ip = normalizeIP(requestIP)
|
||||
if (!ip) return false
|
||||
|
||||
for (const m of matchers) {
|
||||
if (m === 'auto') {
|
||||
const pub = await resolveDynamic('auto', fetchPublicIP)
|
||||
if (pub && ip === pub) return true
|
||||
} else if (m.includes('/')) {
|
||||
if (ipInCidr(ip, m)) return true
|
||||
} else if (/[a-zA-Z]/.test(m)) {
|
||||
const resolved = await resolveDynamic(m, async () => {
|
||||
try { return (await dns.resolve4(m))[0] } catch { return null }
|
||||
})
|
||||
if (resolved && ip === resolved) return true
|
||||
} else {
|
||||
if (ip === m) return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
100
backend/src/lib/drivers/homeassistant.js
Normal file
100
backend/src/lib/drivers/homeassistant.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
// Optional escape-hatch driver — same discover()/getStatus()/setTarget() interface
|
||||
// as every other driver, backed by Home Assistant's REST API instead of a direct
|
||||
// protocol. Per the plan: HA is not required by hvac and nothing else depends on
|
||||
// it existing. Credentials (base_url + long-lived access token) are meant to be
|
||||
// configured once, centrally, as a new integration type in the shared `settings`
|
||||
// service (same tier as NewBook/SMTP) — that settings endpoint does not exist yet,
|
||||
// so this driver no-ops (returns empty / not-configured) until it does. No
|
||||
// hardcoded credentials, no fake integration.
|
||||
const DEVICE_TYPE = 'home_assistant'
|
||||
|
||||
async function getCredentials() {
|
||||
try {
|
||||
const url = `${process.env.SETTINGS_URL}/settings/api/internal/integration/home_assistant`
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${process.env.SETTINGS_SECRET}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!res.ok) return null
|
||||
const s = await res.json()
|
||||
if (!s.base_url || !s.access_token) return null
|
||||
return { baseUrl: s.base_url.replace(/\/$/, ''), token: s.access_token }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/states filtered to climate.* entities.
|
||||
export async function discover() {
|
||||
const creds = await getCredentials()
|
||||
if (!creds) {
|
||||
return { ok: false, error: 'Home Assistant integration not configured in settings', devices: [] }
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`${creds.baseUrl}/api/states`, {
|
||||
headers: { Authorization: `Bearer ${creds.token}` },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
if (!res.ok) throw new Error(`HA API ${res.status}`)
|
||||
const states = await res.json()
|
||||
const devices = states
|
||||
.filter(s => s.entity_id?.startsWith('climate.'))
|
||||
.map(s => ({
|
||||
external_ref: s.entity_id,
|
||||
discovered_name: s.attributes?.friendly_name || s.entity_id,
|
||||
model: 'home_assistant',
|
||||
}))
|
||||
return { ok: true, devices }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err.message, devices: [] }
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStatus(externalRef) {
|
||||
const creds = await getCredentials()
|
||||
if (!creds) return null
|
||||
try {
|
||||
const res = await fetch(`${creds.baseUrl}/api/states/${encodeURIComponent(externalRef)}`, {
|
||||
headers: { Authorization: `Bearer ${creds.token}` },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
if (!res.ok) return null
|
||||
const state = await res.json()
|
||||
return {
|
||||
external_ref: externalRef,
|
||||
current_target_temp: state.attributes?.temperature ?? null,
|
||||
health_state: 'healthy',
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function setTarget(externalRef, { mode, tempC }) {
|
||||
const creds = await getCredentials()
|
||||
if (!creds) return false
|
||||
try {
|
||||
if (tempC != null) {
|
||||
await fetch(`${creds.baseUrl}/api/services/climate/set_temperature`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${creds.token}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ entity_id: externalRef, temperature: tempC }),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
}
|
||||
if (mode) {
|
||||
await fetch(`${creds.baseUrl}/api/services/climate/set_hvac_mode`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${creds.token}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ entity_id: externalRef, hvac_mode: mode }),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
}
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('[homeassistant driver] setTarget failed:', err.message)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export { DEVICE_TYPE }
|
||||
44
backend/src/lib/drivers/trv.js
Normal file
44
backend/src/lib/drivers/trv.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// Driver interface implementation for Shelly Gen1 TRVs, backed by lib/mqtt.js.
|
||||
// Every driver in the stack exposes the same shape: discover() / getStatus(externalRef) /
|
||||
// setTarget(externalRef, { mode, tempC }) — the scheduler and the Devices onboarding
|
||||
// flow only ever talk to this interface, never to MQTT directly.
|
||||
import { pool } from '../../db.js'
|
||||
import { getDiscoveredDevices, setTargetWithRetry, isConnected } from '../mqtt.js'
|
||||
|
||||
export const DEVICE_TYPE = 'shelly_trv'
|
||||
|
||||
// Returns raw devices seen on the MQTT broker (from shellies/announce +
|
||||
// shellies/+/settings), regardless of whether they're already mapped to a zone.
|
||||
// Never auto-maps by parsing the device name — that's a staff action in the UI.
|
||||
export async function discover() {
|
||||
if (!isConnected()) {
|
||||
return { ok: false, error: 'MQTT broker not connected', devices: [] }
|
||||
}
|
||||
const devices = getDiscoveredDevices().map(d => ({
|
||||
external_ref: d.deviceId,
|
||||
discovered_name: d.name,
|
||||
model: d.model,
|
||||
mac: d.mac,
|
||||
ip: d.ip,
|
||||
}))
|
||||
return { ok: true, devices }
|
||||
}
|
||||
|
||||
export async function getStatus(externalRef) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT external_ref, current_target_temp, target_origin, health_state, battery_pct, wifi_rssi, last_seen
|
||||
FROM zone_devices WHERE device_type = $1 AND external_ref = $2`,
|
||||
[DEVICE_TYPE, externalRef]
|
||||
)
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
// mode is accepted for interface parity with other drivers (Modbus/Midea/Daikin
|
||||
// have real heat/cool/off modes) — Shelly TRVs are heat-only, so it's ignored here.
|
||||
export async function setTarget(externalRef, { tempC }) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT device_ip FROM zone_devices WHERE device_type = $1 AND external_ref = $2`,
|
||||
[DEVICE_TYPE, externalRef]
|
||||
)
|
||||
return setTargetWithRetry({ external_ref: externalRef, device_ip: rows[0]?.device_ip || null }, tempC)
|
||||
}
|
||||
21
backend/src/lib/maintenance-client.js
Normal file
21
backend/src/lib/maintenance-client.js
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
// STUB — "Create asset in Maintenance" is explicitly out of scope for this build.
|
||||
//
|
||||
// Per the hvac plan doc (§ "Create a maintenance asset from a device"), the real
|
||||
// integration needs a joint change in `maintenance` first: its own self-service
|
||||
// Settings → API Keys page (copied from forecasting's ApiKeysPage pattern) plus a
|
||||
// new X-API-Key-authenticated `POST /api/public/assets` endpoint. Neither exists
|
||||
// in `maintenance` yet — it currently has no API-key auth at all. Building a real
|
||||
// client against an endpoint that doesn't exist would just be a fake integration,
|
||||
// so this module intentionally does nothing beyond returning a clear "not
|
||||
// implemented" result. Wire this up for real once the maintenance-side work lands
|
||||
// (tracked as its own small piece of work, not bundled into hvac's deploy).
|
||||
export async function createMaintenanceAsset(_device, _zone) {
|
||||
return {
|
||||
ok: false,
|
||||
notImplemented: true,
|
||||
error: 'Maintenance asset creation is not yet available — maintenance needs its own ' +
|
||||
'Settings → API Keys page and a public asset-creation endpoint first (see hvac plan, ' +
|
||||
'"Create a maintenance asset from a device"). Configure maintenance_url / maintenance_api_key ' +
|
||||
'in hvac Settings once that lands.',
|
||||
}
|
||||
}
|
||||
335
backend/src/lib/mqtt.js
Normal file
335
backend/src/lib/mqtt.js
Normal file
|
|
@ -0,0 +1,335 @@
|
|||
// Mosquitto client wrapper for Shelly Gen1 TRVs.
|
||||
//
|
||||
// Ported from the retired homeassistant-newbook-heating-component's trv_monitor.py /
|
||||
// shelly_detector.py — same topic convention, same retry/backoff/stagger/wake-up
|
||||
// reliability logic, same guest-vs-automation source detection. The broker itself
|
||||
// is shared infra (its own LXC, not part of this app) and doesn't exist yet at the
|
||||
// time this file is written, so every public function here degrades cleanly when
|
||||
// the broker is unreachable rather than crashing the backend.
|
||||
//
|
||||
// Credentials are fetched at runtime from the settings service, not baked into
|
||||
// docker-compose — same self-service pattern as newbook.js's getCredentials().
|
||||
// NOTE: the settings endpoint below (`/settings/api/internal/integration/mqtt`)
|
||||
// does not exist yet — this client is written against the shape described in the
|
||||
// hvac plan doc so it "just works" once settings adds it. Until then every
|
||||
// connection attempt fails fast and retries in the background; nothing here blocks
|
||||
// backend startup.
|
||||
import mqtt from 'mqtt'
|
||||
import { pool } from '../db.js'
|
||||
|
||||
const CLIENT_NAME = 'hvac-backend'
|
||||
|
||||
// Same reliability tuning as the old trv_monitor.py: 30s -> 30min backoff, staggered
|
||||
// per-valve commands ~10s apart, HTTP wake-up before declaring a TRV unresponsive.
|
||||
const RETRY_DELAYS_MS = [30, 60, 120, 300, 300, 600, 600, 900, 900, 1800].map(s => s * 1000)
|
||||
const STAGGER_MS = 10 * 1000
|
||||
const BROKER_RECONNECT_BACKOFF_MS = [30, 60, 120, 300, 600, 1800].map(s => s * 1000) // 30s -> 30min
|
||||
|
||||
const GUEST_SOURCES = ['button', 'WS']
|
||||
const AUTOMATION_SOURCES = ['mqtt', 'http']
|
||||
|
||||
let client = null
|
||||
let connecting = false
|
||||
let reconnectAttempt = 0
|
||||
|
||||
// device_id (Shelly's own id, e.g. "shellytrv-84FD270DD7CC") -> { mac, model, ip, name, lastAnnounceAt }
|
||||
const discovered = new Map()
|
||||
|
||||
async function getCredentials() {
|
||||
const url = `${process.env.SETTINGS_URL}/settings/api/internal/integration/mqtt?client=${CLIENT_NAME}`
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${process.env.SETTINGS_SECRET}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!res.ok) throw new Error(`Settings service returned ${res.status} fetching MQTT credentials`)
|
||||
const s = await res.json()
|
||||
if (!s.host || !s.username || !s.password) throw new Error('MQTT broker credentials not configured in settings')
|
||||
return { host: s.host, port: s.port || 1883, username: s.username, password: s.password }
|
||||
}
|
||||
|
||||
// Parse a Shelly Gen1 announce/settings payload. Gen2+ devices (which carry a
|
||||
// "gen" field) are explicitly unsupported — same guard as the retired
|
||||
// shelly_detector.py, since Gen2 uses RPC-over-MQTT, not these flat topics.
|
||||
function isGen1(payload) {
|
||||
return !('gen' in payload)
|
||||
}
|
||||
|
||||
function recordDiscovery(deviceId, { mac, model, ip, name }) {
|
||||
const existing = discovered.get(deviceId) || {}
|
||||
discovered.set(deviceId, {
|
||||
deviceId,
|
||||
mac: mac || existing.mac || '',
|
||||
model: model || existing.model || '',
|
||||
ip: ip || existing.ip || '',
|
||||
name: name || existing.name || deviceId,
|
||||
lastAnnounceAt: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
async function handleAnnounce(payload) {
|
||||
if (!isGen1(payload)) return
|
||||
if (!payload.id || !payload.model) return
|
||||
if (payload.model !== 'SHTRV-01') return // TRVs only in Phase 1
|
||||
recordDiscovery(payload.id, { mac: payload.mac, model: payload.model, ip: payload.ip })
|
||||
}
|
||||
|
||||
async function handleSettings(deviceId, payload) {
|
||||
const deviceInfo = payload.device || {}
|
||||
if (!deviceInfo.type || !deviceInfo.mac) return
|
||||
if ('gen' in payload) return
|
||||
if (deviceInfo.type !== 'SHTRV-01') return
|
||||
recordDiscovery(deviceId, {
|
||||
mac: deviceInfo.mac,
|
||||
model: deviceInfo.type,
|
||||
ip: payload.wifi_sta?.ip || '',
|
||||
name: payload.name || deviceId,
|
||||
})
|
||||
}
|
||||
|
||||
// shellies/room-{room_id}-{location}-trv/thermostat/0/target_t -> { temp, source }
|
||||
// source: button|WS = guest-initiated (never resync from these); mqtt|http = our own
|
||||
// automation's command (safe to resync other valves in the room).
|
||||
async function handleStatus(externalRef, payload) {
|
||||
const targetTemp = payload.temp
|
||||
const source = payload.source
|
||||
const isGuest = GUEST_SOURCES.includes(source)
|
||||
const origin = isGuest ? 'guest' : (AUTOMATION_SOURCES.includes(source) ? 'automation' : 'unknown')
|
||||
|
||||
try {
|
||||
await pool.query(
|
||||
`UPDATE zone_devices
|
||||
SET last_seen = NOW(), current_target_temp = $2, target_origin = $3, updated_at = NOW()
|
||||
WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef, targetTemp ?? null, origin]
|
||||
)
|
||||
} catch (err) {
|
||||
// DB not reachable / table not ready yet — don't crash the MQTT client over it
|
||||
console.error('[mqtt] failed to record status update:', err.message)
|
||||
}
|
||||
|
||||
if (isGuest && targetTemp != null) {
|
||||
await syncGuestAdjustmentToRoom(externalRef, targetTemp).catch(err => {
|
||||
console.error('[mqtt] guest valve sync failed:', err.message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Debounce so we don't loop: our own resync command comes back as source='mqtt'
|
||||
// (automation), which already wouldn't re-trigger this function — but keep a
|
||||
// time-based guard too, matching the old trv_monitor.py's SYNC_DEBOUNCE_SECONDS.
|
||||
const SYNC_DEBOUNCE_MS = 30 * 1000
|
||||
const lastGuestSyncAt = new Map() // external_ref -> timestamp ms
|
||||
|
||||
// Guest-initiated Temperature Respect + valve sync: when a guest adjusts one TRV
|
||||
// (source=button|WS), sync the new setpoint to the room's other valves — unless
|
||||
// the zone has sync_valves disabled, or the source/target valve is the bathroom
|
||||
// and exclude_bathroom is enabled. Never touches valves in other zones.
|
||||
async function syncGuestAdjustmentToRoom(externalRef, tempC) {
|
||||
const last = lastGuestSyncAt.get(externalRef)
|
||||
if (last && Date.now() - last < SYNC_DEBOUNCE_MS) return
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT zd.zone_id, zd.location, z.sync_valves, z.exclude_bathroom
|
||||
FROM zone_devices zd JOIN zones z ON z.id = zd.zone_id
|
||||
WHERE zd.device_type = 'shelly_trv' AND zd.external_ref = $1`,
|
||||
[externalRef]
|
||||
)
|
||||
const row = rows[0]
|
||||
if (!row || !row.zone_id || !row.sync_valves) return
|
||||
|
||||
const sourceIsBathroom = (row.location || '').toLowerCase().includes('bathroom')
|
||||
if (row.exclude_bathroom && sourceIsBathroom) return // bathroom adjustments don't propagate
|
||||
|
||||
const { rows: siblings } = await pool.query(
|
||||
`SELECT external_ref, device_ip, location FROM zone_devices
|
||||
WHERE device_type = 'shelly_trv' AND zone_id = $1 AND external_ref != $2`,
|
||||
[row.zone_id, externalRef]
|
||||
)
|
||||
const targets = siblings.filter(s => !(row.exclude_bathroom && (s.location || '').toLowerCase().includes('bathroom')))
|
||||
if (!targets.length) return
|
||||
|
||||
lastGuestSyncAt.set(externalRef, Date.now())
|
||||
console.log(`[mqtt] guest adjusted ${externalRef} to ${tempC}°C — syncing ${targets.length} other valve(s) in zone ${row.zone_id}`)
|
||||
await batchSetZoneTemperature(targets.map(t => ({ external_ref: t.external_ref, device_ip: t.device_ip })), tempC)
|
||||
}
|
||||
|
||||
function topicMatchesStatus(topic) {
|
||||
return /^shellies\/(.+)\/thermostat\/0\/target_t$/.exec(topic)
|
||||
}
|
||||
|
||||
function scheduleReconnect() {
|
||||
if (connecting) return
|
||||
const delay = BROKER_RECONNECT_BACKOFF_MS[Math.min(reconnectAttempt, BROKER_RECONNECT_BACKOFF_MS.length - 1)]
|
||||
reconnectAttempt++
|
||||
console.warn(`[mqtt] broker unreachable — retrying in ${delay / 1000}s`)
|
||||
setTimeout(() => { connect().catch(() => {}) }, delay)
|
||||
}
|
||||
|
||||
export async function connect() {
|
||||
if (connecting || client?.connected) return
|
||||
connecting = true
|
||||
try {
|
||||
const creds = await getCredentials()
|
||||
await new Promise((resolve, reject) => {
|
||||
const c = mqtt.connect(`mqtt://${creds.host}:${creds.port}`, {
|
||||
username: creds.username,
|
||||
password: creds.password,
|
||||
clientId: `${CLIENT_NAME}-${Math.random().toString(16).slice(2, 8)}`,
|
||||
connectTimeout: 10000,
|
||||
reconnectPeriod: 0, // we own reconnect/backoff ourselves
|
||||
})
|
||||
|
||||
c.on('connect', () => {
|
||||
client = c
|
||||
reconnectAttempt = 0
|
||||
connecting = false
|
||||
console.log('[mqtt] connected to broker')
|
||||
c.subscribe(['shellies/announce', 'shellies/+/settings', 'shellies/+/thermostat/0/target_t'])
|
||||
resolve()
|
||||
})
|
||||
|
||||
c.on('message', (topic, message) => {
|
||||
let payload
|
||||
try { payload = JSON.parse(message.toString()) } catch { return }
|
||||
|
||||
if (topic === 'shellies/announce') {
|
||||
handleAnnounce(payload).catch(() => {})
|
||||
return
|
||||
}
|
||||
const settingsMatch = /^shellies\/(.+)\/settings$/.exec(topic)
|
||||
if (settingsMatch) {
|
||||
handleSettings(settingsMatch[1], payload).catch(() => {})
|
||||
return
|
||||
}
|
||||
const statusMatch = topicMatchesStatus(topic)
|
||||
if (statusMatch) {
|
||||
handleStatus(statusMatch[1], payload).catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
c.on('error', (err) => {
|
||||
console.error('[mqtt] connection error:', err.message)
|
||||
})
|
||||
|
||||
c.on('close', () => {
|
||||
if (client === c) client = null
|
||||
connecting = false
|
||||
scheduleReconnect()
|
||||
})
|
||||
|
||||
// mqtt.js's own connect() already retried internally on the initial attempt;
|
||||
// if it never even reaches 'connect' fire our own backoff.
|
||||
setTimeout(() => {
|
||||
if (!client) { c.end(true); connecting = false; reject(new Error('MQTT connect timed out')) }
|
||||
}, 12000)
|
||||
})
|
||||
} catch (err) {
|
||||
connecting = false
|
||||
console.error('[mqtt] could not connect (broker/credentials unavailable):', err.message)
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
export function isConnected() {
|
||||
return !!client?.connected
|
||||
}
|
||||
|
||||
export function getDiscoveredDevices() {
|
||||
return Array.from(discovered.values())
|
||||
}
|
||||
|
||||
// Publish a setpoint command to a single TRV. Does NOT wait for acknowledgment —
|
||||
// use setTargetWithRetry() for the full reliability pipeline.
|
||||
function publishTarget(externalRef, tempC) {
|
||||
if (!client?.connected) throw new Error('MQTT broker not connected')
|
||||
const topic = `shellies/${externalRef}/thermostat/0/command/target_t`
|
||||
client.publish(topic, String(tempC))
|
||||
}
|
||||
|
||||
async function waitForAck(externalRef, tempC, timeoutMs) {
|
||||
const start = Date.now()
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT current_target_temp, updated_at FROM zone_devices
|
||||
WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef]
|
||||
)
|
||||
const row = rows[0]
|
||||
if (row?.current_target_temp != null && Math.abs(Number(row.current_target_temp) - tempC) < 0.1
|
||||
&& new Date(row.updated_at).getTime() >= start) {
|
||||
return true
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 5000))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HTTP GET wake-up fallback — Shelly devices in deep sleep sometimes respond to a
|
||||
// plain HTTP GET even when not responding over MQTT. Best-effort only.
|
||||
async function tryHttpWakeUp(deviceIp) {
|
||||
if (!deviceIp) return false
|
||||
try {
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(() => ctrl.abort(), 10000)
|
||||
const res = await fetch(`http://${deviceIp}/status`, { signal: ctrl.signal })
|
||||
clearTimeout(timer)
|
||||
return res.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Set a single TRV's target temperature with exponential-backoff retry (30s -> 30min)
|
||||
// and an HTTP wake-up attempt before finally marking the device unresponsive.
|
||||
export async function setTargetWithRetry(device, tempC) {
|
||||
const { external_ref: externalRef, device_ip: deviceIp } = device
|
||||
|
||||
for (let attempt = 0; attempt < RETRY_DELAYS_MS.length; attempt++) {
|
||||
try {
|
||||
publishTarget(externalRef, tempC)
|
||||
} catch (err) {
|
||||
console.error(`[mqtt] publish failed for ${externalRef}:`, err.message)
|
||||
}
|
||||
|
||||
const acked = await waitForAck(externalRef, tempC, RETRY_DELAYS_MS[attempt])
|
||||
if (acked) {
|
||||
await pool.query(
|
||||
`UPDATE zone_devices SET health_state = 'healthy' WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef]
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
const healthState = attempt >= 5 ? 'poor' : attempt >= 3 ? 'degraded' : 'healthy'
|
||||
await pool.query(
|
||||
`UPDATE zone_devices SET health_state = $2 WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef, healthState]
|
||||
).catch(() => {})
|
||||
}
|
||||
|
||||
// All MQTT retries exhausted — try HTTP wake-up before giving up
|
||||
const wokeUp = await tryHttpWakeUp(deviceIp)
|
||||
if (wokeUp) {
|
||||
try { publishTarget(externalRef, tempC) } catch { /* ignore */ }
|
||||
const acked = await waitForAck(externalRef, tempC, 30000)
|
||||
if (acked) return true
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`UPDATE zone_devices SET health_state = 'unresponsive' WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef]
|
||||
).catch(() => {})
|
||||
console.error(`[mqtt] ${externalRef} failed to acknowledge target ${tempC}°C after ${RETRY_DELAYS_MS.length} attempts${wokeUp ? ' + HTTP wake-up' : ''}`)
|
||||
return false
|
||||
}
|
||||
|
||||
// Set temperature for multiple TRVs in a zone, staggered ~10s apart so several
|
||||
// battery-powered valves don't all wake their WiFi radio at once.
|
||||
export async function batchSetZoneTemperature(devices, tempC) {
|
||||
const results = {}
|
||||
for (let i = 0; i < devices.length; i++) {
|
||||
if (i > 0) await new Promise(r => setTimeout(r, STAGGER_MS))
|
||||
results[devices[i].external_ref] = await setTargetWithRetry(devices[i], tempC)
|
||||
}
|
||||
return results
|
||||
}
|
||||
80
backend/src/lib/newbook.js
Normal file
80
backend/src/lib/newbook.js
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// Adapted (near-verbatim) from room-planner/backend/src/lib/newbook.js.
|
||||
// Credentials come from the shared settings service, never a docker-compose env var.
|
||||
const API_BASE = 'https://api.newbook.cloud/rest/'
|
||||
|
||||
async function getCredentials() {
|
||||
const url = `${process.env.SETTINGS_URL}/settings/api/internal/integration/newbook`
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${process.env.SETTINGS_SECRET}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!res.ok) throw new Error(`Settings service returned ${res.status} fetching NewBook credentials`)
|
||||
const s = await res.json()
|
||||
return {
|
||||
username: s.username || '',
|
||||
password: s.password || '',
|
||||
apiKey: s.api_key || '',
|
||||
region: s.region || 'eu',
|
||||
}
|
||||
}
|
||||
|
||||
async function callApi(endpoint, data = {}) {
|
||||
const creds = await getCredentials()
|
||||
if (!creds.username || !creds.password || !creds.apiKey) {
|
||||
throw new Error('NewBook API credentials not configured')
|
||||
}
|
||||
|
||||
// Single-hotel scope — matches room-planner's convention, no multi-property support.
|
||||
const locationId = process.env.NEWBOOK_LOCATION_ID
|
||||
const body = { ...data, region: creds.region, api_key: creds.apiKey }
|
||||
if (locationId) body.location_id = locationId
|
||||
|
||||
const auth = Buffer.from(`${creds.username}:${creds.password}`).toString('base64')
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(() => ctrl.abort(), 30000)
|
||||
|
||||
try {
|
||||
const res = await fetch(API_BASE + endpoint, {
|
||||
method: 'POST',
|
||||
signal: ctrl.signal,
|
||||
headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${auth}` },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
clearTimeout(timer)
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '')
|
||||
throw new Error(`NewBook API ${res.status}: ${text.slice(0, 200)}`)
|
||||
}
|
||||
return await res.json()
|
||||
} catch (err) {
|
||||
clearTimeout(timer)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch all sites (rooms) — used by the zones sync + include/exclude checklist.
|
||||
export async function fetchSites() {
|
||||
const res = await callApi('sites_list', {})
|
||||
return res?.data ?? []
|
||||
}
|
||||
|
||||
// Fetch bookings whose stay overlaps the date window (list_type 'staying' includes
|
||||
// a booking arriving on period_to). This is what the scheduler polls to build the
|
||||
// room state machine — see lib/scheduler.js.
|
||||
export async function fetchBookings(fromDate, toDate) {
|
||||
const res = await callApi('bookings_list', {
|
||||
period_from: `${fromDate} 00:00:00`,
|
||||
period_to: `${toDate} 23:59:59`,
|
||||
list_type: 'staying',
|
||||
})
|
||||
return res?.data ?? []
|
||||
}
|
||||
|
||||
export async function testConnection() {
|
||||
try {
|
||||
const sites = await fetchSites()
|
||||
return { ok: true, message: `Connected. Found ${sites.length} site(s).` }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err.message }
|
||||
}
|
||||
}
|
||||
238
backend/src/lib/scheduler.js
Normal file
238
backend/src/lib/scheduler.js
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
// Room state machine + should_heat decision, ported from the retired
|
||||
// homeassistant-newbook-heating-component's booking_processor.py / heating_controller.py
|
||||
// (see /docs/HEATING_LOGIC.md in that archive for the worked examples this was tested
|
||||
// against: walk-in immediate heat, advance-booking pre-heat, multi-day stay, departed
|
||||
// cooling). All time math runs in Europe/London via luxon so the BST/GMT transition
|
||||
// doesn't silently break "minutes before a wall-clock time" arithmetic.
|
||||
import { DateTime } from 'luxon'
|
||||
import { pool, getConfig, logActivity } from '../db.js'
|
||||
import { fetchBookings } from './newbook.js'
|
||||
import { batchSetZoneTemperature } from './mqtt.js'
|
||||
|
||||
const TZ = 'Europe/London'
|
||||
const ACTIVE_BOOKING_STATUSES = ['confirmed', 'unconfirmed', 'arrived']
|
||||
const HEAT_STATES = ['heating_up', 'occupied']
|
||||
const COOL_STATES = ['vacant', 'cooling_down', 'booked']
|
||||
|
||||
let timerHandle = null
|
||||
let running = false
|
||||
|
||||
function parseNbDateTime(str) {
|
||||
if (!str) return null
|
||||
const dt = DateTime.fromFormat(str, 'yyyy-MM-dd HH:mm:ss', { zone: TZ })
|
||||
if (dt.isValid) return dt
|
||||
const dateOnly = DateTime.fromFormat(str, 'yyyy-MM-dd', { zone: TZ })
|
||||
return dateOnly.isValid ? dateOnly : null
|
||||
}
|
||||
|
||||
function parseHHMMSS(str, fallback) {
|
||||
if (!str) return fallback
|
||||
const parts = str.split(':').map(Number)
|
||||
if (parts.some(Number.isNaN)) return fallback
|
||||
return { hour: parts[0], minute: parts[1] || 0 }
|
||||
}
|
||||
|
||||
// calculate_heating_schedule() — heating_start = arrival - heating_offset_minutes,
|
||||
// cooling_start = departure + cooling_offset_minutes (cooling_offset can be negative
|
||||
// to stop heating BEFORE checkout). Arrival uses the EARLIER of actual vs default
|
||||
// arrival time; departure uses the LATER of actual vs default departure time.
|
||||
export function calculateHeatingSchedule(zone, booking, defaults) {
|
||||
if (!booking) return null
|
||||
const arrivalRaw = parseNbDateTime(booking.booking_arrival)
|
||||
const departureRaw = parseNbDateTime(booking.booking_departure)
|
||||
if (!arrivalRaw || !departureRaw) return null
|
||||
|
||||
const defaultArrival = parseHHMMSS(defaults.default_arrival_time, { hour: 15, minute: 0 })
|
||||
const defaultDeparture = parseHHMMSS(defaults.default_departure_time, { hour: 10, minute: 0 })
|
||||
|
||||
const actualArrivalMins = arrivalRaw.hour * 60 + arrivalRaw.minute
|
||||
const defaultArrivalMins = defaultArrival.hour * 60 + defaultArrival.minute
|
||||
const earliestArrivalMins = Math.min(actualArrivalMins, defaultArrivalMins)
|
||||
const arrival = arrivalRaw.startOf('day').plus({ minutes: earliestArrivalMins })
|
||||
|
||||
const actualDepartureMins = departureRaw.hour * 60 + departureRaw.minute
|
||||
const defaultDepartureMins = defaultDeparture.hour * 60 + defaultDeparture.minute
|
||||
const latestDepartureMins = Math.max(actualDepartureMins, defaultDepartureMins)
|
||||
const departure = departureRaw.startOf('day').plus({ minutes: latestDepartureMins })
|
||||
|
||||
const heatingStart = arrival.plus({ minutes: -zone.heating_offset_min })
|
||||
const coolingStart = departure.plus({ minutes: zone.cooling_offset_min })
|
||||
|
||||
return { heatingStart, coolingStart, arrival, departure }
|
||||
}
|
||||
|
||||
// determine_room_state() — priority order: 1) explicit booking status (arrived/departed
|
||||
// override everything), 2) time-based state from the schedule, 3) vacant if no booking.
|
||||
export function determineRoomState(booking, schedule, now) {
|
||||
if (!booking) return 'vacant'
|
||||
const status = (booking.booking_status || '').toLowerCase()
|
||||
|
||||
if (status === 'departed') return 'cooling_down'
|
||||
if (status === 'arrived') return 'occupied'
|
||||
|
||||
if (!schedule) return 'booked'
|
||||
const { heatingStart, coolingStart, arrival } = schedule
|
||||
if (!heatingStart || !coolingStart) return 'booked'
|
||||
|
||||
// A booking arriving on a future date shouldn't show as "booked" today.
|
||||
if (arrival.toISODate() > now.toISODate()) return 'vacant'
|
||||
|
||||
// heating_up covers both pre-arrival preheat AND "past arrival but not checked
|
||||
// in yet" — keep heating until the PMS actually marks the guest arrived.
|
||||
if (now >= heatingStart && now < coolingStart) return 'heating_up'
|
||||
if (now >= coolingStart) return 'cooling_down'
|
||||
if (now < heatingStart) return 'booked'
|
||||
return 'vacant' // shouldn't happen
|
||||
}
|
||||
|
||||
// should_heat() — auto mode AND an active booking status AND the room state in
|
||||
// [heating_up, occupied]. All three must hold.
|
||||
export function shouldHeat(booking, roomState, autoMode) {
|
||||
if (!autoMode) return false
|
||||
if (!booking) return false
|
||||
const status = (booking.booking_status || '').toLowerCase()
|
||||
if (!ACTIVE_BOOKING_STATUSES.includes(status)) return false
|
||||
return HEAT_STATES.includes(roomState)
|
||||
}
|
||||
|
||||
async function getZoneDevices(zoneId) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, external_ref, device_ip, device_type FROM zone_devices WHERE zone_id = $1`,
|
||||
[zoneId]
|
||||
)
|
||||
return rows
|
||||
}
|
||||
|
||||
async function applyTarget(zone, tempC) {
|
||||
const devices = await getZoneDevices(zone.id)
|
||||
const trvs = devices.filter(d => d.device_type === 'shelly_trv')
|
||||
if (!trvs.length) return { ok: false, reason: 'no_devices' }
|
||||
const results = await batchSetZoneTemperature(trvs, tempC)
|
||||
const successful = Object.values(results).filter(Boolean).length
|
||||
return { ok: successful > 0, successful, total: trvs.length }
|
||||
}
|
||||
|
||||
// Apply heating logic ONLY at state transitions — never poll-and-reassert during
|
||||
// 'occupied', which would stomp a guest's button/WS adjustment made mid-stay.
|
||||
async function applyStateTransition(zone, oldState, newState) {
|
||||
const target = HEAT_STATES.includes(newState) ? Number(zone.occupied_temp) : Number(zone.vacant_temp)
|
||||
const result = await applyTarget(zone, target)
|
||||
await logActivity(zone.id, 'transition', {
|
||||
fromState: oldState,
|
||||
toState: newState,
|
||||
note: result.ok
|
||||
? `Set ${target}°C (${result.successful}/${result.total} devices)`
|
||||
: `Failed to set ${target}°C (${result.reason || `${result.successful || 0}/${result.total || 0} devices`})`,
|
||||
source: 'scheduler',
|
||||
})
|
||||
}
|
||||
|
||||
async function getZoneState(zoneId) {
|
||||
const { rows } = await pool.query('SELECT * FROM zone_state WHERE zone_id = $1', [zoneId])
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
async function saveZoneState(zoneId, roomState, bookingStatus) {
|
||||
await pool.query(
|
||||
`INSERT INTO zone_state (zone_id, room_state, last_booking_status, last_transition_at, updated_at)
|
||||
VALUES ($1, $2, $3, NOW(), NOW())
|
||||
ON CONFLICT (zone_id) DO UPDATE SET
|
||||
room_state = EXCLUDED.room_state,
|
||||
last_booking_status = EXCLUDED.last_booking_status,
|
||||
last_transition_at = CASE WHEN zone_state.room_state != EXCLUDED.room_state THEN NOW() ELSE zone_state.last_transition_at END,
|
||||
updated_at = NOW()`,
|
||||
[zoneId, roomState, bookingStatus]
|
||||
)
|
||||
}
|
||||
|
||||
// One poll cycle: fetch bookings once, walk every active room zone, apply heating
|
||||
// logic only where the room's state has actually changed since the last cycle.
|
||||
export async function pollOnce() {
|
||||
const defaults = {
|
||||
default_arrival_time: await getConfig('default_arrival_time', '15:00:00'),
|
||||
default_departure_time: await getConfig('default_departure_time', '10:00:00'),
|
||||
}
|
||||
|
||||
const now = DateTime.now().setZone(TZ)
|
||||
const today = now.toISODate()
|
||||
|
||||
const { rows: zones } = await pool.query(
|
||||
`SELECT * FROM zones WHERE active = TRUE AND zone_type = 'room' AND newbook_site_id IS NOT NULL`
|
||||
)
|
||||
if (!zones.length) return
|
||||
|
||||
// Fail-safe: if NewBook is unreachable, keep every zone's last-known-good state —
|
||||
// "fetch failed" must never be treated the same as "no booking" (that would turn
|
||||
// off heating in an occupied room on a transient API blip).
|
||||
let bookings
|
||||
try {
|
||||
bookings = await fetchBookings(today, today)
|
||||
} catch (err) {
|
||||
console.error('[scheduler] NewBook fetch failed — keeping last-known-good state:', err.message)
|
||||
await logActivity(null, 'error', { note: `NewBook poll failed: ${err.message}`, source: 'scheduler' })
|
||||
return
|
||||
}
|
||||
|
||||
const bookingsBySite = new Map()
|
||||
for (const b of bookings) {
|
||||
const siteId = String(b.site_id ?? b.room_id ?? '')
|
||||
if (!siteId) continue
|
||||
// If multiple bookings overlap today for a site, prefer the one that's
|
||||
// actually arrived, then the one arriving soonest.
|
||||
const existing = bookingsBySite.get(siteId)
|
||||
if (!existing) { bookingsBySite.set(siteId, b); continue }
|
||||
const existingStatus = (existing.booking_status || '').toLowerCase()
|
||||
const candidateStatus = (b.booking_status || '').toLowerCase()
|
||||
if (candidateStatus === 'arrived' && existingStatus !== 'arrived') bookingsBySite.set(siteId, b)
|
||||
}
|
||||
|
||||
for (const zone of zones) {
|
||||
try {
|
||||
const booking = bookingsBySite.get(String(zone.newbook_site_id)) || null
|
||||
|
||||
// Cache the booking on every successful fetch so a future failed fetch has
|
||||
// something to fall back to (booking_cache is per-zone, TTL is implicit —
|
||||
// the fail-safe path above never even reaches this loop on a failed fetch).
|
||||
await pool.query(
|
||||
`INSERT INTO booking_cache (zone_id, booking_data, fetched_at) VALUES ($1, $2, NOW())
|
||||
ON CONFLICT (zone_id) DO UPDATE SET booking_data = EXCLUDED.booking_data, fetched_at = NOW()`,
|
||||
[zone.id, booking ? JSON.stringify(booking) : null]
|
||||
)
|
||||
|
||||
const schedule = booking ? calculateHeatingSchedule(zone, booking, defaults) : null
|
||||
const newState = determineRoomState(booking, schedule, now)
|
||||
const prev = await getZoneState(zone.id)
|
||||
const oldState = prev?.room_state || 'vacant'
|
||||
|
||||
await saveZoneState(zone.id, newState, booking?.booking_status || null)
|
||||
|
||||
if (!zone.auto_mode) continue // manual override in effect — don't touch setpoints
|
||||
if (newState === oldState) continue // no transition — never poll-and-reassert
|
||||
|
||||
await applyStateTransition(zone, oldState, newState)
|
||||
} catch (err) {
|
||||
console.error(`[scheduler] zone ${zone.id} update failed:`, err.message)
|
||||
await logActivity(zone.id, 'error', { note: err.message, source: 'scheduler' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function startScheduler() {
|
||||
const minutes = Number(await getConfig('poll_interval_minutes', 10)) || 10
|
||||
const intervalMs = Math.max(1, minutes) * 60 * 1000
|
||||
|
||||
const tick = async () => {
|
||||
if (running) return
|
||||
running = true
|
||||
try { await pollOnce() } catch (err) { console.error('[scheduler] poll failed:', err.message) }
|
||||
running = false
|
||||
}
|
||||
|
||||
await tick()
|
||||
timerHandle = setInterval(tick, intervalMs)
|
||||
}
|
||||
|
||||
export function stopScheduler() {
|
||||
if (timerHandle) clearInterval(timerHandle)
|
||||
timerHandle = null
|
||||
}
|
||||
27
backend/src/routes/config.js
Normal file
27
backend/src/routes/config.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool } from '../db.js'
|
||||
|
||||
// Generic key/value config store (hk-planner/maintenance pattern). Zone-specific
|
||||
// settings (excluded_site_ids, etc.) go through their own routes in zones.js so
|
||||
// each has proper validation — this is the catch-all for simple scalar settings
|
||||
// like poll_interval_minutes, default_arrival_time, maintenance_url/api_key.
|
||||
export async function configRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
app.get('/api/config', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows } = await pool.query('SELECT key, value FROM config ORDER BY key')
|
||||
return Object.fromEntries(rows.map(r => [r.key, r.value]))
|
||||
})
|
||||
|
||||
app.put('/api/config/:key', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
const { key } = req.params
|
||||
const { value } = req.body || {}
|
||||
if (value === undefined) return reply.status(400).send({ error: 'value required' })
|
||||
await pool.query(
|
||||
`INSERT INTO config (key, value, updated_at) VALUES ($1, $2, NOW())
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`,
|
||||
[key, JSON.stringify(value)]
|
||||
)
|
||||
return { ok: true }
|
||||
})
|
||||
}
|
||||
160
backend/src/routes/devices.js
Normal file
160
backend/src/routes/devices.js
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
import { mkdir, unlink, writeFile } from 'fs/promises'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { join } from 'path'
|
||||
import sharp from 'sharp'
|
||||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool, logActivity } from '../db.js'
|
||||
import * as trvDriver from '../lib/drivers/trv.js'
|
||||
import * as haDriver from '../lib/drivers/homeassistant.js'
|
||||
import { createMaintenanceAsset } from '../lib/maintenance-client.js'
|
||||
|
||||
const ALLOWED_IMAGES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
|
||||
const PHOTO_TYPES = ['device', 'serial_plate']
|
||||
|
||||
// device_type -> driver implementing discover()/getStatus()/setTarget(). Phase 2/3
|
||||
// types (mhi_modbus, midea, daikin) are enum values only — no driver yet.
|
||||
const DRIVERS = {
|
||||
shelly_trv: trvDriver,
|
||||
home_assistant: haDriver,
|
||||
}
|
||||
const NOT_YET_IMPLEMENTED = ['mhi_modbus', 'midea', 'daikin']
|
||||
|
||||
export async function deviceRoutes(app, opts) {
|
||||
const UPLOADS_DIR = opts.uploadsDir
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
// GET /api/devices — every mapped + unassigned device, with zone name and photo count
|
||||
app.get('/api/devices', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows } = await pool.query(`
|
||||
SELECT zd.*, z.name AS zone_name,
|
||||
(SELECT COUNT(*)::int FROM device_photos p WHERE p.device_id = zd.id) AS photo_count
|
||||
FROM zone_devices zd
|
||||
LEFT JOIN zones z ON z.id = zd.zone_id
|
||||
ORDER BY zd.zone_id NULLS FIRST, zd.device_type, zd.discovered_name
|
||||
`)
|
||||
return rows
|
||||
})
|
||||
|
||||
// POST /api/devices/discover — { device_type } -> runs that driver's discover(),
|
||||
// and inserts any newly-seen device as an unassigned row (never auto-linked to a zone).
|
||||
app.post('/api/devices/discover', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const { device_type } = req.body || {}
|
||||
if (!device_type) return reply.status(400).send({ error: 'device_type required' })
|
||||
|
||||
if (NOT_YET_IMPLEMENTED.includes(device_type)) {
|
||||
return reply.status(200).send({
|
||||
ok: true, devices: [],
|
||||
note: `${device_type} discovery isn't implemented yet — Phase 1 only covers Shelly TRVs. ` +
|
||||
`This device type exists as a column enum value ready for its Phase 2/3 driver.`,
|
||||
})
|
||||
}
|
||||
|
||||
const driver = DRIVERS[device_type]
|
||||
if (!driver) return reply.status(400).send({ error: `Unknown device_type: ${device_type}` })
|
||||
|
||||
const result = await driver.discover()
|
||||
if (!result.ok) return reply.status(200).send(result) // e.g. broker/HA not reachable — not a hard error
|
||||
|
||||
let discoveredCount = 0
|
||||
for (const d of result.devices) {
|
||||
const res = await pool.query(
|
||||
`INSERT INTO zone_devices (device_type, external_ref, discovered_name)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (device_type, external_ref) DO UPDATE SET discovered_name = EXCLUDED.discovered_name, last_seen = NOW()
|
||||
RETURNING (xmax = 0) AS inserted`,
|
||||
[device_type, d.external_ref, d.discovered_name || d.external_ref]
|
||||
)
|
||||
if (res.rows[0].inserted) discoveredCount++
|
||||
}
|
||||
|
||||
return { ok: true, found: result.devices.length, new: discoveredCount }
|
||||
})
|
||||
|
||||
// PATCH /api/devices/:id — zone/location assignment (a living mapping, not a one-time wizard)
|
||||
app.patch('/api/devices/:id', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const { rows: existing } = await pool.query('SELECT * FROM zone_devices WHERE id = $1', [req.params.id])
|
||||
if (!existing.length) return reply.status(404).send({ error: 'Device not found' })
|
||||
const d = existing[0]
|
||||
const { zone_id, location } = req.body || {}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE zone_devices SET zone_id = $1, location = $2, updated_at = NOW() WHERE id = $3 RETURNING *`,
|
||||
[zone_id !== undefined ? zone_id : d.zone_id, location !== undefined ? location : d.location, req.params.id]
|
||||
)
|
||||
return rows[0]
|
||||
})
|
||||
|
||||
// POST /api/devices/:id/photos — multipart: file + photo_type (device | serial_plate)
|
||||
app.post('/api/devices/:id/photos', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const deviceId = parseInt(req.params.id)
|
||||
const { rows } = await pool.query('SELECT id FROM zone_devices WHERE id = $1', [deviceId])
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Device not found' })
|
||||
|
||||
let fileData = null, photoType = 'device'
|
||||
for await (const part of req.parts()) {
|
||||
if (part.type === 'file') {
|
||||
if (!ALLOWED_IMAGES.includes(part.mimetype)) {
|
||||
return reply.status(400).send({ error: 'Only JPEG, PNG and WebP images are allowed' })
|
||||
}
|
||||
const chunks = []
|
||||
for await (const chunk of part.file) chunks.push(chunk)
|
||||
const raw = Buffer.concat(chunks)
|
||||
|
||||
// Auto-rotate (phone EXIF), resize to 1800px max, re-encode as JPEG — same as maintenance's task_photos.
|
||||
const processed = await sharp(raw)
|
||||
.rotate()
|
||||
.resize(1800, 1800, { fit: 'inside', withoutEnlargement: true })
|
||||
.jpeg({ quality: 82, progressive: true })
|
||||
.toBuffer()
|
||||
|
||||
const filename = randomUUID() + '.jpg'
|
||||
const dir = join(UPLOADS_DIR, 'devices', String(deviceId))
|
||||
await mkdir(dir, { recursive: true })
|
||||
await writeFile(join(dir, filename), processed)
|
||||
fileData = { originalName: part.filename, savedAs: filename, size: processed.length }
|
||||
} else {
|
||||
const val = await part.value
|
||||
if (part.fieldname === 'photo_type' && PHOTO_TYPES.includes(String(val))) photoType = String(val)
|
||||
}
|
||||
}
|
||||
if (!fileData?.savedAs) return reply.status(400).send({ error: 'No file uploaded' })
|
||||
|
||||
const filePath = `/devices/${deviceId}/${fileData.savedAs}`
|
||||
const { rows: ins } = await pool.query(
|
||||
`INSERT INTO device_photos (device_id, file_name, file_path, mime_type, file_size, photo_type, uploaded_by)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
|
||||
[deviceId, fileData.originalName, filePath, 'image/jpeg', fileData.size, photoType, req.user.email]
|
||||
)
|
||||
return ins[0]
|
||||
})
|
||||
|
||||
app.get('/api/devices/:id/photos', { preHandler: requireCap('view') }, async (req) => {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT * FROM device_photos WHERE device_id = $1 ORDER BY uploaded_at DESC',
|
||||
[req.params.id]
|
||||
)
|
||||
return rows
|
||||
})
|
||||
|
||||
app.delete('/api/photos/:id', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const { rows } = await pool.query('SELECT * FROM device_photos WHERE id = $1', [req.params.id])
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Not found' })
|
||||
await unlink(join(UPLOADS_DIR, rows[0].file_path)).catch(() => {})
|
||||
await pool.query('DELETE FROM device_photos WHERE id = $1', [req.params.id])
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
// POST /api/devices/:id/create-maintenance-asset — explicit stub. Real integration
|
||||
// needs maintenance's own Settings -> API Keys page + POST /api/public/assets first
|
||||
// (see lib/maintenance-client.js). Returns a clear "not implemented" response rather
|
||||
// than faking a cross-app call.
|
||||
app.post('/api/devices/:id/create-maintenance-asset', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT zd.*, z.name AS zone_name FROM zone_devices zd LEFT JOIN zones z ON z.id = zd.zone_id WHERE zd.id = $1`,
|
||||
[req.params.id]
|
||||
)
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Device not found' })
|
||||
const result = await createMaintenanceAsset(rows[0], { name: rows[0].zone_name })
|
||||
return reply.status(501).send(result)
|
||||
})
|
||||
}
|
||||
41
backend/src/routes/override.js
Normal file
41
backend/src/routes/override.js
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool, logActivity } from '../db.js'
|
||||
import { batchSetZoneTemperature } from '../lib/mqtt.js'
|
||||
|
||||
// Manual force-temperature — the equivalent of the old integration's
|
||||
// newbook.force_room_temperature service. Disables auto mode for the zone so the
|
||||
// scheduler leaves it alone until staff switch auto mode back on (zones.js PATCH).
|
||||
export async function overrideRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
app.post('/api/zones/:id/override', { preHandler: requireCap('control') }, async (req, reply) => {
|
||||
const { temp_c } = req.body || {}
|
||||
const tempC = Number(temp_c)
|
||||
if (!Number.isFinite(tempC)) return reply.status(400).send({ error: 'temp_c must be a number' })
|
||||
|
||||
const { rows } = await pool.query('SELECT * FROM zones WHERE id = $1', [req.params.id])
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Zone not found' })
|
||||
const zone = rows[0]
|
||||
|
||||
await pool.query('UPDATE zones SET auto_mode = FALSE WHERE id = $1', [zone.id])
|
||||
|
||||
const { rows: devices } = await pool.query(
|
||||
`SELECT external_ref, device_ip FROM zone_devices WHERE zone_id = $1 AND device_type = 'shelly_trv'`,
|
||||
[zone.id]
|
||||
)
|
||||
if (!devices.length) {
|
||||
return reply.status(200).send({ ok: false, error: 'No TRVs mapped to this zone', auto_mode: false })
|
||||
}
|
||||
|
||||
const results = await batchSetZoneTemperature(devices, tempC)
|
||||
const successful = Object.values(results).filter(Boolean).length
|
||||
|
||||
await logActivity(zone.id, 'override', {
|
||||
note: `Manual override to ${tempC}°C (${successful}/${devices.length} devices, auto mode disabled)`,
|
||||
source: 'manual',
|
||||
userEmail: req.user.email,
|
||||
})
|
||||
|
||||
return { ok: successful > 0, successful, total: devices.length, auto_mode: false }
|
||||
})
|
||||
}
|
||||
25
backend/src/routes/settings.js
Normal file
25
backend/src/routes/settings.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { testConnection } from '../lib/newbook.js'
|
||||
import { isConnected as mqttConnected } from '../lib/mqtt.js'
|
||||
|
||||
// Settings-page-backing endpoints that don't fit the generic config.js key/value
|
||||
// store: connection tests and the MQTT broker's live status. The Home Assistant
|
||||
// integration itself is configured centrally in the shared `settings` app, not
|
||||
// here — this just reports whether it's reachable (via the driver's own no-op
|
||||
// behaviour when unconfigured).
|
||||
export async function settingsRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
app.post('/api/settings/newbook-test', { preHandler: requireCap('settings') }, async () => {
|
||||
return testConnection()
|
||||
})
|
||||
|
||||
app.get('/api/settings/mqtt-status', { preHandler: requireCap('settings') }, async () => {
|
||||
return {
|
||||
connected: mqttConnected(),
|
||||
note: mqttConnected()
|
||||
? 'Connected to the shared MQTT broker.'
|
||||
: 'Not connected — the shared MQTT broker (LXC 104) may not be provisioned yet, or hvac-backend has no credentials in settings.',
|
||||
}
|
||||
})
|
||||
}
|
||||
59
backend/src/routes/status.js
Normal file
59
backend/src/routes/status.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool } from '../db.js'
|
||||
import { isConnected as mqttConnected } from '../lib/mqtt.js'
|
||||
|
||||
export async function statusRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
// GET /api/status — live status per zone: room state, target temp, device health/battery
|
||||
app.get('/api/status', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows: zones } = await pool.query(`
|
||||
SELECT z.*, zs.room_state, zs.last_transition_at, zs.last_booking_status
|
||||
FROM zones z
|
||||
LEFT JOIN zone_state zs ON zs.zone_id = z.id
|
||||
WHERE z.active = TRUE
|
||||
ORDER BY z.zone_type, z.name
|
||||
`)
|
||||
|
||||
const { rows: devices } = await pool.query(`
|
||||
SELECT id, zone_id, device_type, external_ref, discovered_name, location,
|
||||
health_state, battery_pct, wifi_rssi, current_target_temp, target_origin, last_seen
|
||||
FROM zone_devices WHERE zone_id IS NOT NULL
|
||||
`)
|
||||
const devicesByZone = new Map()
|
||||
for (const d of devices) {
|
||||
if (!devicesByZone.has(d.zone_id)) devicesByZone.set(d.zone_id, [])
|
||||
devicesByZone.get(d.zone_id).push(d)
|
||||
}
|
||||
|
||||
return {
|
||||
mqtt_connected: mqttConnected(),
|
||||
zones: zones.map(z => ({
|
||||
...z,
|
||||
room_state: z.room_state || 'vacant',
|
||||
target_temp: ['heating_up', 'occupied'].includes(z.room_state) ? z.occupied_temp : z.vacant_temp,
|
||||
devices: devicesByZone.get(z.id) || [],
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
// GET /api/status/activity — recent activity log, optionally filtered by zone
|
||||
app.get('/api/status/activity', { preHandler: requireCap('view') }, async (req) => {
|
||||
const { zone_id, limit } = req.query || {}
|
||||
const lim = Math.min(parseInt(limit) || 100, 500)
|
||||
if (zone_id) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT al.*, z.name AS zone_name FROM activity_log al LEFT JOIN zones z ON z.id = al.zone_id
|
||||
WHERE al.zone_id = $1 ORDER BY al.created_at DESC LIMIT $2`,
|
||||
[zone_id, lim]
|
||||
)
|
||||
return rows
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
`SELECT al.*, z.name AS zone_name FROM activity_log al LEFT JOIN zones z ON z.id = al.zone_id
|
||||
ORDER BY al.created_at DESC LIMIT $1`,
|
||||
[lim]
|
||||
)
|
||||
return rows
|
||||
})
|
||||
}
|
||||
145
backend/src/routes/zones.js
Normal file
145
backend/src/routes/zones.js
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool, getConfig, setConfig, logActivity } from '../db.js'
|
||||
import { fetchSites, testConnection } from '../lib/newbook.js'
|
||||
|
||||
export async function zoneRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
// GET /api/zones — all zones with device counts
|
||||
app.get('/api/zones', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows } = await pool.query(`
|
||||
SELECT z.*, COUNT(zd.id)::int AS device_count
|
||||
FROM zones z
|
||||
LEFT JOIN zone_devices zd ON zd.zone_id = z.id
|
||||
GROUP BY z.id
|
||||
ORDER BY z.zone_type, z.name
|
||||
`)
|
||||
return rows
|
||||
})
|
||||
|
||||
// PATCH /api/zones/:id — per-zone config: temps, offsets, auto_mode, sync_valves, exclude_bathroom
|
||||
app.patch('/api/zones/:id', { preHandler: requireCap('schedule_edit') }, async (req, reply) => {
|
||||
const { rows: existing } = await pool.query('SELECT * FROM zones WHERE id = $1', [req.params.id])
|
||||
if (!existing.length) return reply.status(404).send({ error: 'Zone not found' })
|
||||
const z = existing[0]
|
||||
const {
|
||||
name, occupied_temp, vacant_temp, heating_offset_min, cooling_offset_min,
|
||||
auto_mode, sync_valves, exclude_bathroom,
|
||||
} = req.body || {}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE zones SET
|
||||
name = $1, occupied_temp = $2, vacant_temp = $3, heating_offset_min = $4,
|
||||
cooling_offset_min = $5, auto_mode = $6, sync_valves = $7, exclude_bathroom = $8
|
||||
WHERE id = $9 RETURNING *`,
|
||||
[
|
||||
name ?? z.name,
|
||||
occupied_temp ?? z.occupied_temp,
|
||||
vacant_temp ?? z.vacant_temp,
|
||||
heating_offset_min ?? z.heating_offset_min,
|
||||
cooling_offset_min ?? z.cooling_offset_min,
|
||||
auto_mode ?? z.auto_mode,
|
||||
sync_valves ?? z.sync_valves,
|
||||
exclude_bathroom ?? z.exclude_bathroom,
|
||||
req.params.id,
|
||||
]
|
||||
)
|
||||
if (auto_mode !== undefined && auto_mode !== z.auto_mode) {
|
||||
await logActivity(z.id, 'override', {
|
||||
note: auto_mode ? 'Auto mode re-enabled' : 'Auto mode disabled',
|
||||
source: 'manual',
|
||||
userEmail: req.user.email,
|
||||
})
|
||||
}
|
||||
return rows[0]
|
||||
})
|
||||
|
||||
// POST /api/zones — manual zone creation (public areas, or any non-NewBook device group)
|
||||
app.post('/api/zones', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
const { name, zone_type, occupied_temp, vacant_temp } = req.body || {}
|
||||
if (!name) return reply.status(400).send({ error: 'name required' })
|
||||
if (!['room', 'public_area'].includes(zone_type)) {
|
||||
return reply.status(400).send({ error: "zone_type must be 'room' or 'public_area'" })
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO zones (name, zone_type, source, newbook_site_id, occupied_temp, vacant_temp)
|
||||
VALUES ($1, $2, 'manual', NULL, $3, $4) RETURNING *`,
|
||||
[name, zone_type, occupied_temp || 22.0, vacant_temp || 16.0]
|
||||
)
|
||||
return rows[0]
|
||||
})
|
||||
|
||||
// ── NewBook include/exclude checklist (hk-planner's CategorySettings.tsx pattern) ──
|
||||
|
||||
// GET /api/zones/newbook-sites — live sites list + excluded flag, for the checklist UI
|
||||
app.get('/api/zones/newbook-sites', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
let sites
|
||||
try {
|
||||
sites = await fetchSites()
|
||||
} catch (err) {
|
||||
return reply.status(502).send({ error: `NewBook error: ${err.message}` })
|
||||
}
|
||||
const excluded = (await getConfig('excluded_site_ids', [])) || []
|
||||
return {
|
||||
sites: sites.map(s => ({
|
||||
site_id: String(s.site_id),
|
||||
site_name: s.site_name,
|
||||
category_name: s.category_name || null,
|
||||
excluded: excluded.includes(String(s.site_id)),
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
// PUT /api/zones/newbook-sites — save the excluded_site_ids list
|
||||
app.put('/api/zones/newbook-sites', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
const { excluded_site_ids } = req.body || {}
|
||||
if (!Array.isArray(excluded_site_ids)) return reply.status(400).send({ error: 'excluded_site_ids must be an array' })
|
||||
await setConfig('excluded_site_ids', excluded_site_ids.map(String))
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
app.post('/api/zones/newbook-test', { preHandler: requireCap('settings') }, async () => {
|
||||
return testConnection()
|
||||
})
|
||||
|
||||
// POST /api/zones/sync-newbook — upsert a zone per non-excluded site (maintenance's
|
||||
// locations.js sync-newbook pattern): ON CONFLICT (newbook_site_id) DO UPDATE, and
|
||||
// soft-deactivate (never delete) any previously-synced zone whose site disappeared.
|
||||
app.post('/api/zones/sync-newbook', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
let sites
|
||||
try {
|
||||
sites = await fetchSites()
|
||||
} catch (err) {
|
||||
return reply.status(502).send({ error: `NewBook error: ${err.message}` })
|
||||
}
|
||||
|
||||
const excluded = new Set((await getConfig('excluded_site_ids', [])) || [])
|
||||
const included = sites.filter(s => !excluded.has(String(s.site_id)))
|
||||
|
||||
let created = 0, updated = 0
|
||||
for (const site of included) {
|
||||
const siteId = String(site.site_id)
|
||||
const name = site.site_name || `Room ${siteId}`
|
||||
const res = await pool.query(
|
||||
`INSERT INTO zones (name, zone_type, source, newbook_site_id)
|
||||
VALUES ($1, 'room', 'newbook', $2)
|
||||
ON CONFLICT (newbook_site_id) DO UPDATE SET name = EXCLUDED.name, active = TRUE
|
||||
RETURNING (xmax = 0) AS inserted`,
|
||||
[name, siteId]
|
||||
)
|
||||
res.rows[0].inserted ? created++ : updated++
|
||||
}
|
||||
|
||||
// Zones synced from NewBook whose site is now excluded/gone are deactivated,
|
||||
// never deleted — preserves schedule config + activity history.
|
||||
const includedIds = included.map(s => String(s.site_id))
|
||||
await pool.query(
|
||||
`UPDATE zones SET active = FALSE
|
||||
WHERE source = 'newbook' AND newbook_site_id IS NOT NULL AND NOT (newbook_site_id = ANY($1))`,
|
||||
[includedIds.length ? includedIds : ['']]
|
||||
)
|
||||
|
||||
await logActivity(null, 'sync', { note: `NewBook sync: ${created} created, ${updated} updated`, source: 'sync', userEmail: req.user.email })
|
||||
return { ok: true, created, updated, total: included.length }
|
||||
})
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue