「スパイ体験型アトラクション」の運営スタッフが使う、カメラ映像・センサー状態・イベントログを 1画面で確認する管理コンソールです。このページでは、プログラミング初学者ではないけれど Web技術にはまだ詳しくない方向けに、技術的な仕組みとコードの構成をやさしく解説します。
このアプリは大きく3つの部分に分かれています。それぞれ別の役割を持ち、別の場所で動いています。
ブラウザで見ている画面そのもの。ダッシュボード、カメラ一覧、センサー一覧などの画面を描画します。 Cloudflare Pagesという「静的サイトを世界中に配信してくれるサービス」に置かれていて、 誰がどこからアクセスしても同じページが届きます。
「カメラが今オンラインかどうか」「センサーが反応したか」「イベントログに何が記録されたか」といった “みんなで共有すべきデータ”を1か所で管理するサーバーです。複数の端末(PC・スマホなど)で同時に開いても、 同じ状態が全員に届くようにする役目を持ちます。
実機カメラ(Tapo C100など)の映像は、カメラが話す「RTSP」という古い方式のままではブラウザで再生できません。 go2rtcというソフトが、運営スタッフのPC上でRTSP映像をブラウザが再生できる形式に変換してくれます。 これは各拠点ごとに個別に用意する想定の、ローカルな仕組みです。
コード解説の前に、このプロジェクトで頻出する言葉をざっと説明します。
「画面の見た目と動き」を作るためのWebフレームワーク。Reactなどの仲間です。
画面の部品(ボタン、カード、一覧表など)を.svelteファイルという単位で
組み立てていきます。
JavaScriptに「このデータはどんな形をしているべきか」という型の情報を追加した言語。 「カメラの状態は ONLINE/OFFLINE/CONNECTING/ERROR の4種類のどれかしかありえない」といった 決まりをコードに書けるので、typoやうっかりミスに気づきやすくなります。
ブラウザとサーバーの間を「ずっとつないだまま」お互いにメッセージを送り合える通信方式。 通常のWebページの読み込み(1回だけ送って1回だけ返事をもらう)と違い、 サーバー側から「センサーが反応しました」とリアルタイムに知らせることができます。
Workersは「サーバーのプログラムを世界中の拠点で動かしてくれるサービス」。 Durable Objectsはその上で、「1つの状態(今回はカメラやセンサーの状態)を、 常に1か所で一貫して保持してくれる」仕組みです。複数人が同時にアクセスしても データが競合しないようにしてくれます。
監視カメラなどの映像機器が昔からよく使う映像配信の規格。 ブラウザは直接これを再生できないため、別の形式に変換するサーバー(go2rtc)が必要になります。
ブラウザがページごとに持っている「小さな保存領域」。サーバーを介さずに、 端末の設定(アプリ名、通知のON/OFFなど)をブラウザの中だけに保存しておく時に使います。
例として「あるスタッフがセンサーの『反応させる』ボタンを押した」場合に、 裏側で何が起きて、他の端末の画面にも反映されるのかを順番に見てみます。
画面のボタンが systemState.triggerSensor(id) を呼び出します。これはアプリ内の「状態管理」役のオブジェクトです。
自分の端末ではデータを直接書き換えず、「センサーを反応させて」というメッセージをWebSocket経由で状態共有サーバー(Durable Object)に送ります。
サーバーがそのセンサーの状態を書き換え、イベントログに1件追加し、保存します(tools/realtime-worker/src/room.ts)。
更新後の状態全体を、今つながっている全ての端末にWebSocketで一斉に送り返します(ブロードキャスト)。
受け取った端末側では、受信した状態をそのまま画面の表示用データに反映するので、ボタンを押した人以外の画面も自動的に切り替わります。
💡 ポイント: このアプリは「自分の画面だけ書き換えて、あとでサーバーと合わせる」方式ではなく、 「必ずサーバー経由で書き換えて、サーバーからの返事を信じる」方式を採っています。 これにより複数端末間でデータがズレる心配がありません。
プロジェクトの主なフォルダ・ファイルを、役割別にまとめました。カードをクリックすると詳しい解説が開きます。
# フォルダ構成(抜粋) src/ ├── routes/ # 画面(URLのパスに対応) │ ├── +page.svelte # "/" ダッシュボード │ ├── cameras/+page.svelte │ ├── camera-rotation/+page.svelte │ ├── sensors/+page.svelte │ ├── events/+page.svelte │ └── settings/+page.svelte │ └── lib/ ├── components/ # 画面を組み立てるパーツ │ ├── cameras/, sensors/, events/, dashboard/, layout/ ├── stores/ # 状態管理(データの一元管理) │ ├── system-state.svelte.ts │ └── simulation.svelte.ts ├── utils/ # 通信や細かい処理 │ ├── realtime-client.ts │ ├── qr-scanner.ts │ ├── storage.ts │ └── csv-export.ts ├── types/index.ts # 型定義(データの"形"のルール) └── data/mock-data.ts # 初期データ(モック) tools/realtime-worker/ # ② 状態共有サーバー(別デプロイ単位) ├── src/index.ts, room.ts, types.ts, initial-data.ts tools/go2rtc/ # ③ カメラ映像サーバーの設定・起動スクリプト
アプリ全体で使う「データの形」を定義するファイルです。たとえばカメラのデータは必ず次の形を持つ、と決めています。
interface Camera {
id: string;
name: string;
status: 'ONLINE' | 'OFFLINE' | 'CONNECTING' | 'ERROR';
connectionType: 'RTSP_MOCK' | 'RTSP_LIVE';
// ...
}
このように型を決めておくことで、「statusに存在しない文字列を入れてしまう」ような
ミスをコードを書いている最中に検出できます。また、サーバーとブラウザの間でやり取りするメッセージの種類
(ClientMessage / ServerMessage) もここで定義されており、
「ありうる通信の種類」が一覧になっています。
// Camera
export type CameraStatus = 'ONLINE' | 'OFFLINE' | 'CONNECTING' | 'ERROR';
export type CameraConnectionType = 'RTSP_MOCK' | 'RTSP_LIVE';
export interface Camera {
id: string;
name: string;
location: string;
ipAddress: string;
connectionType: CameraConnectionType;
status: CameraStatus;
lastSeenAt: string | null;
videoEnabled: boolean;
mockImage: string;
/**
* go2rtc stream name (the `src` query param in go2rtc's WebSocket API,
* e.g. "cam-01"). Combined with AppSettings.go2rtcBaseUrl to build the
* actual connection URL. Only set when connectionType is RTSP_LIVE.
*/
streamUrl?: string;
/** Accent color (CSS color value) used for this camera's card border/header. Optional. */
themeColor?: string;
}
// Sensor
export type SensorStatus = 'NORMAL' | 'TRIGGERED' | 'OFFLINE' | 'ERROR';
export type SensorType = 'IR_BEAM' | 'PRESSURE_MAT';
export interface Sensor {
id: string;
name: string;
type: SensorType;
location: string;
status: SensorStatus;
lastTriggeredAt: string | null;
lastEventMessage: string | null;
}
// Event
export type EventType =
| 'SENSOR_TRIGGERED'
| 'SENSOR_RESET'
| 'CAMERA_ONLINE'
| 'CAMERA_OFFLINE'
| 'CAMERA_ERROR'
| 'QR_DETECTED'
| 'SYSTEM_WARNING'
| 'SYSTEM_INFO';
export interface SystemEvent {
id: string;
type: EventType;
targetId: string;
targetName: string;
message: string;
timestamp: string;
}
// Settings
/**
* Per-device display/viewing preferences. Kept in localStorage only — NOT
* shared across devices, unlike cameras/sensors/events/dashboardCameraCount
* (see SharedState), which live on the realtime server so every device
* sees the same dashboard.
*/
export interface AppSettings {
appName: string;
showMockModeBadge: boolean;
autoRefreshEnabled: boolean;
notificationsEnabled: boolean;
autoSimulationEnabled: boolean;
/**
* Base URL of the go2rtc instance to connect to for RTSP_LIVE cameras
* (e.g. "ws://localhost:1984" or "ws://192.168.1.50:1984"). go2rtc runs
* on the viewer's own machine/LAN — this setting lets each viewer point
* at wherever their go2rtc happens to be running, independent of where
* this app itself is hosted.
*/
go2rtcBaseUrl: string;
}
/**
* The subset of app state shared across all connected devices, held by the
* realtime Worker (tools/realtime-worker) and synced over WebSocket. Mirrors
* tools/realtime-worker/src/types.ts's SharedState — kept in sync by hand
* since that Worker is a standalone deployable.
*/
export interface SharedState {
cameras: Camera[];
sensors: Sensor[];
events: SystemEvent[];
dashboardCameraCount: number;
}
/** Messages this app sends to the realtime Worker. */
export type ClientMessage =
| { type: 'addCamera'; camera: Camera }
| { type: 'updateCamera'; id: string; patch: Partial<Camera> }
| { type: 'removeCamera'; id: string }
| { type: 'setCameraStatus'; id: string; status: CameraStatus }
| { type: 'toggleCameraVideo'; id: string }
| { type: 'triggerSensor'; id: string }
| { type: 'resetSensor'; id: string }
| { type: 'setSensorStatus'; id: string; status: SensorStatus }
| { type: 'reportQrDetection'; cameraId: string; qrText: string }
| { type: 'addEvent'; event: Omit<SystemEvent, 'id' | 'timestamp'> }
| { type: 'clearEvents' }
| { type: 'setDashboardCameraCount'; count: number }
| { type: 'resetAllCameras' }
| { type: 'resetAllSensors' }
| { type: 'restoreInitialData' };
/** Messages the realtime Worker sends to this app. */
export type ServerMessage =
| { type: 'state'; state: SharedState }
| { type: 'alertQrSeen'; cameraId: string; at: number };
アプリの「今の状態」をまとめて持っているファイルです。カメラ一覧・センサー一覧・イベントログなどを
SystemStateというクラスのプロパティとして保持し、画面側はここから値を読んで表示します。
$state(...) はSvelte 5の書き方で、「このデータが変わったら、使っている画面を自動的に再描画して」という目印です。triggerSensorなど)は、データを直接書き換えず、状態共有サーバーへメッセージを送るだけになっています。実際の書き換えはサーバーからの返事を受け取ったときに行われます。localStorageにだけ保存します(他の端末の表示設定に影響を与えないようにするため)。import { DEFAULT_DASHBOARD_CAMERA_COUNT, DEFAULT_SETTINGS, INITIAL_CAMERAS, INITIAL_EVENTS, INITIAL_SENSORS } from '#lib/data/mock-data';
import type { AppSettings, Camera, CameraStatus, Sensor, SensorStatus, ServerMessage, SystemEvent } from '#lib/types';
import { connectRealtime, type ConnectionStatus, type RealtimeClient } from '#lib/utils/realtime-client';
import { loadFromStorage, saveToStorage } from '#lib/utils/storage';
const STORAGE_KEYS = {
settings: 'spy-cc:settings'
} as const;
export interface Notification {
id: string;
message: string;
level: 'info' | 'warning' | 'critical';
}
/**
* Cameras, sensors, events, and dashboardCameraCount are shared across every
* device via the realtime Worker (tools/realtime-worker) — this class holds
* the latest snapshot broadcast from there and forwards user actions to it
* as commands, rather than mutating local state directly. Everything else
* here (settings, notifications) is per-device only.
*/
class SystemState {
cameras = $state<Camera[]>(INITIAL_CAMERAS.map((c) => ({ ...c })));
sensors = $state<Sensor[]>(INITIAL_SENSORS.map((s) => ({ ...s })));
events = $state<SystemEvent[]>(INITIAL_EVENTS.map((e) => ({ ...e })));
dashboardCameraCount = $state<number>(DEFAULT_DASHBOARD_CAMERA_COUNT);
/** Connection status to the realtime Worker, for a "reconnecting..." indicator. */
connectionStatus = $state<ConnectionStatus>('connecting');
// Per-device settings — not shared, persisted to localStorage.
settings = $state<AppSettings>({
...DEFAULT_SETTINGS,
...loadFromStorage(STORAGE_KEYS.settings, DEFAULT_SETTINGS)
});
notifications = $state<Notification[]>([]);
/**
* Timestamp (ms) of the most recent sighting of the alert-trigger QR code,
* across any camera on any device. `null` when it isn't currently in
* view. Not persisted — purely a live signal for the Camera Rotation
* view's warning badge, which clears it ~1s after sightings stop.
*/
lastAlertQrSeenAt = $state<number | null>(null);
#realtime: RealtimeClient;
/** targetId of the last event this device has already shown a notification for, to avoid re-notifying on every full-state broadcast. */
#lastNotifiedEventId: string | null = null;
onlineCameraCount = $derived(this.cameras.filter((c) => c.status === 'ONLINE').length);
activeSensorCount = $derived(this.sensors.filter((s) => s.status !== 'OFFLINE').length);
triggeredSensorCount = $derived(this.sensors.filter((s) => s.status === 'TRIGGERED').length);
unresolvedWarningCount = $derived(
this.sensors.filter((s) => s.status === 'ERROR').length +
this.cameras.filter((c) => c.status === 'ERROR' || c.status === 'OFFLINE').length
);
todayEventCount = $derived(
this.events.filter((e) => {
const d = new Date(e.timestamp);
const now = new Date();
return (
d.getFullYear() === now.getFullYear() &&
d.getMonth() === now.getMonth() &&
d.getDate() === now.getDate()
);
}).length
);
constructor() {
this.#realtime = connectRealtime(
(message) => this.#handleServerMessage(message),
(status) => (this.connectionStatus = status)
);
}
#handleServerMessage(message: ServerMessage) {
if (message.type === 'state') {
const incomingNewestId = message.state.events[0]?.id ?? null;
const isFirstSync = this.#lastNotifiedEventId === null;
this.cameras = message.state.cameras;
this.sensors = message.state.sensors;
this.events = message.state.events;
this.dashboardCameraCount = message.state.dashboardCameraCount;
if (!isFirstSync && incomingNewestId && incomingNewestId !== this.#lastNotifiedEventId) {
const newEvent = message.state.events[0];
if (this.settings.notificationsEnabled) {
const level: Notification['level'] =
newEvent.type === 'SYSTEM_WARNING' || newEvent.type === 'CAMERA_ERROR'
? 'critical'
: newEvent.type === 'CAMERA_OFFLINE' || newEvent.type === 'SENSOR_TRIGGERED'
? 'warning'
: 'info';
this.pushNotification(newEvent.message, level);
}
}
this.#lastNotifiedEventId = incomingNewestId;
} else if (message.type === 'alertQrSeen') {
this.lastAlertQrSeenAt = message.at;
}
}
persistSettings() {
saveToStorage(STORAGE_KEYS.settings, this.settings);
}
pushNotification(message: string, level: Notification['level'] = 'info') {
const id = `NOTIF-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
this.notifications = [...this.notifications, { id, message, level }];
const duration = level === 'critical' ? 8000 : 5000;
setTimeout(() => this.dismissNotification(id), duration);
}
dismissNotification(id: string) {
this.notifications = this.notifications.filter((n) => n.id !== id);
}
/** Adds a generic event to the shared event log (e.g. the mock simulation's SYSTEM_INFO ticks). */
addEvent(event: Omit<SystemEvent, 'id' | 'timestamp'>) {
this.#realtime.send({ type: 'addEvent', event });
}
// Cameras — all forwarded to the realtime Worker; UI updates once the
// resulting state broadcast comes back (see #handleServerMessage).
addCamera(camera: Camera) {
this.#realtime.send({ type: 'addCamera', camera });
}
updateCamera(id: string, patch: Partial<Camera>) {
this.#realtime.send({ type: 'updateCamera', id, patch });
}
removeCamera(id: string) {
this.#realtime.send({ type: 'removeCamera', id });
}
setCameraStatus(id: string, status: CameraStatus) {
this.#realtime.send({ type: 'setCameraStatus', id, status });
}
toggleCameraVideo(id: string) {
this.#realtime.send({ type: 'toggleCameraVideo', id });
}
reportQrDetection(cameraId: string, qrText: string) {
this.#realtime.send({ type: 'reportQrDetection', cameraId, qrText });
}
// Sensors
triggerSensor(id: string) {
this.#realtime.send({ type: 'triggerSensor', id });
}
resetSensor(id: string) {
this.#realtime.send({ type: 'resetSensor', id });
}
setSensorStatus(id: string, status: SensorStatus) {
this.#realtime.send({ type: 'setSensorStatus', id, status });
}
// Events
clearEvents() {
this.#realtime.send({ type: 'clearEvents' });
}
// Settings (per-device) / shared resets
updateSettings(patch: Partial<AppSettings>) {
this.settings = { ...this.settings, ...patch };
this.persistSettings();
}
setDashboardCameraCount(count: number) {
this.#realtime.send({ type: 'setDashboardCameraCount', count });
}
resetAllCameras() {
this.#realtime.send({ type: 'resetAllCameras' });
}
resetAllSensors() {
this.#realtime.send({ type: 'resetAllSensors' });
}
restoreInitialData() {
this.#realtime.send({ type: 'restoreInitialData' });
}
}
export const systemState = new SystemState();
ブラウザ側で、状態共有サーバー(Cloudflare Workers上のDurable Object)とのWebSocket通信を担当するファイルです。
import type { ClientMessage, ServerMessage } from '#lib/types';
/**
* URL of the deployed realtime Worker (tools/realtime-worker). Fixed at
* build time per project decision — unlike go2rtc, this server is shared
* infrastructure for every device, not something each viewer points at
* their own machine for.
*/
const REALTIME_WORKER_URL = 'wss://spy-control-center-realtime.hokuyoyuki.workers.dev/room';
const RECONNECT_DELAY_MS = 2000;
export type ConnectionStatus = 'connecting' | 'open' | 'closed';
export interface RealtimeClient {
send(message: ClientMessage): void;
disconnect(): void;
}
/**
* Opens a WebSocket to the realtime Worker and keeps it alive, reconnecting
* automatically on drop. `onMessage` is called for every message from the
* server; `onStatusChange` reports connection status for UI (e.g. an
* "offline/reconnecting" indicator).
*/
export function connectRealtime(
onMessage: (message: ServerMessage) => void,
onStatusChange: (status: ConnectionStatus) => void
): RealtimeClient {
let ws: WebSocket | null = null;
let reconnectTimeout: ReturnType<typeof setTimeout> | undefined;
let disconnected = false;
function connect() {
if (disconnected) return;
onStatusChange('connecting');
ws = new WebSocket(REALTIME_WORKER_URL);
ws.addEventListener('open', () => {
onStatusChange('open');
});
ws.addEventListener('message', (event) => {
if (typeof event.data !== 'string') return;
try {
const message = JSON.parse(event.data) as ServerMessage;
onMessage(message);
} catch {
// ignore malformed frames
}
});
ws.addEventListener('close', () => {
onStatusChange('closed');
if (!disconnected) {
reconnectTimeout = setTimeout(connect, RECONNECT_DELAY_MS);
}
});
ws.addEventListener('error', () => {
// 'close' always follows 'error' for WebSocket, so reconnection is
// scheduled there; nothing extra to do here.
});
}
connect();
return {
send(message: ClientMessage) {
if (ws?.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(message));
}
// If not connected, the command is simply dropped — the next full
// state sync after reconnecting will reflect whatever the rest of
// the room agreed on. Queuing and replaying stale commands after a
// reconnect risks applying them out of order against a state
// that's since moved on.
},
disconnect() {
disconnected = true;
if (reconnectTimeout) clearTimeout(reconnectTimeout);
ws?.close();
}
};
}
実機カメラの映像から、QRコードをブラウザの中だけで検出する機能です(jsQRという
ライブラリを利用)。映像フレームをキャンバス(見えない描画領域)に一度描いて、その画像データを解析します。
ALERT-001)を検出すると、「警告QRを検知した」という特別な通知がサーバー経由で全端末に配信されます。import jsQR from 'jsqr';
const SCAN_INTERVAL_MS = 400;
const MAX_SCAN_DIMENSION = 900;
/** QR code content that triggers the full-screen alert on the Camera Rotation view. */
export const ALERT_QR_CONTENT = 'ALERT-001';
export type QrDetectedHandler = (text: string) => void;
export function startQrScanning(video: HTMLVideoElement, onDetected: QrDetectedHandler): () => void {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
let stopped = false;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
function scheduleNext() {
if (stopped) return;
timeoutId = setTimeout(scan, SCAN_INTERVAL_MS);
}
function scan() {
if (stopped || !ctx) {
scheduleNext();
return;
}
const { videoWidth, videoHeight } = video;
if (video.readyState < video.HAVE_CURRENT_DATA || videoWidth === 0 || videoHeight === 0) {
scheduleNext();
return;
}
const scale = Math.min(1, MAX_SCAN_DIMENSION / Math.max(videoWidth, videoHeight));
const width = Math.max(1, Math.round(videoWidth * scale));
const height = Math.max(1, Math.round(videoHeight * scale));
canvas.width = width;
canvas.height = height;
try {
ctx.drawImage(video, 0, 0, width, height);
const imageData = ctx.getImageData(0, 0, width, height);
const result = jsQR(imageData.data, width, height, { inversionAttempts: 'attemptBoth' });
if (result && result.data) {
onDetected(result.data);
}
} catch {
// Drawing can throw if the video frame isn't ready yet (e.g. CORS/tainted
// canvas edge cases); skip this tick and try again on the next interval.
}
scheduleNext();
}
scheduleNext();
return () => {
stopped = true;
if (timeoutId) clearTimeout(timeoutId);
};
}
実機カメラ映像(connectionType: 'RTSP_LIVE')を表示するための動画プレイヤー部品です。
go2rtcサーバーとWebSocketで接続し、映像データ(WebRTC/MSE形式)を受け取って<video>要素に流し込みます。
go2rtcに接続できない場合は、自動的に「NO SIGNAL」表示に切り替わるようになっています。
<script lang="ts">
import { onMount } from 'svelte';
import { startQrScanning } from '#lib/utils/qr-scanner';
import { systemState } from '#lib/stores/system-state.svelte';
let { streamUrl, cameraId }: { streamUrl: string; cameraId: string } = $props();
let container: HTMLDivElement;
let failed = $state(false);
onMount(() => {
let el: HTMLElement | undefined;
let stopQrScanning: (() => void) | undefined;
// Built from two string parts so bundlers treat this as a fully dynamic
// specifier and skip static resolution: /vendor/video-rtc.js is served
// from `static/` at runtime, not a module this app's build graph owns.
const videoRtcUrl = ['/vendor/video-rtc', '.js'].join('');
import(/* @vite-ignore */ videoRtcUrl)
.then(({ VideoRTC }: { VideoRTC: CustomElementConstructor }) => {
if (!customElements.get('video-rtc')) {
customElements.define('video-rtc', VideoRTC);
}
el = document.createElement('video-rtc');
el.style.width = '100%';
el.style.height = '100%';
el.style.display = 'block';
container.appendChild(el);
// `src` is a property setter (not an observed attribute) on VideoRTC,
// and it must be assigned after the element is connected to the DOM
// so connectedCallback's onconnect() sees a populated wsURL.
(el as HTMLElement & { src: string }).src = streamUrl;
const video = el.querySelector('video');
if (video) {
// Camera audio isn't needed for this app; muting avoids pulling
// an audio track over the WebRTC/MSE connection for no reason
// and sidesteps browser autoplay-with-sound restrictions.
video.muted = true;
stopQrScanning = startQrScanning(video, (text) => {
systemState.reportQrDetection(cameraId, text);
});
}
})
.catch(() => {
failed = true;
});
return () => {
stopQrScanning?.();
el?.remove();
};
});
</script>
<div bind:this={container} class="live-video">
{#if failed}
<div class="load-error">LIVE PLAYER LOAD ERROR</div>
{/if}
</div>
<style>
.live-video {
width: 100%;
height: 100%;
}
.load-error {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
color: var(--color-danger);
font-family: var(--font-mono);
font-size: 12px;
}
</style>
アプリを初めて開いたときに表示される「サンプルデータ」をまとめたファイルです。 カメラ3台(Entrance / Corridor / Laser Room)、センサー数台、初期イベントログなどが あらかじめ定義されています。実機のカメラやセンサーが未接続の状態でも、 画面の見た目や操作感を確認できるようにするためのものです。
import type { AppSettings, Camera, Sensor, SystemEvent } from '#lib/types';
// `connectionType: 'RTSP_MOCK'` by default so the app works fully offline
// without go2rtc running. `streamUrl` stays populated for each camera so
// switching a camera back to `connectionType: 'RTSP_LIVE'` (e.g. when a
// real Tapo C100 + go2rtc are available again) only needs that one field
// changed, either here or via the camera edit form.
export const INITIAL_CAMERAS: Camera[] = [
{
id: 'CAM-01',
name: 'Entrance Camera',
location: '入口',
ipAddress: '192.168.11.32',
connectionType: 'RTSP_MOCK',
status: 'ONLINE',
lastSeenAt: new Date().toISOString(),
videoEnabled: true,
mockImage: '/mock-cameras/entrance.svg',
streamUrl: 'cam-01',
themeColor: '#f87171'
},
{
id: 'CAM-02',
name: 'Corridor Camera',
location: '通路',
ipAddress: '192.168.11.36',
connectionType: 'RTSP_MOCK',
status: 'ONLINE',
lastSeenAt: new Date().toISOString(),
videoEnabled: true,
mockImage: '/mock-cameras/corridor.svg',
streamUrl: 'cam-02',
themeColor: '#60a5fa'
},
{
id: 'CAM-03',
name: 'Laser Room Camera',
location: 'レーザーエリア',
ipAddress: '192.168.11.38',
connectionType: 'RTSP_MOCK',
status: 'ONLINE',
lastSeenAt: new Date().toISOString(),
videoEnabled: true,
mockImage: '/mock-cameras/laser-room.svg',
streamUrl: 'cam-03',
themeColor: '#facc15'
}
];
export const INITIAL_SENSORS: Sensor[] = [
{
id: 'SEN-01',
name: 'Entrance Beam',
type: 'IR_BEAM',
location: '入口',
status: 'NORMAL',
lastTriggeredAt: new Date(Date.now() - 1000 * 60 * 4).toISOString(),
lastEventMessage: '入口センサーが反応しました'
},
{
id: 'SEN-02',
name: 'Corridor Beam',
type: 'IR_BEAM',
location: '通路',
status: 'NORMAL',
lastTriggeredAt: null,
lastEventMessage: null
},
{
id: 'SEN-03',
name: 'Laser Beam A',
type: 'IR_BEAM',
location: 'レーザーエリア',
status: 'NORMAL',
lastTriggeredAt: new Date(Date.now() - 1000 * 60 * 2).toISOString(),
lastEventMessage: 'レーザーエリアAのビームが遮断されました'
},
{
id: 'SEN-04',
name: 'Laser Beam B',
type: 'IR_BEAM',
location: 'レーザーエリア',
status: 'NORMAL',
lastTriggeredAt: null,
lastEventMessage: null
},
{
id: 'SEN-05',
name: 'Goal Pressure Mat',
type: 'PRESSURE_MAT',
location: 'ゴール地点',
status: 'NORMAL',
lastTriggeredAt: new Date(Date.now() - 1000 * 60 * 1).toISOString(),
lastEventMessage: 'ゴール地点の圧力センサーが解除されました'
}
];
export const INITIAL_EVENTS: SystemEvent[] = [
{
id: 'EVT-0001',
type: 'SENSOR_TRIGGERED',
targetId: 'SEN-03',
targetName: 'Laser Beam A',
message: 'レーザーエリアAのビームが遮断されました',
timestamp: new Date(Date.now() - 1000 * 60 * 2).toISOString()
},
{
id: 'EVT-0002',
type: 'SENSOR_RESET',
targetId: 'SEN-05',
targetName: 'Goal Pressure Mat',
message: 'ゴール地点の圧力センサーが解除されました',
timestamp: new Date(Date.now() - 1000 * 60 * 1).toISOString()
},
{
id: 'EVT-0003',
type: 'SENSOR_TRIGGERED',
targetId: 'SEN-01',
targetName: 'Entrance Beam',
message: '入口センサーが反応しました',
timestamp: new Date(Date.now() - 1000 * 60 * 4).toISOString()
}
];
export const DEFAULT_SETTINGS: AppSettings = {
appName: 'Spy Control Center',
showMockModeBadge: true,
autoRefreshEnabled: true,
notificationsEnabled: true,
autoSimulationEnabled: false,
go2rtcBaseUrl: 'ws://localhost:1984'
};
/** Fallback shown before the realtime connection delivers the server's shared value. */
export const DEFAULT_DASHBOARD_CAMERA_COUNT = 3;
②の「状態共有サーバー」の本体です。CloudflareのDurable Objectという仕組みを使って、 カメラ・センサー・イベントログの「正しい最新状態」を1か所で管理します。
import { DurableObject } from 'cloudflare:workers';
import { createInitialState } from './initial-data';
import type {
Camera,
CameraStatus,
ClientMessage,
SensorStatus,
ServerMessage,
SharedState,
SystemEvent
} from './types';
const QR_DETECTION_COOLDOWN_MS = 10_000;
const ALERT_QR_CONTENT = 'ALERT-001';
const STATE_STORAGE_KEY = 'shared-state';
const CAMERA_STATUS_LABEL_JA: Record<CameraStatus, string> = {
ONLINE: 'オンライン',
OFFLINE: 'オフライン',
ERROR: 'エラー状態',
CONNECTING: '接続中'
};
let eventCounter = 0;
function nextEventId(): string {
eventCounter += 1;
return `EVT-${String(Date.now()).slice(-8)}-${eventCounter}`;
}
/**
* One Durable Object instance = one shared "room". All connected clients
* (across every device) see the same cameras/sensors/events and have their
* commands applied to the same server-held state, broadcast back out to
* everyone immediately. Uses the WebSocket Hibernation API so idle rooms
* don't keep the Durable Object billed as "active".
*/
export class Room extends DurableObject {
#state: SharedState | undefined;
/** cameraId + "\u0000" + qrText -> last-reported timestamp (ms). In-memory only; resets on hibernation wake, which only affects log-spam debouncing, not correctness. */
#lastQrDetectionAt = new Map<string, number>();
async #loadState(): Promise<SharedState> {
if (this.#state) return this.#state;
const stored = await this.ctx.storage.get<SharedState>(STATE_STORAGE_KEY);
this.#state = stored ?? createInitialState();
return this.#state;
}
async #saveState(): Promise<void> {
if (!this.#state) return;
await this.ctx.storage.put(STATE_STORAGE_KEY, this.#state);
}
async fetch(request: Request): Promise<Response> {
if (request.headers.get('Upgrade') !== 'websocket') {
return new Response('Expected WebSocket upgrade', { status: 426 });
}
const pair = new WebSocketPair();
const [client, server] = Object.values(pair);
// Hibernation API: the runtime can evict this DO from memory between
// messages and wake it back up on the next one, without dropping the
// client's WebSocket connection.
this.ctx.acceptWebSocket(server);
const state = await this.#loadState();
this.#send(server, { type: 'state', state });
return new Response(null, { status: 101, webSocket: client });
}
async webSocketMessage(ws: WebSocket, raw: string | ArrayBuffer): Promise<void> {
if (typeof raw !== 'string') return;
let message: ClientMessage;
try {
message = JSON.parse(raw);
} catch {
return;
}
const state = await this.#loadState();
this.#applyMessage(state, message);
await this.#saveState();
this.#broadcast({ type: 'state', state });
}
async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void> {
try {
ws.close(code, reason);
} catch {
// already closed
}
}
#send(ws: WebSocket, message: ServerMessage): void {
try {
ws.send(JSON.stringify(message));
} catch {
// socket may have just closed; nothing to do
}
}
#broadcast(message: ServerMessage): void {
const payload = JSON.stringify(message);
for (const ws of this.ctx.getWebSockets()) {
try {
ws.send(payload);
} catch {
// a dead socket will be cleaned up by webSocketClose; skip it here
}
}
}
#addEvent(state: SharedState, event: Omit<SystemEvent, 'id' | 'timestamp'>): void {
state.events = [
{ ...event, id: nextEventId(), timestamp: new Date().toISOString() },
...state.events
];
}
#applyMessage(state: SharedState, message: ClientMessage): void {
switch (message.type) {
case 'addCamera': {
state.cameras = [...state.cameras, message.camera];
return;
}
case 'updateCamera': {
state.cameras = state.cameras.map((c) => (c.id === message.id ? { ...c, ...message.patch } : c));
return;
}
case 'removeCamera': {
state.cameras = state.cameras.filter((c) => c.id !== message.id);
return;
}
case 'setCameraStatus': {
this.#setCameraStatus(state, message.id, message.status);
return;
}
case 'toggleCameraVideo': {
const camera = state.cameras.find((c) => c.id === message.id);
if (!camera) return;
state.cameras = state.cameras.map((c) =>
c.id === message.id ? { ...c, videoEnabled: !c.videoEnabled } : c
);
return;
}
case 'triggerSensor': {
this.#triggerSensor(state, message.id);
return;
}
case 'resetSensor': {
this.#resetSensor(state, message.id);
return;
}
case 'setSensorStatus': {
state.sensors = state.sensors.map((s) => (s.id === message.id ? { ...s, status: message.status } : s));
return;
}
case 'reportQrDetection': {
this.#reportQrDetection(state, message.cameraId, message.qrText);
return;
}
case 'addEvent': {
this.#addEvent(state, message.event);
return;
}
case 'clearEvents': {
state.events = [];
return;
}
case 'setDashboardCameraCount': {
state.dashboardCameraCount = message.count;
return;
}
case 'resetAllCameras': {
state.cameras = createInitialState().cameras;
return;
}
case 'resetAllSensors': {
state.sensors = createInitialState().sensors;
return;
}
case 'restoreInitialData': {
const fresh = createInitialState();
state.cameras = fresh.cameras;
state.sensors = fresh.sensors;
state.events = fresh.events;
return;
}
}
}
#setCameraStatus(state: SharedState, id: string, status: CameraStatus): void {
const camera = state.cameras.find((c) => c.id === id);
if (!camera || camera.status === status) return;
state.cameras = state.cameras.map((c) =>
c.id === id ? { ...c, status, lastSeenAt: new Date().toISOString() } : c
);
if (status === 'ONLINE' || status === 'OFFLINE' || status === 'ERROR') {
const eventType = status === 'ONLINE' ? 'CAMERA_ONLINE' : status === 'ERROR' ? 'CAMERA_ERROR' : 'CAMERA_OFFLINE';
this.#addEvent(state, {
type: eventType,
targetId: camera.id,
targetName: camera.name,
message: `${camera.location}の${camera.name}が${CAMERA_STATUS_LABEL_JA[status]}になりました`
});
}
}
#triggerSensor(state: SharedState, id: string): void {
const sensor = state.sensors.find((s) => s.id === id);
if (!sensor || sensor.status === 'TRIGGERED' || sensor.status === 'OFFLINE') return;
const message = `${sensor.location}の${sensor.name}が反応しました`;
state.sensors = state.sensors.map((s) =>
s.id === id
? {
...s,
status: 'TRIGGERED' as SensorStatus,
lastTriggeredAt: new Date().toISOString(),
lastEventMessage: message
}
: s
);
this.#addEvent(state, { type: 'SENSOR_TRIGGERED', targetId: sensor.id, targetName: sensor.name, message });
}
#resetSensor(state: SharedState, id: string): void {
const sensor = state.sensors.find((s) => s.id === id);
if (!sensor || sensor.status !== 'TRIGGERED') return;
const message = `${sensor.location}の${sensor.name}が解除されました`;
state.sensors = state.sensors.map((s) =>
s.id === id ? { ...s, status: 'NORMAL', lastEventMessage: message } : s
);
this.#addEvent(state, { type: 'SENSOR_RESET', targetId: sensor.id, targetName: sensor.name, message });
}
#reportQrDetection(state: SharedState, cameraId: string, qrText: string): void {
const camera = state.cameras.find((c) => c.id === cameraId);
if (!camera) return;
if (qrText.trim() === ALERT_QR_CONTENT) {
this.#broadcast({ type: 'alertQrSeen', cameraId, at: Date.now() });
}
const dedupeKey = `${cameraId}\u0000${qrText}`;
const now = Date.now();
const lastSeenAt = this.#lastQrDetectionAt.get(dedupeKey);
if (lastSeenAt !== undefined && now - lastSeenAt < QR_DETECTION_COOLDOWN_MS) return;
this.#lastQrDetectionAt.set(dedupeKey, now);
this.#addEvent(state, {
type: 'QR_DETECTED',
targetId: camera.id,
targetName: camera.name,
message: `${camera.location}の${camera.name}でQRコードを検知しました(内容: ${qrText})`
});
}
}
ブラウザのlocalStorageへの保存・読み込みを薄くラップしたユーティリティです。
データが壊れていたり、プライベートブラウジングなどでlocalStorage自体が
使えない環境でも、エラーにせず「初期値(fallback)」にそっと戻すようにしてあります。
browserフラグでサーバー側描画(SSR)中かどうかを判定し、サーバー上では何もしません。try/catchで囲むことで、保存先が使えない状況でもアプリ全体が落ちないようにしています。import { browser } from '$app/env';
export function loadFromStorage<T>(key: string, fallback: T): T {
if (!browser) return fallback;
try {
const raw = localStorage.getItem(key);
if (!raw) return fallback;
return JSON.parse(raw) as T;
} catch {
return fallback;
}
}
export function saveToStorage<T>(key: string, value: T): void {
if (!browser) return;
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// localStorage unavailable (quota exceeded, private mode, etc.) — ignore
}
}
export function removeFromStorage(key: string): void {
if (!browser) return;
try {
localStorage.removeItem(key);
} catch {
// ignore
}
}
状態共有サーバー(Workers)側の型定義です。アプリ本体のsrc/lib/types/index.tsと
内容はほぼ同じですが、サーバー側は別のデプロイ単位(tools/realtime-worker)として
単独でビルド・デプロイされるため、あえてコピーとして持たせています。
// Mirrors the subset of src/lib/types/index.ts that is shared across devices.
// Kept as a standalone copy (not imported from the SvelteKit app) so this
// Worker can be built and deployed independently of the main app.
export type CameraStatus = 'ONLINE' | 'OFFLINE' | 'CONNECTING' | 'ERROR';
export type CameraConnectionType = 'RTSP_MOCK' | 'RTSP_LIVE';
export interface Camera {
id: string;
name: string;
location: string;
ipAddress: string;
connectionType: CameraConnectionType;
status: CameraStatus;
lastSeenAt: string | null;
videoEnabled: boolean;
mockImage: string;
streamUrl?: string;
themeColor?: string;
}
export type SensorStatus = 'NORMAL' | 'TRIGGERED' | 'OFFLINE' | 'ERROR';
export type SensorType = 'IR_BEAM' | 'PRESSURE_MAT';
export interface Sensor {
id: string;
name: string;
type: SensorType;
location: string;
status: SensorStatus;
lastTriggeredAt: string | null;
lastEventMessage: string | null;
}
export type EventType =
| 'SENSOR_TRIGGERED'
| 'SENSOR_RESET'
| 'CAMERA_ONLINE'
| 'CAMERA_OFFLINE'
| 'CAMERA_ERROR'
| 'QR_DETECTED'
| 'SYSTEM_WARNING'
| 'SYSTEM_INFO';
export interface SystemEvent {
id: string;
type: EventType;
targetId: string;
targetName: string;
message: string;
timestamp: string;
}
/** The subset of app state shared across all connected devices via the room. */
export interface SharedState {
cameras: Camera[];
sensors: Sensor[];
events: SystemEvent[];
dashboardCameraCount: number;
}
/** Messages a client sends to the room. */
export type ClientMessage =
| { type: 'addCamera'; camera: Camera }
| { type: 'updateCamera'; id: string; patch: Partial<Camera> }
| { type: 'removeCamera'; id: string }
| { type: 'setCameraStatus'; id: string; status: CameraStatus }
| { type: 'toggleCameraVideo'; id: string }
| { type: 'triggerSensor'; id: string }
| { type: 'resetSensor'; id: string }
| { type: 'setSensorStatus'; id: string; status: SensorStatus }
| { type: 'reportQrDetection'; cameraId: string; qrText: string }
| { type: 'addEvent'; event: Omit<SystemEvent, 'id' | 'timestamp'> }
| { type: 'clearEvents' }
| { type: 'setDashboardCameraCount'; count: number }
| { type: 'resetAllCameras' }
| { type: 'resetAllSensors' }
| { type: 'restoreInitialData' };
/** Messages the room sends to clients. */
export type ServerMessage =
| { type: 'state'; state: SharedState }
| { type: 'alertQrSeen'; cameraId: string; at: number };
Workerの一番外側の入口(エントリーポイント)です。届いたHTTPリクエストを見て、
「WebSocketへの接続要求で、パスが/roomであること」を確認したうえで、
実際の処理を担当するRoom(Durable Object、room.ts参照)に引き渡します。
ALLOWED_ORIGIN_SUFFIXESという設定で、どのドメインからの接続を許可するかを制限できます(例: 本番ドメインとそのプレビューのみ許可)。未設定時は開発のしやすさを優先し、どこからでも接続を許可します。default)につながる設計で、1つのダッシュボードをみんなで共有する要件に合わせています。export { Room } from './room';
// `Env` (ROOM binding) comes from the generated worker-configuration.d.ts
// (`npm run types`). ALLOWED_ORIGINS is a plain string var set in
// wrangler.jsonc `vars` — extend the generated interface here since it isn't
// auto-detected from `vars`.
declare global {
interface Env {
/**
* Comma-separated list of hostname suffixes to allow for the WebSocket
* upgrade's Origin header (e.g. "spy-control-center.pages.dev" allows
* both the production domain and every *.spy-control-center.pages.dev
* preview deployment; "localhost:5180" allows local dev). No allowlist
* configured means "allow any origin", which is fine for local dev but
* should be set before relying on this in production.
*/
ALLOWED_ORIGIN_SUFFIXES?: string;
}
}
const DEFAULT_ROOM_NAME = 'default';
function isOriginAllowed(origin: string | null, env: Env): boolean {
if (!env.ALLOWED_ORIGIN_SUFFIXES) return true; // no allowlist configured -> allow (dev convenience)
if (!origin) return false;
let host: string;
try {
host = new URL(origin).host;
} catch {
return false;
}
const suffixes = env.ALLOWED_ORIGIN_SUFFIXES.split(',').map((s) => s.trim());
return suffixes.some((suffix) => host === suffix || host.endsWith(`.${suffix}`));
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname !== '/room') {
return new Response('Not found', { status: 404 });
}
if (!isOriginAllowed(request.headers.get('Origin'), env)) {
return new Response('Origin not allowed', { status: 403 });
}
// Single shared room for now — every client connects to the same
// namespace instance, matching the "everyone sees one dashboard"
// requirement. A `?room=` query param could split this into multiple
// rooms later without changing the client protocol.
const roomName = url.searchParams.get('room') ?? DEFAULT_ROOM_NAME;
const id = env.ROOM.idFromName(roomName);
const stub = env.ROOM.get(id);
return stub.fetch(request);
}
};
実機カメラ(Tapo C100など)の映像をブラウザで見られるようにするための、go2rtcというソフトの設定・起動スクリプト一式です。
go2rtc.yaml にカメラのRTSP接続先(IPアドレス・ユーザー名・パスワード)を記入します。この設定ファイルはパスワードを含むため、Gitの管理対象外(.gitignore)になっています。wss://)に対応させる必要があります(ブラウザは暗号化されたページから非暗号化の接続を自動的にブロックするため)。| パーツ | デプロイ先 | 状態 |
|---|---|---|
| アプリ本体 | spy-control-center.pages.dev | 公開中 |
| 状態共有サーバー | Cloudflare Workers(Durable Objects) | 公開中 |
| カメラ映像サーバー(go2rtc) | 運営スタッフのPC(ローカル/LAN限定) | 任意・運用時のみ起動 |