Spaces:
Paused
Paused
File size: 17,061 Bytes
5a81b95 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 | # Smart Home Widget Architecture - Auto-Discovery & Communication
## π― CORE REQUIREMENTS
Alle smart home widgets SKAL:
1. β
**Auto-discover datakilder** via SourceWidgetDiscovery
2. β
**Kommunikere med andre widgets** via WidgetCommunication
3. β
**Anbefale manglende kilder** til brugeren
4. β
**Subscribe til relevante data streams** via useLiveData
---
## ποΈ WIDGET ARCHITECTURE
### Universal Widget Structure
Alle widgets implementeres med samme base architecture:
```typescript
import { useWidgetCommunication } from '@/contexts/WidgetContext';
import { useLiveData } from '@/hooks/useLiveData';
import { useSourceDiscovery } from '@/services/SourceWidgetDiscovery';
interface SmartHomeWidgetProps {
widgetId: string;
config?: Record<string, any>;
}
export function SonosWidget({ widgetId, config }: SmartHomeWidgetProps) {
// 1. AUTO-DISCOVERY: Connect to data sources automatically
const {
data: sonosData,
connected,
recommendedSources,
connectionStatus
} = useLiveData({
widgetId,
widgetType: 'sonos',
requiredSources: ['sonos-api', 'music-stream'],
autoConnect: true,
});
// 2. INTER-WIDGET COMMUNICATION: Send and receive events
const { broadcastEvent, subscribeToEvent, getWidgetState } = useWidgetCommunication(widgetId);
// 3. SOURCE RECOMMENDATIONS: Suggest missing sources
const { discoverSources, canGenerateWidget } = useSourceDiscovery();
// Example: Broadcast when music starts playing
const handlePlayMusic = async (track: Track) => {
await playOnSonos(track);
// Notify other widgets
broadcastEvent({
type: 'music.started',
source: widgetId,
data: {
track: track.name,
artist: track.artist,
room: getCurrentRoom(),
}
});
};
// Example: Listen for events from other widgets
useEffect(() => {
// If doorbell rings, pause music
subscribeToEvent('doorbell.pressed', (event) => {
pauseMusic();
setTimeout(() => resumeMusic(), 30000); // Resume after 30s
});
// If TV turns on, lower music volume
subscribeToEvent('tv.power.on', (event) => {
setVolume(20); // Lower to background level
});
}, []);
return (
<div className="sonos-widget">
{/* Connection status indicator */}
<ConnectionIndicator status={connectionStatus} />
{/* Recommend missing sources */}
{recommendedSources.length > 0 && (
<SourceRecommendationPanel
sources={recommendedSources}
onEnable={(source) => enableSource(source)}
/>
)}
{/* Widget content */}
{connected && <MusicPlayer data={sonosData} />}
</div>
);
}
```
---
## π‘ DATA SOURCE AUTO-DISCOVERY
### How Widgets Find Their Data:
```typescript
// Backend: Register all smart home sources
// apps/backend/src/routes/acquisition.ts
const SMART_HOME_SOURCES = [
{
id: 'sonos-api',
type: 'music',
protocol: 'http',
endpoint: process.env.SONOS_API_URL,
capabilities: ['play', 'pause', 'volume', 'queue'],
requiredBy: ['sonos', 'spotify', 'music-player'],
},
{
id: 'nest-camera-stream',
type: 'camera',
protocol: 'webrtc',
endpoint: process.env.NEST_CAMERA_API,
capabilities: ['live-stream', 'snapshot', 'motion-detect'],
requiredBy: ['nest-camera', 'security-camera', 'doorbell'],
},
{
id: 'roomba-local',
type: 'vacuum',
protocol: 'rest',
endpoint: 'http://roomba.local:8080',
capabilities: ['start', 'stop', 'dock', 'status'],
requiredBy: ['robot-vacuum'],
},
// ... etc
];
// Auto-register on backend startup
app.post('/api/acquisition/register-smart-home-sources', async (req, res) => {
for (const source of SMART_HOME_SOURCES) {
await sourceRegistry.registerSource(source);
}
res.json({ registered: SMART_HOME_SOURCES.length });
});
```
### Widget Auto-Connection Flow:
```
1. Widget mounts β useLiveData({ widgetType: 'sonos' })
2. Hook queries: GET /api/acquisition/sources?type=music
3. Backend returns matching sources: ['sonos-api', 'spotify-web-api']
4. Widget auto-connects to available sources
5. If source missing β Recommend to user via SourceRecommendationPanel
6. User clicks "Enable" β POST /api/acquisition/enable-source
7. Widget reconnects automatically
```
---
## π INTER-WIDGET COMMUNICATION
### Event Bus Architecture:
```typescript
// Shared event types across all widgets
export enum WidgetEventType {
// Music events
MUSIC_STARTED = 'music.started',
MUSIC_PAUSED = 'music.paused',
MUSIC_STOPPED = 'music.stopped',
VOLUME_CHANGED = 'music.volume.changed',
// TV/Media events
TV_POWER_ON = 'tv.power.on',
TV_POWER_OFF = 'tv.power.off',
TV_INPUT_CHANGED = 'tv.input.changed',
MEDIA_PLAYING = 'media.playing',
// Security events
DOORBELL_PRESSED = 'doorbell.pressed',
MOTION_DETECTED = 'camera.motion',
DOOR_UNLOCKED = 'lock.unlocked',
ALARM_TRIGGERED = 'alarm.triggered',
// Automation events
VACUUM_STARTED = 'vacuum.started',
VACUUM_FINISHED = 'vacuum.finished',
MOWER_STARTED = 'mower.started',
// Climate events
TEMPERATURE_CHANGED = 'thermostat.temp.changed',
HVAC_MODE_CHANGED = 'thermostat.mode.changed',
// General
PRESENCE_DETECTED = 'presence.detected',
PRESENCE_LEFT = 'presence.left',
}
// Example: Sonos Widget listening to multiple events
export function SonosWidget({ widgetId }: SmartHomeWidgetProps) {
const { subscribeToEvent, broadcastEvent } = useWidgetCommunication(widgetId);
useEffect(() => {
// Pause music when doorbell rings
const unsubDoorbell = subscribeToEvent(
WidgetEventType.DOORBELL_PRESSED,
(event) => {
if (isPlaying()) {
pauseMusic();
showNotification('Paused music - Doorbell');
}
}
);
// Lower volume when TV turns on
const unsubTV = subscribeToEvent(
WidgetEventType.TV_POWER_ON,
(event) => {
if (isPlaying() && getCurrentVolume() > 30) {
setVolume(20);
showNotification('Lowered volume - TV is on');
}
}
);
// Resume when vacuum finishes
const unsubVacuum = subscribeToEvent(
WidgetEventType.VACUUM_FINISHED,
(event) => {
if (wasPausedByAutomation) {
resumeMusic();
}
}
);
return () => {
unsubDoorbell();
unsubTV();
unsubVacuum();
};
}, []);
}
```
---
## π€ SMART AUTOMATION SCENARIOS
### Scenario 1: Movie Night Mode
```typescript
// TV Widget broadcasts "movie mode starting"
function TvWidget() {
const startMovieMode = () => {
broadcastEvent({
type: 'media.movie-mode.start',
data: { movie: currentMovie }
});
};
}
// Sonos Widget lowers music
function SonosWidget() {
subscribeToEvent('media.movie-mode.start', () => {
setVolume(5);
});
}
// Smart Lights Widget dims lights
function LightsWidget() {
subscribeToEvent('media.movie-mode.start', () => {
setScene('movie');
setBrightness(20);
});
}
// Thermostat lowers temp slightly
function ThermostatWidget() {
subscribeToEvent('media.movie-mode.start', () => {
setTemp(currentTemp - 1);
});
}
```
### Scenario 2: Vacuum Cleaning Coordination
```typescript
// Robot Vacuum broadcasts start
function VacuumWidget() {
const startCleaning = () => {
broadcastEvent({
type: 'vacuum.started',
data: { room: 'living-room' }
});
};
}
// Sonos pauses music in that room
function SonosWidget() {
subscribeToEvent('vacuum.started', (event) => {
if (event.data.room === currentRoom) {
pauseMusic();
}
});
}
// Pet Feeder delays feeding
function PetFeederWidget() {
subscribeToEvent('vacuum.started', () => {
delayNextFeeding(30); // Wait 30 min
});
}
```
### Scenario 3: Security Alert Chain
```typescript
// Camera detects motion
function CameraWidget() {
onMotionDetected(() => {
broadcastEvent({
type: 'camera.motion',
data: {
camera: 'front-door',
snapshot: snapshotUrl,
confidence: 0.95
}
});
});
}
// Smart Lock checks status
function LockWidget() {
subscribeToEvent('camera.motion', (event) => {
if (!isLocked()) {
showAlert('Motion detected - Door unlocked!');
}
});
}
// Lights turn on
function LightsWidget() {
subscribeToEvent('camera.motion', (event) => {
if (isNightTime() && event.data.camera === 'front-door') {
turnOnPorchLights();
}
});
}
// Sonos announces
function SonosWidget() {
subscribeToEvent('camera.motion', (event) => {
if (event.data.confidence > 0.9) {
announceOnSpeakers('Motion detected at front door');
}
});
}
```
---
## π SOURCE RECOMMENDATION SYSTEM
### How Widgets Suggest Missing Sources:
```typescript
// Backend endpoint to check widget requirements
app.get('/api/widget-sources/:widgetType', async (req, res) => {
const { widgetType } = req.params;
const requirements = WIDGET_REQUIREMENTS[widgetType];
const availableSources = await sourceRegistry.getSources();
const missing = requirements.required.filter(
req => !availableSources.find(s => s.id === req)
);
const optional = requirements.optional.filter(
opt => !availableSources.find(s => s.id === opt)
);
res.json({
widgetType,
available: availableSources,
missing,
optional,
recommendations: missing.map(m => ({
sourceId: m,
setupUrl: `/setup/${m}`,
difficulty: 'easy',
estimatedTime: '5 minutes'
}))
});
});
// Widget requirements mapping
const WIDGET_REQUIREMENTS = {
'sonos': {
required: ['sonos-api'],
optional: ['spotify-web-api', 'apple-music-api'],
},
'nest-camera': {
required: ['nest-camera-stream', 'google-sdm-api'],
optional: ['object-detection-ml'],
},
'robot-vacuum': {
required: ['roomba-local'],
optional: ['floor-plan-image', 'home-assistant'],
},
// ...
};
```
### Frontend: Source Recommendation Panel
```typescript
export function SourceRecommendationPanel({ sources, onEnable }) {
return (
<div className="bg-orange-500/10 border border-orange-500/30 rounded p-3 mb-3">
<div className="flex items-center gap-2 mb-2">
<AlertTriangle className="w-4 h-4 text-orange-400" />
<span className="text-sm font-medium">Missing Data Sources</span>
</div>
{sources.map(source => (
<div key={source.id} className="flex items-center justify-between mb-2">
<div>
<p className="text-xs font-medium">{source.name}</p>
<p className="text-xs opacity-60">{source.description}</p>
</div>
<button
onClick={() => onEnable(source)}
className="px-3 py-1 bg-orange-500 text-white rounded text-xs"
>
Enable
</button>
</div>
))}
</div>
);
}
```
---
## π§ IMPLEMENTATION CHECKLIST
### For Each New Smart Home Widget:
- [ ] **1. Define Widget Requirements**
```typescript
const WIDGET_CONFIG = {
type: 'sonos',
requiredSources: ['sonos-api'],
optionalSources: ['spotify-web-api'],
requiredCapabilities: ['play', 'pause', 'volume'],
};
```
- [ ] **2. Implement useLiveData Hook**
```typescript
const { data, connected, recommendedSources } = useLiveData({
widgetId,
widgetType: 'sonos',
autoConnect: true,
});
```
- [ ] **3. Setup Widget Communication**
```typescript
const { broadcastEvent, subscribeToEvent } = useWidgetCommunication(widgetId);
```
- [ ] **4. Define Events Widget Broadcasts**
```typescript
// On state change
broadcastEvent({ type: 'music.started', data: {...} });
```
- [ ] **5. Subscribe to Relevant Events**
```typescript
subscribeToEvent('doorbell.pressed', handleDoorbell);
subscribeToEvent('tv.power.on', handleTVOn);
```
- [ ] **6. Add Source Recommendations UI**
```typescript
{recommendedSources.length > 0 && (
<SourceRecommendationPanel sources={recommendedSources} />
)}
```
- [ ] **7. Register Backend Source**
```typescript
await sourceRegistry.registerSource({
id: 'sonos-api',
type: 'music',
endpoint: process.env.SONOS_API_URL,
});
```
- [ ] **8. Test Inter-Widget Communication**
- Verify events broadcast correctly
- Verify other widgets respond
- Test multiple widgets simultaneously
---
## π― EXAMPLE: Complete Sonos Widget
```typescript
import React, { useEffect, useState } from 'react';
import { useLiveData } from '@/hooks/useLiveData';
import { useWidgetCommunication } from '@/contexts/WidgetContext';
import { SourceRecommendationPanel } from '@/components/SourceRecommendationPanel';
import { WidgetEventType } from '@/types/widget-events';
export function SonosWidget({ widgetId }: { widgetId: string }) {
// 1. AUTO-CONNECT TO DATA SOURCES
const {
data: sonosData,
connected,
recommendedSources,
connectionStatus,
refetch,
} = useLiveData({
widgetId,
widgetType: 'sonos',
requiredSources: ['sonos-api'],
optionalSources: ['spotify-web-api'],
autoConnect: true,
pollInterval: 5000,
});
// 2. WIDGET COMMUNICATION
const { broadcastEvent, subscribeToEvent, getWidgetState } =
useWidgetCommunication(widgetId);
const [isPaused, setIsPaused] = useState(false);
// 3. HANDLE EXTERNAL EVENTS
useEffect(() => {
// Pause on doorbell
const unsubDoorbell = subscribeToEvent(
WidgetEventType.DOORBELL_PRESSED,
(event) => {
if (sonosData?.isPlaying) {
pauseMusic();
setTimeout(() => resumeMusic(), 30000);
}
}
);
// Lower volume for TV
const unsubTV = subscribeToEvent(
WidgetEventType.TV_POWER_ON,
(event) => {
if (sonosData?.volume > 30) {
setVolume(20);
}
}
);
// Resume after vacuum
const unsubVacuum = subscribeToEvent(
WidgetEventType.VACUUM_FINISHED,
() => {
if (isPaused) {
resumeMusic();
}
}
);
return () => {
unsubDoorbell();
unsubTV();
unsubVacuum();
};
}, [sonosData, isPaused]);
// 4. BROADCAST OWN EVENTS
const handlePlay = async (track: Track) => {
await playOnSonos(track);
broadcastEvent({
type: WidgetEventType.MUSIC_STARTED,
source: widgetId,
data: {
track: track.name,
artist: track.artist,
album: track.album,
room: sonosData?.currentRoom,
}
});
};
const handleVolumeChange = async (newVolume: number) => {
await setVolume(newVolume);
broadcastEvent({
type: WidgetEventType.VOLUME_CHANGED,
source: widgetId,
data: {
volume: newVolume,
room: sonosData?.currentRoom,
}
});
};
return (
<div className="sonos-widget">
{/* Source Recommendations */}
{recommendedSources.length > 0 && (
<SourceRecommendationPanel
sources={recommendedSources}
onEnable={async (source) => {
await enableSource(source.id);
refetch();
}}
/>
)}
{/* Connection Status */}
<ConnectionIndicator
status={connectionStatus}
sources={connected ? sonosData?.sources : []}
/>
{/* Widget Content */}
{connected && sonosData && (
<div className="music-player">
<NowPlaying track={sonosData.currentTrack} />
<VolumeControl
volume={sonosData.volume}
onChange={handleVolumeChange}
/>
<PlaybackControls
isPlaying={sonosData.isPlaying}
onPlay={() => handlePlay(sonosData.queue[0])}
onPause={pauseMusic}
/>
</div>
)}
</div>
);
}
```
---
## π COMPLETE WIDGET LIST WITH COMMUNICATION
| Widget | Broadcasts | Listens To |
|--------|-----------|------------|
| **Sonos** | `music.started`, `music.paused`, `volume.changed` | `doorbell.pressed`, `tv.power.on`, `vacuum.started` |
| **Nest Camera** | `motion.detected`, `person.detected`, `doorbell.pressed` | `alarm.triggered`, `presence.left` |
| **Robot Vacuum** | `vacuum.started`, `vacuum.finished`, `vacuum.error` | `presence.detected`, `music.started` |
| **Smart TV** | `tv.power.on`, `tv.power.off`, `media.playing` | `doorbell.pressed`, `alarm.triggered` |
| **Thermostat** | `temp.changed`, `mode.changed` | `presence.detected`, `presence.left`, `media.movie-mode.start` |
| **Smart Lock** | `lock.unlocked`, `lock.locked` | `motion.detected`, `presence.detected` |
| **Lawn Mower** | `mower.started`, `mower.finished` | `weather.rain`, `presence.detected` |
| **Lights** | `lights.on`, `lights.off`, `scene.changed` | `motion.detected`, `tv.power.on`, `presence.left` |
---
**Architecture:** Auto-Discovery + Inter-Widget Communication
**Backend:** Source Registry + Event Bus
**Frontend:** useLiveData + useWidgetCommunication
**Date:** 2025-12-10
|