Compare commits
4 commits
852fa32c93
...
a7a7eeac0c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7a7eeac0c | ||
|
|
3dfc773590 | ||
|
|
cf66d9af6d | ||
|
|
0daba1bd73 |
13 changed files with 599 additions and 190 deletions
|
|
@ -375,8 +375,15 @@ export const relations = defineRelations(
|
|||
track,
|
||||
trackArtist,
|
||||
user,
|
||||
deviceConnection,
|
||||
},
|
||||
(r) => ({
|
||||
deviceConnection: {
|
||||
user: r.one.user({
|
||||
from: r.deviceConnection.userId,
|
||||
to: r.user.id,
|
||||
}),
|
||||
},
|
||||
artist: {
|
||||
artistGenres: r.many.artistGenre(),
|
||||
artistImages: r.many.artistImage(),
|
||||
|
|
@ -601,6 +608,7 @@ export const relations = defineRelations(
|
|||
from: r.user.id,
|
||||
to: r.party.hostId,
|
||||
}),
|
||||
deviceConnection: r.many.deviceConnection(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -10,14 +10,35 @@ import { pubsub, topic } from "./party-socket";
|
|||
|
||||
type DeviceSocketMessage =
|
||||
| { type: "device_message"; deviceId: string; payload: unknown }
|
||||
| { type: "device_status_request"; deviceId: string }
|
||||
| { type: "hello" }
|
||||
| { type: "device_event"; deviceId: string; event: PartySocketEvent };
|
||||
| { type: "device_event"; deviceId: string; event: DeviceProxyEvent };
|
||||
|
||||
type DeviceProxyEvent =
|
||||
| PartySocketEvent
|
||||
| { type: "device_connect_required" }
|
||||
| { type: "device_connected" };
|
||||
|
||||
type DeviceQuizResponsePayload = {
|
||||
QuizResponse: number;
|
||||
};
|
||||
|
||||
let devProxySocket: WebSocket | null = null;
|
||||
type DeviceConnectionRecord = typeof deviceConnection.$inferSelect;
|
||||
|
||||
type DevProxySocket = {
|
||||
send: (message: string) => unknown;
|
||||
};
|
||||
|
||||
let devProxySocket: DevProxySocket | null = null;
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string) {
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise<T>((_, reject) => {
|
||||
setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
function isDeviceMessage(
|
||||
value: unknown,
|
||||
|
|
@ -30,6 +51,17 @@ function isDeviceMessage(
|
|||
);
|
||||
}
|
||||
|
||||
function isDeviceStatusRequestMessage(
|
||||
value: unknown,
|
||||
): value is Extract<DeviceSocketMessage, { type: "device_status_request" }> {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
(value as { type?: unknown }).type === "device_status_request" &&
|
||||
typeof (value as { deviceId?: unknown }).deviceId === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function isDeviceQuizResponsePayload(
|
||||
value: unknown,
|
||||
): value is DeviceQuizResponsePayload {
|
||||
|
|
@ -41,16 +73,64 @@ function isDeviceQuizResponsePayload(
|
|||
);
|
||||
}
|
||||
|
||||
function sendDeviceEvent(deviceId: string, event: PartySocketEvent) {
|
||||
if (!devProxySocket || devProxySocket.readyState !== WebSocket.OPEN) return;
|
||||
function sendDeviceEvent(deviceId: string, event: DeviceProxyEvent) {
|
||||
if (!devProxySocket) {
|
||||
console.log("[device-socket] no dev proxy for event", deviceId, event.type);
|
||||
return;
|
||||
}
|
||||
|
||||
devProxySocket.send(
|
||||
JSON.stringify({
|
||||
type: "device_event",
|
||||
try {
|
||||
console.log("[device-socket] sending event", deviceId, event.type);
|
||||
devProxySocket.send(
|
||||
JSON.stringify({
|
||||
type: "device_event",
|
||||
deviceId,
|
||||
event,
|
||||
} satisfies DeviceSocketMessage),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[device-socket] failed to send event", error);
|
||||
devProxySocket = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function syncDeviceConnectionStatus(deviceId: string) {
|
||||
console.log("[device-socket] status request", deviceId);
|
||||
let device: DeviceConnectionRecord | undefined;
|
||||
try {
|
||||
console.log("[device-socket] lookup device start", deviceId);
|
||||
device = await withTimeout(
|
||||
db
|
||||
.select()
|
||||
.from(deviceConnection)
|
||||
.where(eq(deviceConnection.id, deviceId))
|
||||
.then((rows) => rows[0]),
|
||||
2_000,
|
||||
`device lookup ${deviceId}`,
|
||||
);
|
||||
console.log(
|
||||
"[device-socket] lookup device result",
|
||||
deviceId,
|
||||
event,
|
||||
} satisfies DeviceSocketMessage),
|
||||
);
|
||||
device ? "claimed" : "missing",
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[device-socket] lookup device failed", deviceId, error);
|
||||
sendDeviceEvent(deviceId, { type: "device_connect_required" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!device) {
|
||||
console.log("[device-socket] device unclaimed", deviceId);
|
||||
sendDeviceEvent(deviceId, { type: "device_connect_required" });
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[device-socket] device claimed", deviceId, device.userId);
|
||||
await db
|
||||
.update(deviceConnection)
|
||||
.set({ lastSeen: new Date() })
|
||||
.where(eq(deviceConnection.id, deviceId));
|
||||
sendDeviceEvent(deviceId, { type: "device_connected" });
|
||||
}
|
||||
|
||||
export async function claimDeviceForUser(deviceId: string, userId: string) {
|
||||
|
|
@ -75,7 +155,7 @@ export async function publishDeviceEventForUser(
|
|||
userId: string,
|
||||
event: PartySocketEvent,
|
||||
) {
|
||||
if (!devProxySocket || devProxySocket.readyState !== WebSocket.OPEN) return;
|
||||
if (!devProxySocket) return;
|
||||
|
||||
const devices = await db
|
||||
.select()
|
||||
|
|
@ -166,25 +246,27 @@ export const deviceSocketApp = new Elysia().group("/dev-socket", (app) =>
|
|||
.get("/test", () => ({ ok: 1 }))
|
||||
.ws("/ws", {
|
||||
open(ws) {
|
||||
devProxySocket = ws as unknown as WebSocket;
|
||||
console.log("[device-socket] dev proxy connected");
|
||||
devProxySocket = ws;
|
||||
ws.send(
|
||||
JSON.stringify({ type: "hello" } satisfies DeviceSocketMessage),
|
||||
);
|
||||
},
|
||||
message: async (_ws, message) => {
|
||||
if (typeof message !== "string") return;
|
||||
message: async (_ws, message: DeviceSocketMessage) => {
|
||||
if (typeof message !== "object") return;
|
||||
console.log("[device-socket] received", message.type);
|
||||
|
||||
let parsed: DeviceSocketMessage;
|
||||
try {
|
||||
parsed = JSON.parse(message) as DeviceSocketMessage;
|
||||
} catch {
|
||||
if (isDeviceStatusRequestMessage(message)) {
|
||||
await syncDeviceConnectionStatus(message.deviceId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isDeviceMessage(parsed)) return;
|
||||
await forwardDevicePayload(parsed.deviceId, parsed.payload);
|
||||
if (isDeviceMessage(message)) {
|
||||
await forwardDevicePayload(message.deviceId, message.payload);
|
||||
}
|
||||
},
|
||||
close() {
|
||||
console.log("[device-socket] dev proxy disconnected");
|
||||
if (devProxySocket === null) return;
|
||||
devProxySocket = null;
|
||||
},
|
||||
|
|
@ -198,6 +280,7 @@ export const deviceClaimApp = new Elysia()
|
|||
"/:deviceId/connect",
|
||||
async ({ user, params }) => {
|
||||
await claimDeviceForUser(params.deviceId, user.id);
|
||||
sendDeviceEvent(params.deviceId, { type: "device_connected" });
|
||||
return { ok: true, deviceId: params.deviceId, userId: user.id };
|
||||
},
|
||||
{ auth: true },
|
||||
|
|
|
|||
|
|
@ -4,58 +4,82 @@ type ApiEnvelope =
|
|||
| { type: "hello" }
|
||||
| { type: "device_event"; deviceId: string; event: unknown };
|
||||
|
||||
type DeviceMessage = {
|
||||
DeviceId: string;
|
||||
} | {
|
||||
QuizResponse: number;
|
||||
}
|
||||
type DeviceMessage =
|
||||
| {
|
||||
DeviceId: string;
|
||||
}
|
||||
| {
|
||||
QuizResponse: number;
|
||||
};
|
||||
|
||||
type DeviceQuestionData = {
|
||||
text: string;
|
||||
points: number;
|
||||
index: number;
|
||||
q_type: "Choice" | { Numeric: { min: number; max: number } }
|
||||
}
|
||||
text: string;
|
||||
points: number;
|
||||
index: number;
|
||||
q_type: "Choice" | { Numeric: { min: number; max: number } };
|
||||
};
|
||||
|
||||
type ProxyOutput =
|
||||
| { ConnectPrompt: string }
|
||||
| "WaitingForParty"
|
||||
| { Question: DeviceQuestionData }
|
||||
| "Results"
|
||||
| { Error: string };
|
||||
|
||||
type ApiMessage =
|
||||
| { type: "device_status_request"; deviceId: string }
|
||||
| { type: "device_message"; deviceId: string; payload: unknown };
|
||||
|
||||
type QuizQuestion =
|
||||
| {
|
||||
type: "choice";
|
||||
text: string;
|
||||
points: number;
|
||||
}
|
||||
| {
|
||||
type: "numeric";
|
||||
text: string;
|
||||
points: number;
|
||||
range: { min: number; max: number };
|
||||
};
|
||||
| {
|
||||
type: "choice";
|
||||
text: string;
|
||||
points: number;
|
||||
}
|
||||
| {
|
||||
type: "numeric";
|
||||
text: string;
|
||||
points: number;
|
||||
range: { min: number; max: number };
|
||||
};
|
||||
|
||||
type QuizState = {
|
||||
status: "running" | "results";
|
||||
questionIndex: number;
|
||||
currentQuestion: QuizQuestion | null;
|
||||
status: "running" | "results";
|
||||
questionIndex: number;
|
||||
currentQuestion: QuizQuestion | null;
|
||||
};
|
||||
|
||||
type PartyStatusEvent = {
|
||||
type: "party_status";
|
||||
party: { data?: QuizState } | null;
|
||||
type: "party_status";
|
||||
party: { data?: QuizState } | null;
|
||||
};
|
||||
|
||||
type QuizStateEvent = {
|
||||
type: "quiz_state";
|
||||
quiz: QuizState;
|
||||
type: "quiz_state";
|
||||
quiz: QuizState;
|
||||
};
|
||||
|
||||
type ErrorEvent = {
|
||||
type: "error";
|
||||
message: string;
|
||||
type: "error";
|
||||
message: string;
|
||||
};
|
||||
|
||||
type PartySocketEvent = PartyStatusEvent | QuizStateEvent | ErrorEvent;
|
||||
type DeviceLifecycleEvent =
|
||||
| { type: "device_connect_required" }
|
||||
| { type: "device_connected" };
|
||||
|
||||
type PartySocketEvent =
|
||||
| PartyStatusEvent
|
||||
| QuizStateEvent
|
||||
| ErrorEvent
|
||||
| DeviceLifecycleEvent;
|
||||
|
||||
const sockets = new Map<string, Socket>();
|
||||
const socketIds = new WeakMap<Socket, string>();
|
||||
const apiSocket = new WebSocket("ws://localhost:4000/api/dev-socket/ws");
|
||||
const API_SOCKET_URL = "ws://localhost:4000/api/dev-socket/ws";
|
||||
let apiSocket: WebSocket | null = null;
|
||||
let apiReconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const pendingDeviceStatus = new Set<string>();
|
||||
|
||||
function socketDeviceId(socket: Socket) {
|
||||
return socketIds.get(socket);
|
||||
|
|
@ -65,75 +89,155 @@ function registerSocket(socket: Socket, deviceId: string) {
|
|||
const existing = sockets.get(deviceId);
|
||||
if (existing && existing !== socket) existing.end();
|
||||
sockets.set(deviceId, socket);
|
||||
socketIds.set(socket, deviceId);
|
||||
console.log("Registered", socket.remoteAddress, deviceId);
|
||||
socketIds.set(socket, deviceId);
|
||||
console.log("Registered", socket.remoteAddress, deviceId);
|
||||
}
|
||||
|
||||
function toDeviceQuestionData(
|
||||
quizData: QuizState,
|
||||
): DeviceQuestionData | null {
|
||||
if (!quizData.currentQuestion) return null;
|
||||
const question = quizData.currentQuestion;
|
||||
const q_type =
|
||||
question.type === "choice"
|
||||
? "Choice"
|
||||
: { Numeric: { min: question.range.min, max: question.range.max } };
|
||||
function writeProxyOutput(socket: Socket, output: ProxyOutput) {
|
||||
socket.write(`${JSON.stringify(output)}\n`);
|
||||
}
|
||||
|
||||
return {
|
||||
text: question.text,
|
||||
points: question.points,
|
||||
index: quizData.questionIndex,
|
||||
q_type,
|
||||
};
|
||||
function sendApiMessage(message: ApiMessage) {
|
||||
if (!apiSocket || apiSocket.readyState !== WebSocket.OPEN) return false;
|
||||
console.log("API send", message.type, message.deviceId);
|
||||
apiSocket.send(JSON.stringify(message));
|
||||
return true;
|
||||
}
|
||||
|
||||
function requestDeviceStatus(deviceId: string) {
|
||||
pendingDeviceStatus.add(deviceId);
|
||||
if (sendApiMessage({ type: "device_status_request", deviceId })) {
|
||||
console.log("Requested device status", deviceId);
|
||||
pendingDeviceStatus.delete(deviceId);
|
||||
return;
|
||||
}
|
||||
console.log("Queued device status request", deviceId);
|
||||
}
|
||||
|
||||
function flushPendingDeviceStatus() {
|
||||
for (const deviceId of pendingDeviceStatus) {
|
||||
if (
|
||||
sockets.has(deviceId) &&
|
||||
sendApiMessage({ type: "device_status_request", deviceId })
|
||||
) {
|
||||
console.log("Flushed device status request", deviceId);
|
||||
pendingDeviceStatus.delete(deviceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function disconnectDeviceClients(reason: string) {
|
||||
console.log("Disconnecting device clients", reason, sockets.size);
|
||||
for (const socket of sockets.values()) {
|
||||
socket.end();
|
||||
}
|
||||
sockets.clear();
|
||||
pendingDeviceStatus.clear();
|
||||
}
|
||||
|
||||
function scheduleApiReconnect() {
|
||||
if (apiReconnectTimer) return;
|
||||
apiReconnectTimer = setTimeout(() => {
|
||||
apiReconnectTimer = null;
|
||||
connectApiSocket();
|
||||
}, 500);
|
||||
}
|
||||
|
||||
function connectApiSocket() {
|
||||
if (
|
||||
apiSocket?.readyState === WebSocket.OPEN ||
|
||||
apiSocket?.readyState === WebSocket.CONNECTING
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Connecting to API device socket");
|
||||
apiSocket = new WebSocket(API_SOCKET_URL);
|
||||
apiSocket.onmessage = handleApiMessage;
|
||||
apiSocket.onerror = (error) => {
|
||||
console.error("API device socket error", error);
|
||||
};
|
||||
apiSocket.onclose = () => {
|
||||
console.log("API device socket closed; reconnecting");
|
||||
apiSocket = null;
|
||||
disconnectDeviceClients("api socket closed");
|
||||
scheduleApiReconnect();
|
||||
};
|
||||
apiSocket.onopen = () => {
|
||||
console.log("Connected to API device socket");
|
||||
flushPendingDeviceStatus();
|
||||
};
|
||||
}
|
||||
|
||||
function toDeviceQuestionData(quizData: QuizState): DeviceQuestionData | null {
|
||||
if (!quizData.currentQuestion) return null;
|
||||
const question = quizData.currentQuestion;
|
||||
const q_type =
|
||||
question.type === "choice"
|
||||
? "Choice"
|
||||
: { Numeric: { min: question.range.min, max: question.range.max } };
|
||||
|
||||
return {
|
||||
text: question.text,
|
||||
points: question.points,
|
||||
index: quizData.questionIndex,
|
||||
q_type,
|
||||
};
|
||||
}
|
||||
|
||||
const listener = Bun.listen({
|
||||
port: 7070,
|
||||
hostname: "0.0.0.0",
|
||||
socket: {
|
||||
open(socket) {
|
||||
socket.setKeepAlive(true);
|
||||
console.log("Connection", socket.remoteAddress, socket.remotePort);
|
||||
},
|
||||
data(socket, buf) {
|
||||
const raw = new TextDecoder().decode(buf).trim();
|
||||
let data: DeviceMessage;
|
||||
try {
|
||||
data = JSON.parse(raw);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
console.log("Data", socket.remoteAddress, data);
|
||||
if (!data) return;
|
||||
socket: {
|
||||
open(socket) {
|
||||
socket.setKeepAlive(true);
|
||||
console.log("Connection", socket.remoteAddress, socket.remotePort);
|
||||
},
|
||||
data(socket, buf) {
|
||||
const raw = new TextDecoder().decode(buf).trim();
|
||||
let data: DeviceMessage;
|
||||
try {
|
||||
data = JSON.parse(raw);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
console.log("Data", socket.remoteAddress, data);
|
||||
if (!data) return;
|
||||
|
||||
if ("DeviceId" in data) {
|
||||
registerSocket(socket, data.DeviceId);
|
||||
return;
|
||||
}
|
||||
if ("QuizResponse" in data) {
|
||||
const deviceId = socketDeviceId(socket);
|
||||
if (!deviceId) return;
|
||||
apiSocket?.send(
|
||||
JSON.stringify({
|
||||
type: "device_message",
|
||||
deviceId,
|
||||
payload: { QuizResponse: data.QuizResponse },
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if ("DeviceId" in data) {
|
||||
registerSocket(socket, data.DeviceId);
|
||||
console.log(
|
||||
"Requesting device status",
|
||||
data.DeviceId,
|
||||
"apiState",
|
||||
apiSocket?.readyState,
|
||||
);
|
||||
requestDeviceStatus(data.DeviceId);
|
||||
return;
|
||||
}
|
||||
if ("QuizResponse" in data) {
|
||||
const deviceId = socketDeviceId(socket);
|
||||
if (!deviceId) return;
|
||||
sendApiMessage({
|
||||
type: "device_message",
|
||||
deviceId,
|
||||
payload: { QuizResponse: data.QuizResponse },
|
||||
});
|
||||
return;
|
||||
}
|
||||
},
|
||||
close(socket) {
|
||||
console.log("Connection", socket.remoteAddress);
|
||||
console.log("Connection", socket.remoteAddress);
|
||||
const deviceId = socketDeviceId(socket);
|
||||
if (deviceId && sockets.get(deviceId) === socket) {
|
||||
sockets.delete(deviceId);
|
||||
pendingDeviceStatus.delete(deviceId);
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
apiSocket.onmessage = (e) => {
|
||||
function handleApiMessage(e: MessageEvent) {
|
||||
let message: ApiEnvelope;
|
||||
try {
|
||||
message = JSON.parse(e.data) as ApiEnvelope;
|
||||
|
|
@ -141,12 +245,29 @@ apiSocket.onmessage = (e) => {
|
|||
return;
|
||||
}
|
||||
|
||||
console.log("API recv", message.type);
|
||||
if (message.type !== "device_event") return;
|
||||
const socket = sockets.get(message.deviceId);
|
||||
if (!socket) return;
|
||||
if (!socket) {
|
||||
console.log("No TCP socket for API event", message.deviceId);
|
||||
return;
|
||||
}
|
||||
const event = message.event as PartySocketEvent;
|
||||
console.log("API device event", message.deviceId, event.type);
|
||||
if (event.type === "device_connect_required") {
|
||||
console.log("Writing connect prompt", message.deviceId);
|
||||
writeProxyOutput(socket, { ConnectPrompt: message.deviceId });
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "device_connected") {
|
||||
console.log("Writing waiting-for-party", message.deviceId);
|
||||
writeProxyOutput(socket, "WaitingForParty");
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "error") {
|
||||
socket.write(`${JSON.stringify({ Error: event.message })}\n`);
|
||||
writeProxyOutput(socket, { Error: event.message });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -154,31 +275,27 @@ apiSocket.onmessage = (e) => {
|
|||
const quizData = event.party?.data ?? null;
|
||||
if (!quizData) return;
|
||||
const question = toDeviceQuestionData(quizData);
|
||||
socket.write(
|
||||
`${JSON.stringify({ Question: question, Status: quizData.status })}\n`,
|
||||
);
|
||||
if (question) {
|
||||
writeProxyOutput(socket, { Question: question });
|
||||
} else if (quizData.status === "results") {
|
||||
writeProxyOutput(socket, "Results");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "quiz_state") {
|
||||
const question = toDeviceQuestionData(event.quiz);
|
||||
socket.write(
|
||||
`${JSON.stringify({ Question: question, Status: event.quiz.status })}\n`,
|
||||
);
|
||||
if (question) {
|
||||
writeProxyOutput(socket, { Question: question });
|
||||
} else if (event.quiz.status === "results") {
|
||||
writeProxyOutput(socket, "Results");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
socket.write(`${JSON.stringify(message.event)}\n`);
|
||||
};
|
||||
writeProxyOutput(socket, { Error: "Unsupported proxy event." });
|
||||
}
|
||||
|
||||
|
||||
|
||||
apiSocket.onerror = (error) => {
|
||||
console.error(error);
|
||||
};
|
||||
|
||||
apiSocket.onopen = () => {
|
||||
console.log("Connected to API device socket");
|
||||
};
|
||||
connectApiSocket();
|
||||
|
||||
console.log(`Started on :${listener.port}`);
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "dev-proxy",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5"
|
||||
}
|
||||
"name": "dev-proxy",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,29 +1,29 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
// Environment setup & latest features
|
||||
"lib": ["ESNext"],
|
||||
"target": "ESNext",
|
||||
"module": "Preserve",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
"allowJs": true,
|
||||
"compilerOptions": {
|
||||
// Environment setup & latest features
|
||||
"lib": ["ESNext"],
|
||||
"target": "ESNext",
|
||||
"module": "Preserve",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
"allowJs": true,
|
||||
|
||||
// Bundler mode
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
// Bundler mode
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
|
||||
// Best practices
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
// Best practices
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
|
||||
// Some stricter flags (disabled by default)
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noPropertyAccessFromIndexSignature": false
|
||||
}
|
||||
// Some stricter flags (disabled by default)
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noPropertyAccessFromIndexSignature": false
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,9 @@ const DOT: char = char::from_u32(0b1010_0101).unwrap();
|
|||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ViewState {
|
||||
Loading,
|
||||
Reconnecting,
|
||||
ConnectPrompt,
|
||||
WaitingForParty,
|
||||
Question,
|
||||
Results,
|
||||
}
|
||||
|
|
@ -44,6 +47,8 @@ pub struct QuestionDataNet<'a> {
|
|||
|
||||
#[derive(Deserialize)]
|
||||
pub enum ProxyOutput<'a> {
|
||||
ConnectPrompt(&'a str),
|
||||
WaitingForParty,
|
||||
Question(QuestionDataNet<'a>),
|
||||
Results,
|
||||
Error(&'a str),
|
||||
|
|
@ -81,6 +86,7 @@ impl WheelData {
|
|||
|
||||
pub struct DeviceState {
|
||||
view: ViewState,
|
||||
device_id: Option<OwnedStr<64>>,
|
||||
question: Option<QuestionData>,
|
||||
wheel: WheelData,
|
||||
last_index: usize,
|
||||
|
|
@ -91,6 +97,7 @@ impl DeviceState {
|
|||
pub const fn new() -> Self {
|
||||
Self {
|
||||
view: ViewState::Loading,
|
||||
device_id: None,
|
||||
question: None,
|
||||
wheel: WheelData::empty(),
|
||||
last_index: 0,
|
||||
|
|
@ -99,12 +106,19 @@ impl DeviceState {
|
|||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.view = ViewState::Loading;
|
||||
self.question = None;
|
||||
self.wheel = WheelData::empty();
|
||||
self.last_index = 0;
|
||||
self.title_offset = 0;
|
||||
}
|
||||
|
||||
pub fn reconnecting(&mut self) {
|
||||
self.question = None;
|
||||
self.wheel = WheelData::empty();
|
||||
self.view = ViewState::Reconnecting;
|
||||
}
|
||||
|
||||
pub fn view_state(&self) -> ViewState {
|
||||
self.view
|
||||
}
|
||||
|
|
@ -119,6 +133,21 @@ impl DeviceState {
|
|||
|
||||
pub fn apply_proxy_output(&mut self, data: ProxyOutput<'_>) {
|
||||
match data {
|
||||
ProxyOutput::ConnectPrompt(device_id) => {
|
||||
let mut owned_device_id = OwnedStr::new();
|
||||
for char in device_id.chars() {
|
||||
if owned_device_id.try_push(char).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.device_id = Some(owned_device_id);
|
||||
self.question = None;
|
||||
self.view = ViewState::ConnectPrompt;
|
||||
}
|
||||
ProxyOutput::WaitingForParty => {
|
||||
self.question = None;
|
||||
self.view = ViewState::WaitingForParty;
|
||||
}
|
||||
ProxyOutput::Question(data) => {
|
||||
let data: QuestionData = data.into();
|
||||
let mut future_wheel = WheelData::empty();
|
||||
|
|
@ -157,6 +186,41 @@ impl DeviceState {
|
|||
}
|
||||
|
||||
pub fn render_lines(&mut self) -> Option<(OwnedStr<16>, OwnedStr<16>)> {
|
||||
if self.view == ViewState::Loading {
|
||||
return Some((
|
||||
OwnedStr::from_str("Connecting").unwrap(),
|
||||
OwnedStr::from_str("Please wait").unwrap(),
|
||||
));
|
||||
}
|
||||
|
||||
if self.view == ViewState::Reconnecting {
|
||||
return Some((
|
||||
OwnedStr::from_str("Reconnecting").unwrap(),
|
||||
OwnedStr::from_str("Please wait").unwrap(),
|
||||
));
|
||||
}
|
||||
|
||||
if self.view == ViewState::ConnectPrompt {
|
||||
let device_id = self.device_id.as_ref()?;
|
||||
let mut display_id: OwnedStr<16> = OwnedStr::new();
|
||||
for char in device_id.as_str().chars() {
|
||||
if display_id.try_push(char).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return Some((
|
||||
OwnedStr::from_str("Connect device").unwrap(),
|
||||
center_str::<16>(display_id.as_str(), 16).unwrap(),
|
||||
));
|
||||
}
|
||||
|
||||
if self.view == ViewState::WaitingForParty {
|
||||
return Some((
|
||||
OwnedStr::from_str("Connected").unwrap(),
|
||||
OwnedStr::from_str("Waiting party").unwrap(),
|
||||
));
|
||||
}
|
||||
|
||||
if self.view != ViewState::Question {
|
||||
return None;
|
||||
}
|
||||
|
|
@ -233,11 +297,7 @@ pub fn wheel_delta(old_angle: i32, current_angle: i32, inverted: bool) -> i32 {
|
|||
};
|
||||
}
|
||||
|
||||
if inverted {
|
||||
-diff
|
||||
} else {
|
||||
diff
|
||||
}
|
||||
if inverted { -diff } else { diff }
|
||||
}
|
||||
|
||||
pub fn apply_wheel_delta(
|
||||
|
|
@ -304,7 +364,10 @@ impl<const CAP: usize> ufmt::uWrite for OwnedStrWriter<CAP> {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn center_str<const CAP: usize>(text: &str, width: usize) -> Result<OwnedStr<CAP>, owned_str::Error> {
|
||||
pub fn center_str<const CAP: usize>(
|
||||
text: &str,
|
||||
width: usize,
|
||||
) -> Result<OwnedStr<CAP>, owned_str::Error> {
|
||||
let mut res = OwnedStr::new();
|
||||
let len = text.len();
|
||||
let padding = (width.saturating_sub(len) + 1) / 2;
|
||||
|
|
@ -317,7 +380,65 @@ pub fn center_str<const CAP: usize>(text: &str, width: usize) -> Result<OwnedStr
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{apply_wheel_delta, wheel_delta};
|
||||
use super::{DeviceState, ViewState, apply_wheel_delta, parse_proxy_output, wheel_delta};
|
||||
|
||||
#[test]
|
||||
fn parses_and_renders_connect_prompt() {
|
||||
let data = parse_proxy_output(r#"{"ConnectPrompt":"esp32-1"}"#).unwrap();
|
||||
let mut state = DeviceState::new();
|
||||
|
||||
state.apply_proxy_output(data);
|
||||
|
||||
assert_eq!(state.view_state(), ViewState::ConnectPrompt);
|
||||
let (line1, line2) = state.render_lines().unwrap();
|
||||
assert_eq!(line1.as_str(), "Connect device");
|
||||
assert_eq!(line2.as_str(), " esp32-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_results_message() {
|
||||
let data = parse_proxy_output(r#""Results""#).unwrap();
|
||||
let mut state = DeviceState::new();
|
||||
|
||||
state.apply_proxy_output(data);
|
||||
|
||||
assert_eq!(state.view_state(), ViewState::Results);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_renders_waiting_for_party() {
|
||||
let data = parse_proxy_output(r#""WaitingForParty""#).unwrap();
|
||||
let mut state = DeviceState::new();
|
||||
|
||||
state.apply_proxy_output(data);
|
||||
|
||||
assert_eq!(state.view_state(), ViewState::WaitingForParty);
|
||||
let (line1, line2) = state.render_lines().unwrap();
|
||||
assert_eq!(line1.as_str(), "Connected");
|
||||
assert_eq!(line2.as_str(), "Waiting party");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_reconnecting_state() {
|
||||
let mut state = DeviceState::new();
|
||||
|
||||
state.reconnecting();
|
||||
|
||||
assert_eq!(state.view_state(), ViewState::Reconnecting);
|
||||
let (line1, line2) = state.render_lines().unwrap();
|
||||
assert_eq!(line1.as_str(), "Reconnecting");
|
||||
assert_eq!(line2.as_str(), "Please wait");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_loading_state() {
|
||||
let mut state = DeviceState::new();
|
||||
|
||||
let (line1, line2) = state.render_lines().unwrap();
|
||||
|
||||
assert_eq!(line1.as_str(), "Connecting");
|
||||
assert_eq!(line2.as_str(), "Please wait");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wraps_forward_across_zero() {
|
||||
|
|
|
|||
|
|
@ -49,6 +49,11 @@ pub async fn reset_state() {
|
|||
state.reset();
|
||||
}
|
||||
|
||||
pub async fn reconnecting_state() {
|
||||
let mut state = STATE.lock().await;
|
||||
state.reconnecting();
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(info: &core::panic::PanicInfo) -> ! {
|
||||
println!("PANIC! {:?}", info);
|
||||
|
|
|
|||
|
|
@ -14,8 +14,9 @@ use esp_radio::wifi::sta::StationConfig;
|
|||
use esp_radio::wifi::{Config, ControllerConfig, scan::ScanConfig};
|
||||
|
||||
use crate::screen::overwrite_lcd;
|
||||
use crate::{buffer::wait_for_config, tcp_read_loop, tcp_write_loop};
|
||||
use crate::{WIFI_NETWORK, WIFI_PASSWORD};
|
||||
use crate::{buffer::wait_for_config, tcp_read_loop, tcp_write_loop};
|
||||
use crate::{reconnecting_state, reset_state};
|
||||
|
||||
pub struct NetworkConfig<'a> {
|
||||
pub wifi: WIFI<'a>,
|
||||
|
|
@ -129,10 +130,12 @@ pub async fn network_setup_task(
|
|||
.await
|
||||
{
|
||||
println!("tcp connect error: {:?}", e);
|
||||
reconnecting_state().await;
|
||||
overwrite_lcd("TCP error", &format!("{}", e)).await;
|
||||
Timer::after_millis(1000).await;
|
||||
continue;
|
||||
}
|
||||
reset_state().await;
|
||||
overwrite_lcd("Connected", "").await;
|
||||
|
||||
let cancel = Signal::<CriticalSectionRawMutex, ()>::new();
|
||||
|
|
@ -149,10 +152,11 @@ pub async fn network_setup_task(
|
|||
|
||||
if !stack.is_config_up() {
|
||||
println!("wifi down, reconnecting wifi");
|
||||
reconnecting_state().await;
|
||||
break;
|
||||
}
|
||||
|
||||
overwrite_lcd("Connection close", "").await;
|
||||
reconnecting_state().await;
|
||||
Timer::after_millis(500).await;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,11 +4,11 @@ use std::sync::{Arc, Mutex};
|
|||
use std::thread;
|
||||
|
||||
use clap::Parser;
|
||||
use crossterm::event::{Event, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
|
||||
use crossterm::cursor::Show;
|
||||
use crossterm::queue;
|
||||
use crossterm::event;
|
||||
use crossterm::event::{Event, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use crossterm::queue;
|
||||
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
|
||||
use device_state::{DeviceState, WriteType, apply_wheel_delta};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
|
|
@ -88,6 +88,7 @@ async fn main() -> io::Result<()> {
|
|||
Ok(stream) => break stream,
|
||||
Err(err) => {
|
||||
log_error(&format!("connect error: {err}"));
|
||||
state.lock().unwrap().reconnecting();
|
||||
tokio::select! {
|
||||
_ = &mut sigint => {
|
||||
log_error("received SIGINT");
|
||||
|
|
@ -107,10 +108,12 @@ async fn main() -> io::Result<()> {
|
|||
}
|
||||
};
|
||||
let (mut read, mut write) = stream.into_split();
|
||||
state.lock().unwrap().reset();
|
||||
|
||||
let device_id = device_state::serialize_write(&WriteType::DeviceId(DEVICE_ID)).unwrap();
|
||||
if write.write_all(device_id.as_bytes()).await.is_err() {
|
||||
log_error("failed to send device id");
|
||||
state.lock().unwrap().reconnecting();
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -184,6 +187,7 @@ async fn main() -> io::Result<()> {
|
|||
}
|
||||
|
||||
log_error("reconnecting in 500ms");
|
||||
state.lock().unwrap().reconnecting();
|
||||
tokio::select! {
|
||||
_ = &mut sigint => {
|
||||
log_error("received SIGINT");
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@ import {
|
|||
|
||||
export function UserInfo() {
|
||||
const { user } = useUser();
|
||||
const { party, members, isConnecting, isReconnecting } = useParty();
|
||||
const { party, members, isConnecting, isReconnecting, resetParty } =
|
||||
useParty();
|
||||
return (
|
||||
<Item>
|
||||
<ItemMedia>
|
||||
|
|
@ -37,8 +38,15 @@ export function UserInfo() {
|
|||
</ItemDescription>
|
||||
</ItemContent>
|
||||
<ItemActions>
|
||||
{party && members.length > 1 && (
|
||||
<Button onClick={() => client.api.party.leave.post()}>Leave</Button>
|
||||
{party && (
|
||||
<Button
|
||||
onClick={async () => {
|
||||
await client.api.party.leave.post();
|
||||
resetParty();
|
||||
}}
|
||||
>
|
||||
Leave
|
||||
</Button>
|
||||
)}
|
||||
</ItemActions>
|
||||
</Item>
|
||||
|
|
|
|||
|
|
@ -1,4 +1,13 @@
|
|||
import { useCallback, useMemo, useState } from "react";
|
||||
import {
|
||||
createContext,
|
||||
createElement,
|
||||
type ReactNode,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import type {
|
||||
PartySocketEvent,
|
||||
PartyState,
|
||||
|
|
@ -6,14 +15,34 @@ import type {
|
|||
import { usePartySocket } from "./use-party-socket";
|
||||
import { useUser } from "./user";
|
||||
|
||||
const emptyPartyState: PartyState = {
|
||||
party: null,
|
||||
members: [],
|
||||
};
|
||||
|
||||
type PartyContextValue = PartyState & {
|
||||
connectionState: "disconnected" | "connecting" | "connected" | "reconnecting";
|
||||
isConnected: boolean;
|
||||
isConnecting: boolean;
|
||||
isReconnecting: boolean;
|
||||
setPartyState: (state: PartyState) => void;
|
||||
resetParty: () => void;
|
||||
};
|
||||
|
||||
const PartyContext = createContext<PartyContextValue | null>(null);
|
||||
|
||||
function reducePartyState(
|
||||
state: PartyState,
|
||||
event: PartySocketEvent,
|
||||
userId: string,
|
||||
): PartyState {
|
||||
switch (event.type) {
|
||||
case "snapshot":
|
||||
case "party_status":
|
||||
case "party_status": {
|
||||
if (!event.party) return emptyPartyState;
|
||||
const isMember = event.members.some((member) => member.userId === userId);
|
||||
if (!isMember) return emptyPartyState;
|
||||
return { party: event.party, members: event.members };
|
||||
}
|
||||
case "member_payload":
|
||||
case "pong":
|
||||
case "error":
|
||||
|
|
@ -28,16 +57,18 @@ function getApiUrl(): string | null {
|
|||
return `${window.location.protocol}//${window.location.host}`;
|
||||
}
|
||||
|
||||
export function useParty() {
|
||||
const { session } = useUser();
|
||||
const [state, setState] = useState<PartyState>({
|
||||
party: null,
|
||||
members: [],
|
||||
});
|
||||
export function PartyProvider({ children }: { children: ReactNode }) {
|
||||
const { user } = useUser();
|
||||
const userId = user?.id ?? null;
|
||||
const [state, setState] = useState<PartyState>(emptyPartyState);
|
||||
|
||||
const handleMessage = useCallback((event: PartySocketEvent) => {
|
||||
setState((prev: PartyState) => reducePartyState(prev, event));
|
||||
}, []);
|
||||
const handleMessage = useCallback(
|
||||
(event: PartySocketEvent) => {
|
||||
if (!userId) return;
|
||||
setState((prev: PartyState) => reducePartyState(prev, event, userId));
|
||||
},
|
||||
[userId],
|
||||
);
|
||||
|
||||
const apiUrl = useMemo(() => {
|
||||
const url = getApiUrl();
|
||||
|
|
@ -45,13 +76,36 @@ export function useParty() {
|
|||
return url;
|
||||
}, []);
|
||||
|
||||
const resetParty = useCallback(() => {
|
||||
setState(emptyPartyState);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!userId) resetParty();
|
||||
}, [resetParty, userId]);
|
||||
|
||||
const wsState = usePartySocket({
|
||||
apiUrl,
|
||||
onMessage: session ? handleMessage : null,
|
||||
apiUrl: userId ? apiUrl : null,
|
||||
onMessage: userId ? handleMessage : null,
|
||||
});
|
||||
|
||||
return {
|
||||
...state,
|
||||
...wsState,
|
||||
};
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
...state,
|
||||
...wsState,
|
||||
setPartyState: setState,
|
||||
resetParty,
|
||||
}),
|
||||
[state, wsState, resetParty],
|
||||
);
|
||||
|
||||
return createElement(PartyContext.Provider, { value }, children);
|
||||
}
|
||||
|
||||
export function useParty() {
|
||||
const context = useContext(PartyContext);
|
||||
if (!context) {
|
||||
throw new Error("useParty must be used within PartyProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import { treaty } from "@elysiajs/eden";
|
||||
import type { App } from "../../../api/src/index";
|
||||
|
||||
export const client = treaty<App>("aura.rpi1.danbulant.cloud", {});
|
||||
// export const client = treaty<App>("aura.rpi1.danbulant.cloud", {});
|
||||
export const client = treaty<App>(
|
||||
process.env.VITE_BETTER_AUTH_URL || "127.0.0.1:3000",
|
||||
{},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools";
|
|||
import type * as React from "react";
|
||||
import { useEffect } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { PartyProvider } from "#/hooks/use-party";
|
||||
import type { AuthSession } from "#/lib/auth.serverfn";
|
||||
import { fetchSession, sessionQueryKey } from "#/lib/auth-client";
|
||||
import { client } from "#/lib/eden";
|
||||
|
|
@ -131,7 +132,7 @@ function RootDocument({ children }: { children: React.ReactNode }) {
|
|||
<HeadContent />
|
||||
</head>
|
||||
<body className="font-sans antialiased wrap-anywhere dark">
|
||||
{children}
|
||||
<PartyProvider>{children}</PartyProvider>
|
||||
<Toaster />
|
||||
<TanStackDevtools
|
||||
config={{
|
||||
|
|
|
|||
Loading…
Reference in a new issue