sse => ws

This commit is contained in:
Darius
2026-02-06 10:08:36 +01:00
parent 18708add17
commit 5866216e36
4 changed files with 189 additions and 46 deletions

View File

@@ -19,12 +19,12 @@ import { HomeAssistantService } from "./homeassistant/service.js";
import { TidalClient } from "./tidal/client.js";
import { TidalService } from "./tidal/service.js";
import { tidalRoutes } from "./tidal/routes.js";
import { sseRoutes } from "./sse/routes.js";
import { sseRoutes } from "./websocket/routes.js";
import { SseService } from "@dpu/shared";
import { HomepageService } from "./homepage/service.js";
import { homepageRoutes } from "./homepage/routes.js";
import fastifySSE from "@fastify/sse";
import fastifyCors from "@fastify/cors";
import fastifyWebsocket from "@fastify/websocket";
const fastify = Fastify().withTypeProvider<ZodTypeProvider>();
@@ -81,7 +81,7 @@ await fastify.register(fastifyAxios, {
},
});
await fastify.register(fastifySSE);
await fastify.register(fastifyWebsocket);
const haClient = new HomeAssistantClient(fastify.axios.homeassistant);
const haService = new HomeAssistantService(haClient);

View File

@@ -14,29 +14,26 @@ export async function sseRoutes(
"/dpu/events",
{
schema: {
description: "Register for SSE",
tags: ["sse"],
description: "Register for WebSocket events",
tags: ["ws"],
hide: true,
},
sse: true,
websocket: true,
},
async (_request, reply) => {
reply.sse.keepAlive();
(socket, _request) => {
const clientId = randomUUID();
const sendEvent = (event: SseEvent) => {
reply.sse.send({
event: event.type,
data: JSON.stringify(event.data),
});
if (socket.readyState === socket.OPEN) {
socket.send(JSON.stringify({ event: event.type, data: event.data }));
}
};
sseService.addClient({ id: clientId, send: sendEvent });
await reply.sse.send({ data: "Connected" });
socket.send(JSON.stringify({ event: "connected", data: "Connected" }));
logInfo(`Connection for client ${clientId} established`);
reply.sse.onClose(() => {
socket.on("close", () => {
sseService.removeClient(clientId);
logInfo(`Connection for client ${clientId} closed`);
});