forked from Zive-IT-2025/Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlight_controller.py
More file actions
577 lines (458 loc) · 20.6 KB
/
light_controller.py
File metadata and controls
577 lines (458 loc) · 20.6 KB
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
"""
Light Controller Module
Supports multiple lighting control backends: simulated, MQTT, HTTP, Philips Hue, OpenLab
"""
import time
import logging
import json
from typing import Optional, Dict
from abc import ABC, abstractmethod
import requests
from enum import Enum
# Optional MQTT support
try:
import paho.mqtt.client as mqtt
MQTT_AVAILABLE = True
except ImportError:
MQTT_AVAILABLE = False
logging.warning("paho-mqtt not installed. MQTT support disabled.")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class LightState(Enum):
"""Light states"""
OFF = "off"
ON = "on"
TRANSITIONING = "transitioning"
class LightController(ABC):
"""Abstract base class for light controllers"""
def __init__(self, config: dict):
self.config = config
self.current_brightness = 0
self.target_brightness = 0
self.state = LightState.OFF
self.last_update = time.time()
self.brightness_levels = config.get('brightness', {
'off': 0,
'low': 30,
'medium': 60,
'high': 100
})
self.default_on_brightness = config.get('default_on_brightness', 80)
self.fade_duration = config.get('fade_duration', 1.0)
self.debounce_time = config.get('debounce_time', 2.0)
self.auto_off_delay = config.get('auto_off_delay', 2.0)
# Dynamic brightness settings
self.dynamic_config = config.get('dynamic_brightness', {})
self.dynamic_enabled = self.dynamic_config.get('enabled', True)
self.min_brightness = self.dynamic_config.get('min_brightness', 20)
self.max_brightness = self.dynamic_config.get('max_brightness', 100)
self.score_threshold = self.dynamic_config.get('score_threshold', 0.05)
self.score_ceiling = self.dynamic_config.get('score_ceiling', 0.3)
self.class_weights = self.dynamic_config.get('class_weights', {'person': 1.0, 'default': 0.1})
self.last_detection_time = 0
def calculate_brightness_from_detections(self, detections: list, frame_size: tuple) -> int:
"""
Calculate brightness based on detection score
Formula: score = sum(confidence_i × relative_area_i × class_weight_i)
Args:
detections: List of Detection objects with .confidence, .area, .class_name
frame_size: Tuple (width, height) of frame for calculating relative area
Returns:
Brightness value (0-100)
"""
if not self.dynamic_enabled or not detections:
return 0
# Calculate total frame area
frame_width, frame_height = frame_size
total_frame_area = frame_width * frame_height
# Calculate score
score = 0.0
for detection in detections:
confidence = detection.confidence
relative_area = detection.area / total_frame_area
# Get class weight (use default if class not in weights)
class_weight = self.class_weights.get(
detection.class_name,
self.class_weights.get('default', 0.1)
)
detection_score = confidence * relative_area * class_weight
score += detection_score
logger.debug(f"Detection score: {detection.class_name} conf={confidence:.2f} "
f"area={relative_area:.4f} weight={class_weight} -> {detection_score:.4f}")
logger.info(f"Total detection score: {score:.4f}")
# Check if score meets threshold
if score < self.score_threshold:
return 0
# Map score to brightness range [min_brightness, max_brightness]
# score_threshold maps to min_brightness
# score_ceiling maps to max_brightness
normalized_score = min(1.0, (score - self.score_threshold) /
(self.score_ceiling - self.score_threshold))
brightness = int(self.min_brightness +
normalized_score * (self.max_brightness - self.min_brightness))
# Clamp to valid range
brightness = max(0, min(100, brightness))
logger.info(f"Calculated brightness: {brightness}% (score: {score:.4f}, normalized: {normalized_score:.2f})")
return brightness
@abstractmethod
def set_brightness(self, brightness: int):
"""Set light brightness (0-100)"""
pass
@abstractmethod
def get_status(self) -> dict:
"""Get current light status"""
pass
def turn_on(self, brightness: Optional[int] = None):
"""Turn lights on"""
if brightness is None:
brightness = self.default_on_brightness
logger.info(f"Turning lights ON (brightness: {brightness})")
self.target_brightness = brightness
self.state = LightState.ON
self.set_brightness(brightness)
def turn_off(self):
"""Turn lights off"""
logger.info("Turning lights OFF")
self.target_brightness = 0
self.state = LightState.OFF
self.set_brightness(0)
def update_from_detections(self, detections: list, frame_size: tuple):
"""
Update light brightness based on current detections
Args:
detections: List of Detection objects
frame_size: Tuple (width, height) of frame
"""
current_time = time.time()
if detections:
# Calculate brightness from detections
calculated_brightness = self.calculate_brightness_from_detections(detections, frame_size)
if calculated_brightness > 0:
# Update detection time
self.last_detection_time = current_time
# Set brightness immediately (no debounce - allow smooth real-time changes)
self.target_brightness = calculated_brightness
self.state = LightState.ON
self.set_brightness(calculated_brightness)
self.last_update = current_time
else:
# No detections - handle auto-off
self.on_no_detection()
def on_object_detected(self):
"""Called when a target object is detected (DEPRECATED - use update_from_detections)"""
current_time = time.time()
# Debounce check
if current_time - self.last_detection_time < self.debounce_time:
# Update detection time but don't change lights rapidly
self.last_detection_time = current_time
return
self.last_detection_time = current_time
# Turn on lights if not already on
if self.state == LightState.OFF:
self.turn_on()
def on_no_detection(self):
"""Called when no objects are detected"""
current_time = time.time()
# Only turn off after auto_off_delay
if self.state == LightState.ON:
time_since_detection = current_time - self.last_detection_time
# if time_since_detection > self.auto_off_delay:
if time_since_detection > 2.0:
logger.info(f"No detection for {time_since_detection:.1f}s, turning off")
self.turn_off()
class SimulatedLightController(LightController):
"""Simulated light controller for testing"""
def __init__(self, config: dict):
super().__init__(config)
logger.info("Initialized Simulated Light Controller")
def set_brightness(self, brightness: int):
"""Set brightness (simulated)"""
brightness = max(0, min(100, brightness)) # Clamp to 0-100
self.current_brightness = brightness
self.last_update = time.time()
logger.info(f"[SIMULATED] Light brightness set to: {brightness}%")
def get_current_brightness(self) -> int:
"""Get current brightness level"""
return self.current_brightness
def get_status(self) -> dict:
"""Get status"""
return {
"mode": "simulated",
"state": self.state.value,
"current_brightness": self.current_brightness,
"target_brightness": self.target_brightness,
"last_update": self.last_update,
"last_detection": self.last_detection_time
}
class MQTTLightController(LightController):
"""MQTT-based light controller"""
def __init__(self, config: dict):
super().__init__(config)
if not MQTT_AVAILABLE:
raise ImportError("paho-mqtt not installed")
mqtt_config = config.get('mqtt', {})
self.broker = mqtt_config.get('broker', 'localhost')
self.port = mqtt_config.get('port', 1883)
self.topic = mqtt_config.get('topic', 'home/lights/control')
self.username = mqtt_config.get('username')
self.password = mqtt_config.get('password')
# Create MQTT client
self.client = mqtt.Client()
if self.username and self.password:
self.client.username_pw_set(self.username, self.password)
try:
self.client.connect(self.broker, self.port, 60)
self.client.loop_start()
logger.info(f"Connected to MQTT broker: {self.broker}:{self.port}")
except Exception as e:
logger.error(f"Failed to connect to MQTT broker: {e}")
raise
def set_brightness(self, brightness: int):
"""Set brightness via MQTT"""
brightness = max(0, min(100, brightness))
try:
payload = str(brightness)
self.client.publish(self.topic, payload)
self.current_brightness = brightness
self.last_update = time.time()
logger.info(f"Published brightness {brightness} to {self.topic}")
except Exception as e:
logger.error(f"Error publishing to MQTT: {e}")
def get_status(self) -> dict:
"""Get status"""
return {
"mode": "mqtt",
"broker": self.broker,
"topic": self.topic,
"state": self.state.value,
"current_brightness": self.current_brightness,
"target_brightness": self.target_brightness,
"last_update": self.last_update,
"last_detection": self.last_detection_time
}
def __del__(self):
"""Cleanup"""
if hasattr(self, 'client'):
self.client.loop_stop()
self.client.disconnect()
class HTTPLightController(LightController):
"""HTTP API-based light controller"""
def __init__(self, config: dict):
super().__init__(config)
http_config = config.get('http', {})
self.url = http_config.get('url', 'http://localhost:8000/api/lights')
self.method = http_config.get('method', 'POST').upper()
logger.info(f"Initialized HTTP Light Controller: {self.url}")
def set_brightness(self, brightness: int):
"""Set brightness via HTTP API"""
brightness = max(0, min(100, brightness))
try:
payload = {"brightness": brightness}
if self.method == 'POST':
response = requests.post(self.url, json=payload, timeout=5)
elif self.method == 'PUT':
response = requests.put(self.url, json=payload, timeout=5)
else:
response = requests.get(self.url, params=payload, timeout=5)
response.raise_for_status()
self.current_brightness = brightness
self.last_update = time.time()
logger.info(f"HTTP request sent: brightness={brightness}, status={response.status_code}")
except Exception as e:
logger.error(f"Error sending HTTP request: {e}")
def get_status(self) -> dict:
"""Get status"""
return {
"mode": "http",
"url": self.url,
"method": self.method,
"state": self.state.value,
"current_brightness": self.current_brightness,
"target_brightness": self.target_brightness,
"last_update": self.last_update,
"last_detection": self.last_detection_time
}
class PhilipsHueLightController(LightController):
"""Philips Hue light controller"""
def __init__(self, config: dict):
super().__init__(config)
hue_config = config.get('hue', {})
self.bridge_ip = hue_config.get('bridge_ip', '192.168.1.100')
self.username = hue_config.get('username', 'your-hue-username')
self.light_ids = hue_config.get('light_ids', [1])
self.base_url = f"http://{self.bridge_ip}/api/{self.username}"
logger.info(f"Initialized Philips Hue Controller: {self.bridge_ip}")
def set_brightness(self, brightness: int):
"""Set brightness for Hue lights"""
brightness = max(0, min(100, brightness))
# Convert 0-100 to 0-254 (Hue range)
hue_brightness = int(brightness * 254 / 100)
try:
for light_id in self.light_ids:
url = f"{self.base_url}/lights/{light_id}/state"
if brightness == 0:
payload = {"on": False}
else:
payload = {"on": True, "bri": hue_brightness}
response = requests.put(url, json=payload, timeout=5)
response.raise_for_status()
self.current_brightness = brightness
self.last_update = time.time()
logger.info(f"Hue lights brightness set to: {brightness}%")
except Exception as e:
logger.error(f"Error controlling Hue lights: {e}")
def get_status(self) -> dict:
"""Get status"""
return {
"mode": "hue",
"bridge_ip": self.bridge_ip,
"light_ids": self.light_ids,
"state": self.state.value,
"current_brightness": self.current_brightness,
"target_brightness": self.target_brightness,
"last_update": self.last_update,
"last_detection": self.last_detection_time
}
class OpenLabLightController(LightController):
"""OpenLab MQTT-based light controller for TUKE school lights"""
def __init__(self, config: dict):
super().__init__(config)
if not MQTT_AVAILABLE:
raise ImportError("paho-mqtt not installed")
# OpenLab specific configuration
openlab_config = config.get('openlab', {})
self.broker = openlab_config.get('broker', 'openlab.kpi.fei.tuke.sk')
self.port = openlab_config.get('port', 1883)
self.topic = '/openlab/lights' # Fixed topic for OpenLab (with leading slash)
self.fade_duration_ms = int(config.get('fade_duration', 1.0) * 1000) # Convert to ms
# Light selection
self.control_all = openlab_config.get('control_all', True)
self.light_ids = openlab_config.get('light_ids', list(range(1, 98))) # All 97 lights by default
# Create MQTT client
self.client = mqtt.Client()
self.connected = False
# Set up callbacks
self.client.on_connect = self._on_connect
self.client.on_disconnect = self._on_disconnect
try:
logger.info(f"Connecting to OpenLab MQTT broker: {self.broker}:{self.port}")
self.client.connect(self.broker, self.port, 60)
self.client.loop_start()
logger.info("OpenLab Light Controller initialized")
except Exception as e:
logger.error(f"Failed to connect to OpenLab MQTT broker: {e}")
raise
def _on_connect(self, client, userdata, flags, rc):
"""Callback when connected to MQTT broker"""
if rc == 0:
self.connected = True
logger.info("Connected to OpenLab MQTT broker")
else:
logger.error(f"Failed to connect to OpenLab MQTT, return code: {rc}")
self.connected = False
def _on_disconnect(self, client, userdata, rc):
"""Callback when disconnected from MQTT broker"""
self.connected = False
logger.info("Disconnected from OpenLab MQTT broker")
def _brightness_to_rgbw(self, brightness: int) -> str:
"""
Convert brightness (0-100) to RGBW hex string
Args:
brightness: Brightness percentage (0-100)
Returns:
RGBW hex string (e.g., "0000ff00" for white at max)
"""
# Map brightness 0-100 to 0-255
white_value = int((brightness / 100.0) * 255)
# Format as RGBW: RGB=000000 (off), W=brightness
# Using pure white light (W channel only)
rgbw = f"000000{white_value:02x}"
return rgbw
def set_brightness(self, brightness: int):
"""Set brightness of OpenLab lights via MQTT"""
brightness = max(0, min(100, brightness))
if not self.connected:
logger.warning("Not connected to OpenLab MQTT broker")
return
try:
# Convert brightness to RGBW format
rgbw_value = self._brightness_to_rgbw(brightness)
# Create MQTT payload
if self.control_all:
# Control all lights at once
payload = {
"all": rgbw_value,
"duration": self.fade_duration_ms
}
else:
# Control specific lights
light_dict = {}
for light_id in self.light_ids:
light_dict[str(light_id)] = rgbw_value
payload = {
"light": light_dict,
"duration": self.fade_duration_ms
}
# Publish to OpenLab
json_payload = json.dumps(payload)
logger.info(f"Publishing to {self.topic}: {json_payload}")
result = self.client.publish(self.topic, json_payload, qos=0)
if result.rc == 0:
self.current_brightness = brightness
self.last_update = time.time()
logger.info(f"✓ OpenLab lights set to {brightness}% (RGBW: {rgbw_value}, duration: {self.fade_duration_ms}ms) - Message sent successfully")
else:
logger.error(f"✗ Failed to publish to OpenLab MQTT, return code: {result.rc}")
except Exception as e:
logger.error(f"Error controlling OpenLab lights: {e}")
def get_status(self) -> dict:
"""Get status"""
return {
"mode": "openlab",
"broker": self.broker,
"topic": self.topic,
"connected": self.connected,
"control_all": self.control_all,
"num_lights": len(self.light_ids) if not self.control_all else 97,
"state": self.state.value,
"current_brightness": self.current_brightness,
"target_brightness": self.target_brightness,
"last_update": self.last_update,
"last_detection": self.last_detection_time
}
def __del__(self):
"""Cleanup"""
if hasattr(self, 'client'):
try:
# Turn off lights on shutdown
logger.info("Shutting down OpenLab lights...")
self.turn_off()
time.sleep(0.5) # Give time for message to send
self.client.loop_stop()
self.client.disconnect()
except:
pass
def create_light_controller(config: dict) -> LightController:
"""
Factory function to create appropriate light controller
Args:
config: Lighting configuration dict
Returns:
LightController instance
"""
mode = config.get('mode', 'simulated').lower()
if mode == 'simulated':
return SimulatedLightController(config)
elif mode == 'mqtt':
return MQTTLightController(config)
elif mode == 'http':
return HTTPLightController(config)
elif mode == 'hue':
return PhilipsHueLightController(config)
elif mode == 'openlab':
logger.info("🔌 Creating OpenLab MQTT light controller for real OpenLab lights")
from openlab_light_controller import OpenLabLightController
return OpenLabLightController(config)
else:
logger.warning(f"Unknown mode '{mode}', using simulated")
return SimulatedLightController(config)