Skip to content

Commit

Permalink
Update device-live-inspector to use SSE for real-time updates
Browse files Browse the repository at this point in the history
  • Loading branch information
mateuscardosodeveloper committed May 8, 2024
1 parent 5aeb893 commit 5d62548
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions src/commands/devices/device-live-inspector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@ import { pickDeviceIDFromTagoIO } from "../../prompt/pick-device-id-from-tagoio"
* @param profileToken - The user's profile token.
* @returns An EventSource instance connected to the TagoIO Realtime API.
*/
function apiSSE(profileToken: string) {
const sse = new EventSource(`https://realtime.tago.io?token=${profileToken}`);
function apiSSE(profileToken: string, deviceID: string) {
const sse = new EventSource(`https://sse.tago.io/events?channel=device_inspector.${deviceID}&token=${profileToken}`);

return sse;
}

interface ScopeContent {
connection_id: string;
content: string;
device_id: string;
timestamp: string;
title: string;
content: string;
}

/**
Expand All @@ -47,19 +49,20 @@ function displayMessage(scope: ScopeContent) {
*/
function setupSSE(sse: ReturnType<typeof apiSSE>, deviceIdOrToken: string, deviceInfo: DeviceInfo) {
sse.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.resourceName === "device" && data.resourceID === deviceIdOrToken) {
if (Array.isArray(data.scope)) {
for (const item of data.scope) {
displayMessage(item);
}
} else {
displayMessage(data.scope);
const scope = JSON.parse(event.data).payload as ScopeContent;
if (Array.isArray(scope)) {
for (const item of scope) {
displayMessage(item);
}
} else {
displayMessage(scope);
}
};

sse.onerror = (error) => errorHandler(`Connection error: ${JSON.stringify(error)}`);
sse.onerror = (_error) => {
errorHandler("Connection error");
console.error(_error);
};

sse.onopen = () => {
const deviceName = deviceInfo?.name || deviceIdOrToken;
Expand Down Expand Up @@ -107,7 +110,7 @@ async function inspectorConnection(deviceIdOrToken: string, options: IOptions) {
deviceIdOrToken = deviceInfo.id;
}

const sse = apiSSE(config.profileToken);
const sse = apiSSE(config.profileToken, deviceInfo.id);
setupSSE(sse, deviceIdOrToken, deviceInfo);
}

Expand Down

0 comments on commit 5d62548

Please sign in to comment.