Smart Site
Home Docs Smart Data Realtime Communication

Realtime Communication

The Realtime Communication module pushes live data, alarms, and system events from the backend to the browser using Socket.IO. It is the backbone of every live dashboard and monitoring screen in Smart SCADA.

Interface Screenshot

Realtime Communication - WebSocket Monitor (English UI)

Captured from the live Smart Site system with the English UI. See the zh-CN counterpart for the Chinese-UI screenshot.

1. Architecture

  • Backend gateway — WebSocketGateway (NestJS @WebSocketGateway) backed by Socket.IO
  • Transport — WebSocket with HTTP long-polling fallback
  • Default URL — ws://localhost:4000 (same host as the REST API)
  • Authentication — JWT passed as a handshake auth token; verified by JwtAuthGuard

The gateway is part of @ss-node/ss-core and is registered as a global module so every feature module can emit events through it.

2. Message Types

The gateway emits well-defined message types to subscribed clients:

Event Payload Purpose
device.data { deviceId, tagId, value, quality, ts } Live tag value update
device.status { deviceId, status } Online/offline change
alarm.raised Alarm entity New active alarm
alarm.acknowledged { alarmId, user } Alarm acknowledged
alarm.cleared { alarmId, ts } Alarm auto-cleared
system.notification { level, title, message } Generic system notice
config.changed { configType, changes } System config updated

3. Rooms and Subscriptions

To avoid flooding every client with all data, the gateway uses Socket.IO rooms:

  • device:{deviceId} — only clients viewing that device receive its data
  • project:{projectId} — project-scoped broadcasts
  • alarms — any client that has the alarm banner open
  • system — system-wide notifications

Clients join/leave rooms via emitted subscribe / unsubscribe messages. The RoomService tracks membership and enforces authorization (a user cannot join a room for a project they cannot access).

4. Frontend Real-Time Data Push

The frontend opens a single Socket.IO connection on login and shares it via a composable:

const { subscribe, onMessage, offMessage } = useWebSocket()

// Subscribe to a device's live data
subscribe(`device:${deviceId}`)

// Handle incoming values
onMessage('device.data', (payload) => {
  // update reactive store
})

The connection auto-reconnects with exponential backoff. On reconnect, the client re-subscribes to its active rooms.

5. Offline Message Cache

If a client is temporarily disconnected, the OfflineMessageService buffers messages for rooms the client was in. On reconnect, buffered messages are flushed so the UI catches up without gaps.

  • Cache is bounded (configurable max size per room)
  • Oldest messages are discarded when the bound is hit (see discard.strategy.ts)
  • Frequency reduction can be applied to compress high-rate streams (see frequency-reduction.strategy.ts)

6. Monitoring

The System → WebSocket Monitor page (route /system/ws-monitor) shows:

  • Connected client count and list
  • Messages per second (in/out)
  • Per-event-type counters
  • Room membership counts
  • Latency histogram (round-trip ping)

The WebsocketMetricsService and metrics-collector.service.ts feed this page. Use it to detect overloaded clients or a stuck gateway.

7. Operational Guidance

7.1 Diagnosing "no live data"

  1. Open the WebSocket Monitor page — is the client connected?
  2. Check the browser console for Socket.IO errors
  3. Verify the JWT is still valid (a 401 on handshake causes silent reconnect loops)
  4. Confirm the client subscribed to the right room (device:{id})
  5. Check the backend log for device.data emissions from the pipeline

7.2 Scaling Considerations

  • Each connected client holds a socket open; typical servers handle a few thousand concurrent clients
  • For large deployments, run multiple backend instances behind a sticky-session load balancer and configure the Socket.IO Redis adapter (not bundled by default)
  • Reduce message volume by enabling deadband and frequency reduction at the source

8. FAQ

Q: The browser shows "polling" instead of "websocket" transport. A: A proxy or firewall is blocking WebSocket upgrades. Ensure the reverse proxy (e.g. nginx) forwards the Upgrade header. The bundled nginx config under ss-run/ss/web/nginx/conf/ already supports this.

Q: Live data stops after a few minutes. A: The JWT may have expired. The frontend should refresh the token before it expires; verify the refresh-token flow is working. Also check the WebSocket Monitor for disconnect events.

Q: Can I push custom events from a script? A: Yes. The Script API exposes a SocketAPI that lets scripts emit custom events to subscribed clients. See the Script Engine article.

Q: How are messages ordered? A: Within a single tag, messages are delivered in timestamp order. Across tags, ordering is not guaranteed — design the UI to handle independent updates.

  • ../../03-device/device-detail.md
  • ../../06-alarm/README.md
  • ../../10-script/README.md
  • ../../../../../../../ss-services/ss-node/packages/ss-core/src/core/pipeline/offline-cache.service.ts