Repository navigation
Expand file tree
/
Copy pathalpaca_safety_monitor.py.canbedeleted
More file actions
2892 lines (2494 loc) · 154 KB
/
Copy pathalpaca_safety_monitor.py.canbedeleted
File metadata and controls
2892 lines (2494 loc) · 154 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
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
ASCOM Alpaca SafetyMonitor Server
Provides a safety monitor interface based on SimpleCloudDetect cloud detection:
https://github.com/chvvkumar/simpleCloudDetect
Authors: chvvkumar
"""
import logging
import socket
import threading
import time
import os
import signal
import sys
from dataclasses import dataclass, asdict, field
from datetime import datetime
from zoneinfo import ZoneInfo
from typing import Optional, Dict, Any, Tuple
import json
import base64
import io
from flask import Flask, request, jsonify, render_template_string, redirect, url_for, Response
from flask_cors import CORS
import paho.mqtt.client as mqtt
from PIL import Image
from detect import CloudDetector, Config as DetectConfig, HADiscoveryManager
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
start_time = datetime.now()
# Global timezone helper
def get_current_time(timezone_str: str = 'UTC') -> datetime:
"""Get current time in specified timezone"""
try:
tz = ZoneInfo(timezone_str)
return datetime.now(tz)
except Exception:
# Fallback to UTC if timezone is invalid
return datetime.now(ZoneInfo('UTC'))
# ASCOM Error Codes
ERROR_SUCCESS = 0
ERROR_NOT_IMPLEMENTED = 0x400 # 1024
ERROR_INVALID_VALUE = 0x401 # 1025
ERROR_NOT_CONNECTED = 0x407 # 1031
ERROR_UNSPECIFIED = 0x500 # 1280
# Available cloud conditions from ML model
ALL_CLOUD_CONDITIONS = ['Clear', 'Mostly Cloudy', 'Overcast', 'Rain', 'Snow', 'Wisps of clouds']
@dataclass
class AlpacaConfig:
"""Configuration for the Alpaca server"""
port: int = 11111
device_number: int = 0
device_name: str = "SimpleCloudDetect"
device_description: str = "ASCOM SafetyMonitor based on ML cloud detection"
driver_info: str = "ASCOM Alpaca SafetyMonitor v2.0 - Cloud Detection Driver"
driver_version: str = "2.0"
interface_version: int = 3 # Changed from 1 to 3
detection_interval: int = 30 # seconds between ML detections (from detect.py)
update_interval: int = 30 # seconds between cloud detection updates
location: str = "AllSky Camera"
image_url: str = field(default_factory=lambda: os.environ.get('IMAGE_URL', ''))
unsafe_conditions: list = field(default_factory=lambda: ['Rain', 'Snow', 'Mostly Cloudy', 'Overcast'])
# Confidence threshold settings
default_threshold: float = 50.0 # Default threshold for any class not explicitly configured
class_thresholds: Dict[str, float] = field(default_factory=dict) # Map class names to thresholds
# Debounce settings (in seconds)
debounce_to_safe_sec: int = 60 # Wait time before switching from Unsafe → Safe
debounce_to_unsafe_sec: int = 0 # Wait time before switching from Safe → Unsafe (immediate)
# NTP and timezone settings
ntp_server: str = field(default_factory=lambda: os.environ.get('NTP_SERVER', 'pool.ntp.org'))
timezone: str = field(default_factory=lambda: os.environ.get('TZ', 'UTC'))
def save_to_file(self, filepath: str = "alpaca_config.json"):
"""Save configuration to JSON file"""
try:
config_dict = asdict(self)
with open(filepath, 'w') as f:
json.dump(config_dict, f, indent=2)
logger.info(f"Configuration saved to {filepath}")
except Exception as e:
logger.error(f"Failed to save configuration: {e}")
@classmethod
def load_from_file(cls, filepath: str = "alpaca_config.json"):
"""Load configuration from JSON file with backward compatibility"""
try:
if os.path.exists(filepath):
with open(filepath, 'r') as f:
config_dict = json.load(f)
# Ensure new fields exist with defaults for backward compatibility
if 'default_threshold' not in config_dict:
config_dict['default_threshold'] = 50.0
if 'class_thresholds' not in config_dict:
config_dict['class_thresholds'] = {}
if 'debounce_to_safe_sec' not in config_dict:
config_dict['debounce_to_safe_sec'] = 60
if 'debounce_to_unsafe_sec' not in config_dict:
config_dict['debounce_to_unsafe_sec'] = 0
if 'detection_interval' not in config_dict:
config_dict['detection_interval'] = 30
if 'image_url' not in config_dict:
config_dict['image_url'] = os.environ.get('IMAGE_URL', '')
logger.info(f"Configuration loaded from {filepath}")
return cls(**config_dict)
except Exception as e:
logger.error(f"Failed to load configuration: {e}")
return None
class AlpacaSafetyMonitor:
"""ASCOM Alpaca SafetyMonitor implementation"""
def __init__(self, alpaca_config: AlpacaConfig, detect_config: DetectConfig):
self.alpaca_config = alpaca_config
self.detect_config = detect_config
self.server_transaction_id = 0
self.transaction_lock = threading.Lock()
# Device state
self.connected_clients: Dict[Tuple[str, int], datetime] = {} # (IP, ClientID) -> ConnectionTime
self.disconnected_clients: Dict[Tuple[str, int], Tuple[datetime, datetime]] = {} # (IP, ClientID) -> (ConnectionTime, DisconnectionTime)
self.connection_lock = threading.Lock()
self.connecting = False
self.connected_at: Optional[datetime] = None
self.disconnected_at: Optional[datetime] = None
self.last_connected_at: Optional[datetime] = None # Track last successful connection
self.client_ip: Optional[str] = None # Track connected client's IP address (deprecated in multi-client)
self.last_session_duration: Optional[float] = None
# Cloud detection state - use single lock for all state
self.latest_detection: Optional[Dict[str, Any]] = {
'class_name': 'Unknown',
'confidence_score': 0.0,
'Detection Time (Seconds)': 0.0,
'timestamp': None
}
self._cached_is_safe = False # Cache safe status to reduce lock contention
self._unsafe_conditions_set = set(alpaca_config.unsafe_conditions) # Set lookup is O(1)
# Debounce state tracking
self._stable_safe_state = False # The actual safe/unsafe value returned to the client
self._pending_safe_state: Optional[bool] = None # The potential new state we are waiting to verify
self._state_change_start_time: Optional[datetime] = None # Timestamp when pending state first appeared
# Safety state history (last 100 transitions)
self._safety_history: list = [] # List of (timestamp, is_safe, condition, confidence) tuples
# Latest detection image (base64 encoded)
self.latest_image_data: Optional[str] = None
self.detection_lock = threading.Lock()
self.detection_thread: Optional[threading.Thread] = None
self.stop_detection = threading.Event()
# Setup MQTT client first
self.mqtt_client = self._setup_mqtt()
self.ha_discovery = None
# Pre-load cloud detector at startup (pass MQTT client to avoid double connection)
logger.info("Pre-loading ML model...")
self.cloud_detector = CloudDetector(self.detect_config, mqtt_client=self.mqtt_client)
logger.info("ML model loaded successfully")
# Setup HA Discovery if enabled
if self.mqtt_client and self.detect_config.mqtt_discovery_mode == 'homeassistant':
self.ha_discovery = HADiscoveryManager(self.detect_config, self.mqtt_client)
self.ha_discovery.publish_discovery_configs()
# FIX: Blocking initial detection to ensure readiness (better than background thread)
logger.info("Performing initial detection (blocking)...")
try:
initial_result = self.cloud_detector.detect(return_image=True)
initial_result['timestamp'] = get_current_time(self.alpaca_config.timezone)
# Create thumbnail from the image that was just used for detection
initial_image = None
if 'image' in initial_result:
initial_image = self._create_thumbnail_from_image(initial_result['image'])
del initial_result['image']
with self.detection_lock:
self.latest_detection = initial_result
self.latest_image_data = initial_image
self._update_cached_safety(initial_result)
# Add initial state to safety history
self._safety_history.append({
'timestamp': get_current_time(self.alpaca_config.timezone),
'is_safe': self._stable_safe_state,
'condition': initial_result.get('class_name', 'Unknown'),
'confidence': initial_result.get('confidence_score', 0.0)
})
logger.info(f"Initial detection complete: {initial_result['class_name']}")
except Exception as e:
logger.error(f"Initial detection failed: {e}")
logger.info(f"Initialized {self.alpaca_config.device_name}")
def _create_thumbnail_from_image(self, img: Image.Image) -> Optional[str]:
"""Create base64-encoded thumbnail from a PIL image"""
try:
# Resize to thumbnail size (200x200) to reduce data size
img_copy = img.copy()
img_copy.thumbnail((200, 200), Image.Resampling.LANCZOS)
# Convert to base64
buffered = io.BytesIO()
img_copy.save(buffered, format="JPEG", quality=85)
img_str = base64.b64encode(buffered.getvalue()).decode()
return img_str
except Exception as e:
logger.warning(f"Failed to create thumbnail: {e}")
return None
def _update_cached_safety(self, detection: Dict[str, Any]):
"""Update cached safety status with debouncing logic (assumes lock is held)"""
# Step A: Determine Instantaneous Safety
class_name = detection.get('class_name', '')
confidence = detection.get('confidence_score', 0.0)
# Get the specific threshold for this class, or use default
threshold = self.alpaca_config.class_thresholds.get(
class_name,
self.alpaca_config.default_threshold
)
# Check if current conditions indicate safe state
is_safe_now = (
confidence >= threshold and
class_name != 'Unknown' and
class_name not in self._unsafe_conditions_set
)
# Step B: Apply Debouncing
if is_safe_now == self._stable_safe_state:
# State matches - reset any pending changes
self._pending_safe_state = None
self._state_change_start_time = None
self._cached_is_safe = self._stable_safe_state # Keep cache in sync
else:
# State differs from stable state
if self._pending_safe_state != is_safe_now:
# New change detected - start debounce timer
self._pending_safe_state = is_safe_now
self._state_change_start_time = get_current_time(self.alpaca_config.timezone)
logger.info(f"State change detected: {'Safe' if is_safe_now else 'Unsafe'} "
f"(pending debounce verification)")
else:
# Change persisting - check if debounce period has elapsed
if self._state_change_start_time:
elapsed_time = (get_current_time(self.alpaca_config.timezone) - self._state_change_start_time).total_seconds()
# Determine required duration based on transition direction
if is_safe_now:
# Transitioning to Safe - use safe debounce time
required_duration = self.alpaca_config.debounce_to_safe_sec
else:
# Transitioning to Unsafe - use unsafe debounce time (usually 0 for immediate)
required_duration = self.alpaca_config.debounce_to_unsafe_sec
if elapsed_time >= required_duration:
# Debounce period complete - commit state change
self._stable_safe_state = is_safe_now
self._cached_is_safe = is_safe_now
self._pending_safe_state = None
self._state_change_start_time = None
# Add to safety history (keep last 100)
self._safety_history.append({
'timestamp': get_current_time(self.alpaca_config.timezone),
'is_safe': is_safe_now,
'condition': class_name,
'confidence': confidence
})
if len(self._safety_history) > 100:
self._safety_history.pop(0)
logger.warning(f"SAFETY STATE CHANGED: {'SAFE' if is_safe_now else 'UNSAFE'} "
f"(class={class_name}, confidence={confidence:.1f}%, "
f"threshold={threshold:.1f}%, debounce={elapsed_time:.1f}s)")
else:
# Still waiting - log progress
remaining = required_duration - elapsed_time
logger.debug(f"Debouncing: {remaining:.1f}s remaining for state change to "
f"{'Safe' if is_safe_now else 'Unsafe'}")
def _setup_mqtt(self):
"""Setup and return MQTT client based on detect_config"""
# Only setup if broker is configured
if not self.detect_config.broker:
logger.warning("MQTT broker not configured, MQTT publishing disabled")
return None
client = mqtt.Client()
if self.detect_config.mqtt_username and self.detect_config.mqtt_password:
client.username_pw_set(self.detect_config.mqtt_username, self.detect_config.mqtt_password)
# Setup Last Will Testament for HA discovery mode
if self.detect_config.mqtt_discovery_mode == 'homeassistant':
availability_topic = f"{self.detect_config.mqtt_discovery_prefix}/sensor/clouddetect_{self.detect_config.device_id}/availability"
client.will_set(availability_topic, "offline", retain=True)
try:
client.connect(self.detect_config.broker, self.detect_config.port)
client.loop_start()
logger.info(f"Connected to MQTT broker at {self.detect_config.broker}:{self.detect_config.port}")
return client
except Exception as e:
logger.error(f"Failed to connect to MQTT broker: {e}")
return None
def get_next_transaction_id(self) -> int:
"""Generate next server transaction ID (thread-safe, wraps at uint32 max)"""
with self.transaction_lock:
self.server_transaction_id = (self.server_transaction_id + 1) % 4294967296
return self.server_transaction_id
def create_response(self, value: Any = None, error_number: int = ERROR_SUCCESS,
error_message: str = "", client_transaction_id: int = 0) -> Dict[str, Any]:
"""Create standard ASCOM Alpaca response"""
response = {
"ClientTransactionID": client_transaction_id,
"ServerTransactionID": self.get_next_transaction_id(),
"ErrorNumber": error_number,
"ErrorMessage": error_message
}
if value is not None or error_number == ERROR_SUCCESS:
response["Value"] = value
return response
def get_client_params(self) -> tuple:
"""Extract client ID and transaction ID from request with validation"""
# Use case-insensitive retrieval
client_id_raw = self._get_arg('ClientID', '0')
client_tx_raw = self._get_arg('ClientTransactionID', '0')
# Strip whitespace and convert to string
client_id_raw = str(client_id_raw).strip()
client_tx_raw = str(client_tx_raw).strip()
# Parse ClientID with fallback to 0
try:
client_id = int(client_id_raw) if client_id_raw else 0
except (ValueError, TypeError):
logger.warning(f"Invalid ClientID received: {client_id_raw}")
client_id = 0
# Parse ClientTransactionID with fallback to 0
try:
client_transaction_id = int(client_tx_raw) if client_tx_raw else 0
# Validate ClientTransactionID is unsigned 32-bit (0 to 4294967295)
# Per ASCOM Alpaca spec, this must be a uint32
if client_transaction_id < 0 or client_transaction_id > 4294967295:
logger.warning(f"ClientTransactionID out of range: {client_transaction_id}")
client_transaction_id = 0
except (ValueError, TypeError):
logger.warning(f"Invalid ClientTransactionID received: {client_tx_raw}")
client_transaction_id = 0
return client_id, client_transaction_id
def _detection_loop(self):
"""Background thread for continuous cloud detection AND MQTT publishing"""
logger.info("Starting unified detection loop (ASCOM + MQTT)")
while not self.stop_detection.is_set():
try:
# Perform detection in background without blocking API responses
# Request the image to be returned so we can create a thumbnail
result = self.cloud_detector.detect(return_image=True)
result['timestamp'] = get_current_time(self.alpaca_config.timezone)
# Create thumbnail from the image that was just used for detection
image_data = None
if 'image' in result:
image_data = self._create_thumbnail_from_image(result['image'])
# Remove image from result before storing (don't need it in detection dict)
del result['image']
# Update ASCOM state
with self.detection_lock:
self.latest_detection = result
self.latest_image_data = image_data
self._update_cached_safety(result)
# Publish to MQTT (unified publishing)
if self.mqtt_client:
try:
# Convert datetime to ISO format for JSON serialization
mqtt_result = result.copy()
if 'timestamp' in mqtt_result and isinstance(mqtt_result['timestamp'], datetime):
mqtt_result['timestamp'] = mqtt_result['timestamp'].isoformat()
if self.detect_config.mqtt_discovery_mode == 'homeassistant':
self.ha_discovery.publish_states(mqtt_result)
else:
# Legacy single-topic publishing
self.mqtt_client.publish(self.detect_config.topic, json.dumps(mqtt_result))
except Exception as e:
logger.error(f"MQTT publish failed: {e}")
logger.info(f"Cloud detection: {result['class_name']} "
f"({result['confidence_score']:.1f}%)")
except Exception as e:
logger.error(f"Error in detection loop: {e}")
# On error, keep previous detection state
# Wait for next update - check stop signal every second
if self.stop_detection.wait(self.alpaca_config.update_interval):
break
logger.info("Detection loop stopped")
@property
def is_connected(self) -> bool:
"""Check if any clients are connected"""
with self.connection_lock:
return len(self.connected_clients) > 0
def connect(self, client_ip: str, client_id: int):
"""Connect a client to the device"""
with self.connection_lock:
# Add or update client session
key = (client_ip, client_id)
self.connected_clients[key] = get_current_time(self.alpaca_config.timezone)
# If this is the first connection, set global connected_at
if len(self.connected_clients) == 1:
self.connected_at = self.connected_clients[key]
self.last_connected_at = self.connected_at
self.disconnected_at = None
logger.info(f"Client connected: {client_ip} (ID: {client_id}). Total clients: {len(self.connected_clients)}")
def disconnect(self, client_ip: str, client_id: int):
"""Disconnect a client from the device"""
with self.connection_lock:
key = (client_ip, client_id)
if key in self.connected_clients:
# Move to disconnected history
conn_time = self.connected_clients[key]
disc_time = get_current_time(self.alpaca_config.timezone)
self.disconnected_clients[key] = (conn_time, disc_time)
del self.connected_clients[key]
logger.info(f"Client disconnected: {client_ip} (ID: {client_id}). Total clients: {len(self.connected_clients)}")
# If no clients left, update global disconnected state
if len(self.connected_clients) == 0:
self.disconnected_at = disc_time
if self.connected_at:
duration = (self.disconnected_at - self.connected_at).total_seconds()
self.last_session_duration = duration
self.connected_at = None
logger.info("All clients disconnected")
else:
logger.warning(f"Attempted to disconnect unknown client: {client_ip} (ID: {client_id})")
def is_safe(self) -> bool:
"""Determine if conditions are safe based on latest detection"""
# Safety Fail-safe: Always return False if not connected
if not self.is_connected:
return False
with self.detection_lock:
return self._stable_safe_state
def get_device_state(self) -> list:
"""Get current operational state"""
# Per ASCOM spec: DeviceState should only include operational properties
# For SafetyMonitor, only IsSafe is operational
is_safe_val = self.is_safe()
return [{"Name": "IsSafe", "Value": is_safe_val}]
def _get_arg(self, key: str, default: Any = None) -> str:
"""Case-insensitive argument retrieval from request values"""
# Search in both query args and form data (combined in request.values)
key_lower = key.lower()
for k, v in request.values.items():
if k.lower() == key_lower:
return v
return default
# Flask application setup
app = Flask(__name__)
CORS(app)
# Global safety monitor instance (will be initialized in main)
safety_monitor: Optional[AlpacaSafetyMonitor] = None
discovery_service: Optional['AlpacaDiscovery'] = None
def validate_device_number(device_number: int) -> Optional[tuple]:
"""Validate device number and return error response if invalid"""
if device_number != safety_monitor.alpaca_config.device_number:
_, client_tx_id = safety_monitor.get_client_params()
return jsonify(safety_monitor.create_response(
error_number=ERROR_INVALID_VALUE,
error_message=f"Invalid device number: {device_number}",
client_transaction_id=client_tx_id
)), 400
return None
def create_simple_get_endpoint(attribute_getter):
"""Factory for simple GET endpoints that return a config value"""
def endpoint(device_number: int):
error_response = validate_device_number(device_number)
if error_response:
return error_response
_, client_tx_id = safety_monitor.get_client_params()
return jsonify(safety_monitor.create_response(
value=attribute_getter(),
client_transaction_id=client_tx_id
))
return endpoint
@app.route('/api/v1/safetymonitor/<int:device_number>/issafe', methods=['GET'])
def get_issafe(device_number: int):
"""Get safety status"""
error_response = validate_device_number(device_number)
if error_response:
return error_response
_, client_tx_id = safety_monitor.get_client_params()
# Per ASCOM spec: Always return a value, never an error
# If disconnected, return False (unsafe) to protect equipment
# is_safe() now handles the connection check internally
is_safe = safety_monitor.is_safe()
return jsonify(safety_monitor.create_response(
value=is_safe,
client_transaction_id=client_tx_id
))
@app.route('/api/v1/safetymonitor/<int:device_number>/connected', methods=['GET'])
def get_connected(device_number: int):
"""Get connection state"""
error_response = validate_device_number(device_number)
if error_response:
return error_response
_, client_tx_id = safety_monitor.get_client_params()
return jsonify(safety_monitor.create_response(
value=safety_monitor.is_connected,
client_transaction_id=client_tx_id
))
@app.route('/api/v1/safetymonitor/<int:device_number>/connected', methods=['PUT'])
def set_connected(device_number: int):
"""Set connection state"""
error_response = validate_device_number(device_number)
if error_response:
return error_response
client_id, client_tx_id = safety_monitor.get_client_params()
connected_str = safety_monitor._get_arg('Connected', '').strip().lower()
if connected_str == 'true':
target_state = True
elif connected_str == 'false':
target_state = False
else:
return jsonify(safety_monitor.create_response(
error_number=ERROR_INVALID_VALUE,
error_message=f"Invalid boolean value for Connected: '{connected_str}'",
client_transaction_id=client_tx_id
)), 400
try:
client_ip = request.remote_addr
if target_state:
safety_monitor.connect(client_ip=client_ip, client_id=client_id)
else:
safety_monitor.disconnect(client_ip=client_ip, client_id=client_id)
return jsonify(safety_monitor.create_response(
client_transaction_id=client_tx_id
))
except Exception as e:
logger.error(f"Failed to set connected state: {e}")
return jsonify(safety_monitor.create_response(
error_number=ERROR_UNSPECIFIED,
error_message=str(e),
client_transaction_id=client_tx_id
)), 500
@app.route('/api/v1/safetymonitor/<int:device_number>/connecting', methods=['GET'])
def get_connecting(device_number: int):
"""Get connecting state (Platform 7)"""
error_response = validate_device_number(device_number)
if error_response:
return error_response
_, client_tx_id = safety_monitor.get_client_params()
return jsonify(safety_monitor.create_response(
value=safety_monitor.connecting,
client_transaction_id=client_tx_id
))
@app.route('/api/v1/safetymonitor/<int:device_number>/connect', methods=['PUT'])
def connect_device(device_number: int):
"""Connect to device asynchronously (Platform 7, Interface V3+)"""
error_response = validate_device_number(device_number)
if error_response:
return error_response
client_id, client_tx_id = safety_monitor.get_client_params()
try:
client_ip = request.remote_addr
safety_monitor.connect(client_ip=client_ip, client_id=client_id)
return jsonify(safety_monitor.create_response(client_transaction_id=client_tx_id))
except Exception as e:
logger.error(f"Failed to connect: {e}")
return jsonify(safety_monitor.create_response(
error_number=ERROR_UNSPECIFIED,
error_message=str(e),
client_transaction_id=client_tx_id
)), 500
@app.route('/api/v1/safetymonitor/<int:device_number>/disconnect', methods=['PUT'])
def disconnect_device(device_number: int):
"""Disconnect from device asynchronously (Platform 7, Interface V3+)"""
error_response = validate_device_number(device_number)
if error_response:
return error_response
client_id, client_tx_id = safety_monitor.get_client_params()
try:
client_ip = request.remote_addr
safety_monitor.disconnect(client_ip=client_ip, client_id=client_id)
return jsonify(safety_monitor.create_response(client_transaction_id=client_tx_id))
except Exception as e:
logger.error(f"Error during disconnect: {e}")
return jsonify(safety_monitor.create_response(
error_number=ERROR_UNSPECIFIED,
error_message=str(e),
client_transaction_id=client_tx_id
)), 500
@app.route('/api/v1/safetymonitor/<int:device_number>/description', methods=['GET'])
def get_description(device_number: int):
return create_simple_get_endpoint(lambda: safety_monitor.alpaca_config.device_description)(device_number)
@app.route('/api/v1/safetymonitor/<int:device_number>/devicestate', methods=['GET'])
def get_devicestate(device_number: int):
return create_simple_get_endpoint(safety_monitor.get_device_state)(device_number)
@app.route('/api/v1/safetymonitor/<int:device_number>/driverinfo', methods=['GET'])
def get_driverinfo(device_number: int):
return create_simple_get_endpoint(lambda: safety_monitor.alpaca_config.driver_info)(device_number)
@app.route('/api/v1/safetymonitor/<int:device_number>/driverversion', methods=['GET'])
def get_driverversion(device_number: int):
return create_simple_get_endpoint(lambda: safety_monitor.alpaca_config.driver_version)(device_number)
@app.route('/api/v1/safetymonitor/<int:device_number>/interfaceversion', methods=['GET'])
def get_interfaceversion(device_number: int):
return create_simple_get_endpoint(lambda: safety_monitor.alpaca_config.interface_version)(device_number)
@app.route('/api/v1/safetymonitor/<int:device_number>/name', methods=['GET'])
def get_name(device_number: int):
return create_simple_get_endpoint(lambda: safety_monitor.alpaca_config.device_name)(device_number)
@app.route('/api/v1/safetymonitor/<int:device_number>/supportedactions', methods=['GET'])
def get_supportedactions(device_number: int):
return create_simple_get_endpoint(lambda: [])(device_number)
@app.route('/api/v1/safetymonitor/<int:device_number>/action', methods=['PUT'])
def put_action(device_number: int):
"""Execute custom action (not implemented)"""
error_response = validate_device_number(device_number)
if error_response:
return error_response
_, client_tx_id = safety_monitor.get_client_params()
return jsonify(safety_monitor.create_response(
error_number=ERROR_NOT_IMPLEMENTED,
error_message="No custom actions are supported",
client_transaction_id=client_tx_id
)), 200
@app.route('/api/v1/safetymonitor/<int:device_number>/commandblind', methods=['PUT'])
@app.route('/api/v1/safetymonitor/<int:device_number>/commandbool', methods=['PUT'])
@app.route('/api/v1/safetymonitor/<int:device_number>/commandstring', methods=['PUT'])
def deprecated_commands(device_number: int):
"""Deprecated command methods"""
_, client_tx_id = safety_monitor.get_client_params()
return jsonify(safety_monitor.create_response(
error_number=ERROR_NOT_IMPLEMENTED,
error_message="This method is deprecated",
client_transaction_id=client_tx_id
)), 200
@app.route('/management/apiversions', methods=['GET'])
def get_apiversions():
"""Get supported API versions"""
return jsonify({
"Value": [1],
"ClientTransactionID": 0,
"ServerTransactionID": safety_monitor.get_next_transaction_id(),
"ErrorNumber": 0,
"ErrorMessage": ""
})
@app.route('/management/v1/description', methods=['GET'])
def get_management_description():
"""Get server description"""
value = {
"ServerName": safety_monitor.alpaca_config.device_name,
"Manufacturer": "chvvkumar",
"ManufacturerVersion": safety_monitor.alpaca_config.driver_version,
"Location": safety_monitor.alpaca_config.location
}
# MUST wrap in create_response
return jsonify(safety_monitor.create_response(value=value))
@app.route('/management/v1/configureddevices', methods=['GET'])
def get_configured_devices():
"""Get list of configured devices"""
value = [{
"DeviceName": safety_monitor.alpaca_config.device_name,
"DeviceType": "SafetyMonitor",
"DeviceNumber": safety_monitor.alpaca_config.device_number,
"UniqueID": "cloud-safety-monitor-0"
}]
# MUST wrap in create_response
return jsonify(safety_monitor.create_response(value=value))
@app.route('/api/v1/latest_image', methods=['GET'])
def get_latest_image():
"""Serve the latest detection image as JPEG"""
with safety_monitor.detection_lock:
image_data = safety_monitor.latest_image_data
if image_data:
try:
# Decode base64 and return as image
img_bytes = base64.b64decode(image_data)
return Response(img_bytes, mimetype='image/jpeg')
except Exception as e:
logger.error(f"Failed to serve image: {e}")
return Response(status=404)
else:
return Response(status=404)
def get_available_cloud_conditions() -> list:
"""Load cloud conditions from labels file"""
try:
label_path = os.getenv('LABEL_PATH', 'labels.txt')
with open(label_path, 'r') as f:
# Parse labels like "0 Clear" and extract just the class name
return [line.strip().split(' ', 1)[1] for line in f.readlines()]
except Exception as e:
logger.error(f"Failed to load labels: {e}")
# Fallback to hardcoded list
return ['Clear', 'Mostly Cloudy', 'Overcast', 'Rain', 'Snow', 'Wisps of clouds']
def sync_class_thresholds_with_labels():
"""Synchronize class_thresholds with available labels, adding defaults for new labels"""
if safety_monitor:
all_conditions = get_available_cloud_conditions()
current_thresholds = safety_monitor.alpaca_config.class_thresholds
# Check if any new labels were added that don't have thresholds
for condition in all_conditions:
if condition not in current_thresholds:
# Initialize new conditions with default threshold
current_thresholds[condition] = safety_monitor.alpaca_config.default_threshold
logger.info(f"Initialized threshold for new condition '{condition}': {safety_monitor.alpaca_config.default_threshold}%")
# Optionally remove thresholds for conditions no longer in labels
removed_conditions = [cond for cond in current_thresholds if cond not in all_conditions]
for condition in removed_conditions:
del current_thresholds[condition]
logger.info(f"Removed threshold for obsolete condition '{condition}'")
if removed_conditions:
# Save if we made changes
safety_monitor.alpaca_config.save_to_file()
@app.route('/setup/v1/safetymonitor/<int:device_number>/setup', methods=['GET', 'POST'])
def setup_device(device_number: int):
"""Setup page for configuring device name and location"""
if device_number != safety_monitor.alpaca_config.device_number:
return jsonify({"error": "Invalid device number"}), 404
# Synchronize thresholds with available labels (handles new labels in labels.txt)
sync_class_thresholds_with_labels()
# Get available conditions from labels.txt - used by both GET and POST
all_available_conditions = get_available_cloud_conditions()
if request.method == 'POST':
# Handle form submission
device_name = request.form.get('device_name', '').strip()
location = request.form.get('location', '').strip()
image_url = request.form.get('image_url', '').strip()
if device_name:
safety_monitor.alpaca_config.device_name = device_name
logger.info(f"Device name updated to: {device_name}")
if location:
safety_monitor.alpaca_config.location = location
logger.info(f"Location updated to: {location}")
if image_url:
safety_monitor.alpaca_config.image_url = image_url
# Update the detect_config as well
safety_monitor.detect_config.image_url = image_url
logger.info(f"Image URL updated to: {image_url}")
elif image_url == '' and 'image_url' in request.form:
# User explicitly cleared the field - use environment default
default_url = os.environ.get('IMAGE_URL', '')
safety_monitor.alpaca_config.image_url = default_url
safety_monitor.detect_config.image_url = default_url
logger.info(f"Image URL reset to environment default: {default_url}")
# Handle NTP and timezone settings
ntp_server = request.form.get('ntp_server', '').strip()
if ntp_server:
safety_monitor.alpaca_config.ntp_server = ntp_server
logger.info(f"NTP server updated to: {ntp_server}")
timezone = request.form.get('timezone', '').strip()
if timezone:
safety_monitor.alpaca_config.timezone = timezone
logger.info(f"Timezone updated to: {timezone}")
# Handle timing configuration with safety validations
try:
detection_interval = request.form.get('detection_interval', '').strip()
if detection_interval:
val = int(detection_interval)
if 5 <= val <= 300:
safety_monitor.alpaca_config.detection_interval = val
# Update the detect_config as well
safety_monitor.detect_config.detect_interval = val
logger.info(f"Detection interval updated to: {val}s")
else:
logger.warning(f"Detection interval {val}s out of range (5-300s)")
except ValueError:
logger.warning(f"Invalid detection_interval value: {detection_interval}")
try:
update_interval = request.form.get('update_interval', '').strip()
if update_interval:
val = int(update_interval)
if 5 <= val <= 300:
safety_monitor.alpaca_config.update_interval = val
logger.info(f"ASCOM update interval updated to: {val}s")
else:
logger.warning(f"Update interval {val}s out of range (5-300s)")
except ValueError:
logger.warning(f"Invalid update_interval value: {update_interval}")
# Handle debounce timers with safety validations
try:
debounce_safe = request.form.get('debounce_safe', '').strip()
if debounce_safe:
val = int(debounce_safe)
# Validation: Safe debounce should be >= detection_interval for smooth operation
if val > 0 and val < safety_monitor.alpaca_config.detection_interval:
logger.warning(f"Safe wait time {val}s < detection interval {safety_monitor.alpaca_config.detection_interval}s - may cause erratic behavior")
safety_monitor.alpaca_config.debounce_to_safe_sec = val
logger.info(f"Debounce to safe updated to: {val}s")
except ValueError:
logger.warning(f"Invalid debounce_safe value: {debounce_safe}")
try:
debounce_unsafe = request.form.get('debounce_unsafe', '').strip()
if debounce_unsafe:
val = int(debounce_unsafe)
# Safety validation: Warn if unsafe debounce > 30s (delays emergency response)
if val > 30:
logger.warning(f"Unsafe wait time {val}s > 30s - delays emergency response to dangerous conditions")
safety_monitor.alpaca_config.debounce_to_unsafe_sec = val
logger.info(f"Debounce to unsafe updated to: {val}s")
except ValueError:
logger.warning(f"Invalid debounce_unsafe value: {debounce_unsafe}")
# Handle unsafe conditions from radio buttons
unsafe_conditions = []
for condition in all_available_conditions:
safety_choice = request.form.get(f'safety_{condition}')
if safety_choice == 'unsafe':
unsafe_conditions.append(condition)
safety_monitor.alpaca_config.unsafe_conditions = unsafe_conditions
# Update the in-memory set to match the new configuration
safety_monitor._unsafe_conditions_set = set(unsafe_conditions)
# Handle class-specific thresholds
class_thresholds = {}
for condition in all_available_conditions:
threshold_value = request.form.get(f'threshold_{condition}', '').strip()
if threshold_value:
try:
threshold = float(threshold_value)
if 0 <= threshold <= 100:
class_thresholds[condition] = threshold
else:
logger.warning(f"Threshold for {condition} out of range: {threshold}")
except ValueError:
logger.warning(f"Invalid threshold for {condition}: {threshold_value}")
safety_monitor.alpaca_config.class_thresholds = class_thresholds
logger.info(f"Class thresholds updated: {class_thresholds}")
# Recalculate cached safety status with new configuration
with safety_monitor.detection_lock:
# Reset debounce state when configuration changes
safety_monitor._pending_safe_state = None
safety_monitor._state_change_start_time = None
safety_monitor._update_cached_safety(safety_monitor.latest_detection)
logger.info(f"Unsafe conditions updated to: {unsafe_conditions}")
# Save configuration to file
safety_monitor.alpaca_config.save_to_file()
# Trigger immediate detection with new settings
logger.info("Triggering immediate detection after config save")
try:
result = safety_monitor.cloud_detector.detect(return_image=True)
result['timestamp'] = get_current_time(safety_monitor.alpaca_config.timezone)
# Create thumbnail from the image that was just used for detection
image_data = None
if 'image' in result:
image_data = safety_monitor._create_thumbnail_from_image(result['image'])
del result['image']
with safety_monitor.detection_lock:
safety_monitor.latest_detection = result
safety_monitor.latest_image_data = image_data
safety_monitor._update_cached_safety(result)
logger.info(f"Immediate detection after config save: {result['class_name']} ({result['confidence_score']:.1f}%)")
except Exception as e:
logger.error(f"Immediate detection after config save failed: {e}")
# Redirect to prevent form resubmission (Post/Redirect/Get pattern)
return redirect(url_for('setup_device', device_number=device_number))
# GET request - show the form
message = ""
# HTML form for setup
html_template = """
<!DOCTYPE html>
<html>