aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorAutumn <git@autumnfo.rest>2026-05-12 18:31:59 +0100
committerAutumn <git@autumnfo.rest>2026-05-12 18:31:59 +0100
commita8addc5aaaecca292b7d2bdc3a848a795329a3b4 (patch)
tree6c28cdb7f0644708b0a66fe3062b7cbcbc549547 /src
parent56ccdf34d5a820fbdabb3674b2392b9d1e2b1ecf (diff)
[api] added device toggling API route
Diffstat (limited to 'src')
-rw-r--r--src/app.ts4
-rw-r--r--src/lib/helpers/device.ts20
-rw-r--r--src/routes/api.ts33
3 files changed, 56 insertions, 1 deletions
diff --git a/src/app.ts b/src/app.ts
index bdefefa..5000fbb 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -12,8 +12,10 @@ app.set("view engine", "pug")
app.set("views", "./src/views")
// setup routes
-import dashboardRouter from "@routes/dashboard"
+import apiRouter from "@routes/api.ts"
+import dashboardRouter from "@routes/dashboard.ts"
+app.use("/api", apiRouter)
app.use("/", dashboardRouter)
// export app
diff --git a/src/lib/helpers/device.ts b/src/lib/helpers/device.ts
new file mode 100644
index 0000000..42076cb
--- /dev/null
+++ b/src/lib/helpers/device.ts
@@ -0,0 +1,20 @@
+//
+// ~~~ device helper utilities
+//
+
+// imports
+import { sendMessage } from "@lib/mqtt.ts"
+import allDevices from "@lib/config/devices.ts"
+
+// set state
+export async function setState(device, state) {
+
+ const deviceInfo = allDevices.find((dev) => dev.id === device)
+
+ if (!deviceInfo) return false
+
+ const deviceTopic = `${deviceInfo.mqtt}/set`
+ const deviceMessage = JSON.stringify({ "state": state })
+
+ return sendMessage(deviceTopic, deviceMessage)
+}
diff --git a/src/routes/api.ts b/src/routes/api.ts
new file mode 100644
index 0000000..84a0f5d
--- /dev/null
+++ b/src/routes/api.ts
@@ -0,0 +1,33 @@
+//
+// ~~~ api routing
+//
+
+// imports
+import { Router } from "express"
+import { setState } from "@lib/helpers/device.ts"
+
+// setup router
+const router = Router()
+
+// toggle device
+router.get("/device/:id/toggle", async (req, res) => {
+
+ const device = req.params.id
+ const state = await setState(device, "TOGGLE")
+
+ console.debug(`-> toggling ${device}`)
+
+ if (state === false) {
+
+ console.error(`!> cannot toggle ${device}`)
+ res.sendStatus(500)
+
+ } else {
+
+ res.sendStatus(200)
+
+ }
+})
+
+// export router
+export default router