-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflask_app.py
More file actions
2957 lines (2436 loc) · 116 KB
/
flask_app.py
File metadata and controls
2957 lines (2436 loc) · 116 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
# app.py
from flask import Flask, render_template, send_from_directory, jsonify, request, redirect, url_for, Response
import os
import glob
import re
import json
import subprocess
from datetime import datetime, timedelta
import threading
import time
import shutil
import psutil
import platform
import socket
# Import requests for weather API - make it optional in case it's not installed
try:
import requests
REQUESTS_AVAILABLE = True
except ImportError:
REQUESTS_AVAILABLE = False
print("Warning: 'requests' module not found. Weather data will not be available.")
print("Install with: pip install requests")
app = Flask(__name__)
# Configure this to match your output directory
# Note: These paths will be automatically updated by install.sh during installation
IMAGE_DIR = os.path.expanduser("~/allsky_images")
SCRIPT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "image_capture.py")
CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app_config.json") # Configuration file for persistent settings
# Global variables to track capture process
capture_interval = 300 # Default 5 minutes
is_capturing = False
capture_log = []
capture_thread = None
stop_capture_flag = False
last_capture_time = None
background_capture_enabled = False # Track if background capture should be running
# ==================== STAY-ALIVE CONSTANTS ====================
STAY_ALIVE_PING_HOST = "8.8.8.8" # Google DNS - reliable host to ping
STAY_ALIVE_PING_PORT = 53 # DNS port
STAY_ALIVE_CHECK_INTERVAL_SECONDS = 600 # Check connectivity every 60 seconds
STAY_ALIVE_MAX_REBOOT_ATTEMPTS = 5 # Max reboot attempts per tracking period
STAY_ALIVE_TRACKING_PERIOD_SECONDS = 3600 # 1 hour tracking period
STAY_ALIVE_CONNECTION_TIMEOUT_SECONDS = 10 # Timeout for connection test
STAY_ALIVE_RETRY_DELAY_SECONDS = 30 # Delay between reconnection attempts before reboot
STAY_ALIVE_MAX_RECONNECT_ATTEMPTS = 3 # Number of reconnection attempts before reboot
# Global variables for stay-alive feature
stay_alive_thread = None
stay_alive_stop_flag = False
stay_alive_log = []
stay_alive_reboot_attempts = [] # List of timestamps of reboot attempts
stay_alive_last_successful_ping = None
stay_alive_enabled = True # Enable stay-alive by default
stay_alive_sudo_available = None # None = not checked, True/False = cached result
stay_alive_sudo_password = None # Cached sudo password from config
stay_alive_sudo_warning_logged = False # Only log sudo warning once
# Global settings storage
app_settings = {
"latitude": None,
"longitude": None,
"timezone": None,
"dst_enabled": False,
"openweather_api_key": None,
"min_exposure_ms": 0.034,
"max_exposure_ms": 30000,
"capture_daytime": False,
"capture_civil_twilight": False,
"capture_nautical_twilight": False,
"capture_astronomical_darkness": True,
"ftp_protocol": "ftp", # "ftp" or "sftp"
"ftp_server": None,
"ftp_port": 21,
"ftp_username": None,
"ftp_password": None,
"ftp_remote_path": None,
"compass_rotation": 0,
"compass_enabled": True,
"starmap_enabled": False,
"starmap_magnitude_limit": 4.0,
"starmap_show_names": True,
"starmap_show_constellations": True,
"starmap_opacity": 0.8,
"starmap_color": "#FFD700",
"starmap_rotation_adjust": 0,
"starmap_offset_x": 0,
"starmap_offset_y": 0,
"starmap_scale_x": 1.0,
"starmap_scale_y": 1.0
}
# NOTE: Configuration loading moved to after function definitions to avoid import errors
def load_config():
"""Load configuration from JSON file"""
global app_settings, capture_interval, IMAGE_DIR, SCRIPT_PATH, background_capture_enabled
try:
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as f:
config = json.load(f)
# Load settings
if 'settings' in config:
app_settings.update(config['settings'])
# Load capture interval
if 'capture_interval' in config:
capture_interval = config['capture_interval']
# Load background capture status
if 'background_capture_enabled' in config:
background_capture_enabled = config['background_capture_enabled']
# Load exposure limits (with fallback to top-level config for backward compatibility)
if 'min_exposure_ms' in config:
app_settings['min_exposure_ms'] = config['min_exposure_ms']
if 'max_exposure_ms' in config:
app_settings['max_exposure_ms'] = config['max_exposure_ms']
# Load paths (optional, can be overridden) - only if non-empty
if config.get('image_dir'):
IMAGE_DIR = config['image_dir']
if config.get('script_path'):
SCRIPT_PATH = config['script_path']
print(f"Configuration loaded from {CONFIG_FILE}")
print(f"Settings: lat={app_settings.get('latitude')}, lon={app_settings.get('longitude')}, api_key={'set' if app_settings.get('openweather_api_key') else 'not set'}")
print(f"Exposure limits: min={app_settings.get('min_exposure_ms')}ms, max={app_settings.get('max_exposure_ms')}ms")
return True
else:
print(f"Configuration file not found: {CONFIG_FILE}")
print("Using default settings")
except Exception as e:
print(f"Error loading configuration: {str(e)}")
import traceback
traceback.print_exc()
return False
def save_config():
"""Save configuration to JSON file"""
global app_settings, capture_interval, IMAGE_DIR, SCRIPT_PATH, background_capture_enabled
try:
config = {
"settings": app_settings,
"capture_interval": capture_interval,
"background_capture_enabled": background_capture_enabled,
"image_dir": IMAGE_DIR,
"script_path": SCRIPT_PATH,
"min_exposure_ms": app_settings.get("min_exposure_ms", 0.034),
"max_exposure_ms": app_settings.get("max_exposure_ms", 30000),
"last_updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
print(f"Attempting to save config to: {CONFIG_FILE}")
print(f"File exists before save: {os.path.exists(CONFIG_FILE)}")
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=4)
f.flush()
os.fsync(f.fileno())
print(f"Configuration saved to {CONFIG_FILE}")
print(f"File exists after save: {os.path.exists(CONFIG_FILE)}")
print(f"Settings: lat={app_settings.get('latitude')}, lon={app_settings.get('longitude')}, api_key={'set' if app_settings.get('openweather_api_key') else 'not set'}")
print(f"Exposure limits: min={app_settings.get('min_exposure_ms')}ms, max={app_settings.get('max_exposure_ms')}ms")
print(f"Compass: enabled={app_settings.get('compass_enabled')}, rotation={app_settings.get('compass_rotation')}")
return True
except Exception as e:
print(f"Error saving configuration to {CONFIG_FILE}: {str(e)}")
import traceback
traceback.print_exc()
return False
def extract_metadata_from_filename(filename):
"""Extract metadata from the ZWO image filename"""
metadata = {
"timestamp": None,
"exposure_ms": None,
"datetime_obj": None
}
# Extract timestamp (format: YYYYMMDD_HHMMSS_expXXXms.png)
timestamp_match = re.search(r'(\d{8}_\d{6})', filename)
if timestamp_match:
timestamp_str = timestamp_match.group(1)
try:
dt = datetime.strptime(timestamp_str, "%Y%m%d_%H%M%S")
metadata["timestamp"] = dt.strftime("%Y-%m-%d %H:%M:%S")
metadata["datetime_obj"] = dt
except ValueError:
pass
# Extract exposure time (handle both milliseconds and microseconds)
exposure_match = re.search(r'exp(\d+)ms', filename)
if exposure_match:
metadata["exposure_ms"] = int(exposure_match.group(1))
else:
# Try microseconds format
exposure_match = re.search(r'exp(\d+)us', filename)
if exposure_match:
# Convert microseconds to milliseconds (as float to preserve precision)
metadata["exposure_ms"] = float(int(exposure_match.group(1))) / 1000.0
return metadata
def get_night_session_for_image(image_datetime):
"""
Determine which night session an image belongs to.
A night session runs from noon of one day to noon of the next day.
Images taken before noon belong to the previous night, images after noon belong to that night.
Returns a tuple: (session_start_date, session_end_date, display_label)
"""
if image_datetime is None:
return None, None, "Unknown Date"
# If the image was taken before noon (12:00), it belongs to the previous night
# If taken after noon, it belongs to tonight
if image_datetime.hour < 12:
# Before noon - this is the end of the previous night
night_start = (image_datetime - timedelta(days=1)).date()
night_end = image_datetime.date()
else:
# After noon - this is the start of tonight
night_start = image_datetime.date()
night_end = (image_datetime + timedelta(days=1)).date()
# Format: "Night of 2024-11-13 to 2024-11-14"
display_label = f"Night of {night_start.strftime('%Y-%m-%d')} to {night_end.strftime('%Y-%m-%d')}"
return night_start, night_end, display_label
def get_all_images():
"""Get all ZWO images with metadata, sorted by date (newest first)"""
# Match files with pattern: YYYYMMDD_HHMMSS_expXXXms.png or YYYYMMDD_HHMMSS_expXXXus.png
image_files = []
image_files.extend(glob.glob(os.path.join(IMAGE_DIR, "*_exp*ms.png")))
image_files.extend(glob.glob(os.path.join(IMAGE_DIR, "*_exp*us.png")))
images = []
for img_path in image_files:
filename = os.path.basename(img_path)
metadata = extract_metadata_from_filename(filename)
# Get file stats
stats = os.stat(img_path)
file_size = stats.st_size / (1024 * 1024) # Convert to MB
# Calculate night session
night_start, night_end, night_label = get_night_session_for_image(metadata["datetime_obj"])
images.append({
"filename": filename,
"path": img_path,
"timestamp": metadata["timestamp"],
"exposure_ms": metadata["exposure_ms"],
"size_mb": round(file_size, 2),
"modified": datetime.fromtimestamp(stats.st_mtime),
"night_session_start": night_start,
"night_session_end": night_end,
"night_session_label": night_label
})
# Sort by modification time (newest first)
images.sort(key=lambda x: x["modified"], reverse=True)
return images
def run_single_capture(exposure_ms=None):
"""Run a single image capture"""
global capture_log, last_capture_time
try:
cmd = ["python3", SCRIPT_PATH]
if exposure_ms is not None:
cmd.extend(["--exposure", str(exposure_ms)])
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] Starting capture...")
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1
)
# Read output line by line
for line in process.stdout:
line = line.strip()
if line:
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] {line}")
# Keep only last 100 log lines
if len(capture_log) > 100:
capture_log.pop(0)
process.wait()
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] Capture completed (exit code: {process.returncode})")
last_capture_time = time.time()
return process.returncode == 0
except Exception as e:
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] Error: {str(e)}")
return False
def get_current_twilight_period():
"""
Determine what twilight period we're currently in based on location and time.
Returns: ('daytime', 'civil_twilight', 'nautical_twilight', 'astronomical_darkness', or 'unknown')
"""
global app_settings
# Need location to calculate
if app_settings['latitude'] is None or app_settings['longitude'] is None:
return 'unknown'
try:
import math
now = datetime.now()
lat = app_settings['latitude']
lon = app_settings['longitude']
# Calculate solar times using the same function from api_solar_info
def calculate_solar_noon(lon):
return 12.0 - (lon / 15.0)
def calculate_sunrise_sunset(lat, lon, date):
day_of_year = date.timetuple().tm_yday
declination = 23.45 * math.sin(math.radians((360/365) * (day_of_year - 81)))
lat_rad = math.radians(lat)
dec_rad = math.radians(declination)
cos_hour_angle = -math.tan(lat_rad) * math.tan(dec_rad)
if cos_hour_angle > 1:
return None, None
elif cos_hour_angle < -1:
return "00:00", "23:59"
hour_angle = math.degrees(math.acos(cos_hour_angle))
solar_noon = calculate_solar_noon(lon)
sunrise_hour = solar_noon - (hour_angle / 15.0)
sunset_hour = solar_noon + (hour_angle / 15.0)
tz_offset = app_settings.get('timezone', 0) or 0
if app_settings.get('dst_enabled'):
tz_offset += 1
sunrise_hour += tz_offset
sunset_hour += tz_offset
return sunrise_hour, sunset_hour
sunrise_hour, sunset_hour = calculate_sunrise_sunset(lat, lon, now)
if sunrise_hour is None or sunset_hour is None:
return 'unknown'
# Calculate twilight times
civil_twilight_end = (sunset_hour + 0.5) % 24 # ~30 min after sunset
nautical_twilight_end = (sunset_hour + 1.0) % 24 # ~1 hour after sunset
astronomical_twilight_end = (sunset_hour + 1.5) % 24 # ~1.5 hours after sunset
astronomical_twilight_begin = (sunrise_hour - 1.5) % 24 # ~1.5 hours before sunrise
nautical_twilight_begin = (sunrise_hour - 1.0) % 24 # ~1 hour before sunrise
civil_twilight_begin = (sunrise_hour - 0.5) % 24 # ~30 min before sunrise
# Current time in hours
current_hour = now.hour + now.minute / 60
# Determine period (checking from darkest to lightest)
# Handle cases that may cross midnight
# Check if we're in astronomical darkness
if astronomical_twilight_end < astronomical_twilight_begin:
# Crosses midnight
if current_hour >= astronomical_twilight_end or current_hour < astronomical_twilight_begin:
return 'astronomical_darkness'
else:
if astronomical_twilight_end <= current_hour < astronomical_twilight_begin:
return 'astronomical_darkness'
# Check if we're in nautical twilight (between civil and astronomical twilight)
if (civil_twilight_end <= current_hour < nautical_twilight_end or
nautical_twilight_begin <= current_hour < civil_twilight_begin):
return 'nautical_twilight'
# Check if we're in civil twilight (just after sunset or just before sunrise)
if (sunset_hour <= current_hour < civil_twilight_end or
civil_twilight_begin <= current_hour < sunrise_hour):
return 'civil_twilight'
# Check if we're in daytime (between sunrise and sunset)
if sunrise_hour <= current_hour < sunset_hour:
return 'daytime'
# If we reach here, we're in astronomical darkness (fallback for edge cases)
return 'astronomical_darkness'
except Exception as e:
print(f"Error calculating twilight period: {e}")
return 'unknown'
def should_capture_be_active():
"""
Check if background capture should be active based on current twilight period and settings.
Returns: (should_be_active: bool, reason: str)
"""
global app_settings
current_period = get_current_twilight_period()
if current_period == 'unknown':
# If we can't determine, default to allowing capture
return True, "Unable to determine twilight period, allowing capture"
# Check each period
if current_period == 'astronomical_darkness' and app_settings.get('capture_astronomical_darkness', True):
return True, "Astronomical darkness - capture enabled"
if current_period == 'nautical_twilight' and app_settings.get('capture_nautical_twilight', False):
return True, "Nautical twilight - capture enabled"
if current_period == 'civil_twilight' and app_settings.get('capture_civil_twilight', False):
return True, "Civil twilight - capture enabled"
if current_period == 'daytime' and app_settings.get('capture_daytime', False):
return True, "Daytime - capture enabled"
return False, f"Current period ({current_period}) - capture disabled by settings"
def background_capture_loop():
"""Background thread that captures images at regular intervals"""
global is_capturing, stop_capture_flag, capture_log, last_capture_time, background_capture_enabled
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] Background capture started (interval: {capture_interval}s)")
try:
while not stop_capture_flag:
# Check if we should capture based on twilight period settings
should_capture, reason = should_capture_be_active()
if should_capture:
is_capturing = True
# Run capture
success = run_single_capture()
is_capturing = False
if success:
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] Waiting {capture_interval} seconds until next capture...")
else:
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] Capture failed, will retry in {capture_interval} seconds...")
else:
# Not in capture window
is_capturing = False
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] {reason}")
# Wait for the interval (check stop flag every second)
for _ in range(capture_interval):
if stop_capture_flag:
break
time.sleep(1)
except Exception as e:
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] Background capture error: {str(e)}")
# Don't change the flag - let the user control the intent via Start/Stop buttons
# The flag represents USER INTENT, not thread state
# (Removed auto-correction that was causing flicker)
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] Background capture stopped")
def start_background_capture():
"""Start the background capture thread"""
global capture_thread, stop_capture_flag, background_capture_enabled
if capture_thread and capture_thread.is_alive():
return False, "Background capture already running"
stop_capture_flag = False
background_capture_enabled = True
capture_thread = threading.Thread(target=background_capture_loop, daemon=True)
capture_thread.start()
# Save the status to config
save_config()
return True, "Background capture started"
def stop_background_capture():
"""Stop the background capture thread"""
global stop_capture_flag, capture_thread, background_capture_enabled
if not capture_thread or not capture_thread.is_alive():
# Even if not running, update the flag and save
background_capture_enabled = False
save_config()
return False, "Background capture not running"
stop_capture_flag = True
background_capture_enabled = False
capture_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] Stopping background capture...")
# Wait for thread to finish (with timeout)
capture_thread.join(timeout=5)
# Save the status to config
save_config()
return True, "Background capture stopped"
# ==================== STAY-ALIVE FUNCTIONS ====================
def stay_alive_log_message(message):
"""Add a timestamped message to the stay-alive log"""
global stay_alive_log
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_entry = f"[{timestamp}] {message}"
stay_alive_log.append(log_entry)
# Keep only the last 100 log entries
if len(stay_alive_log) > 100:
stay_alive_log = stay_alive_log[-100:]
print(f"STAY-ALIVE: {message}")
def load_sudo_password():
"""Load sudo password from config file if available."""
global stay_alive_sudo_password
if stay_alive_sudo_password is not None:
return stay_alive_sudo_password
try:
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app_config.json")
if os.path.exists(config_path):
with open(config_path, 'r') as f:
config = json.load(f)
password = config.get('settings', {}).get('sudo_password', '')
if password:
stay_alive_sudo_password = password
return password
except Exception as e:
stay_alive_log_message(f"Could not load sudo password from config: {e}")
stay_alive_sudo_password = "" # Empty string means no password configured
return ""
def check_sudo_available():
"""
Check if sudo commands can be run (either passwordless or with configured password).
Caches the result to avoid repeated checks and log spam.
Returns True if sudo is available, False otherwise.
"""
global stay_alive_sudo_available, stay_alive_sudo_warning_logged
# Return cached result if already checked
if stay_alive_sudo_available is not None:
return stay_alive_sudo_available
# Only check on Linux
if platform.system() != "Linux":
stay_alive_sudo_available = False
return False
# First, check if passwordless sudo works
try:
result = subprocess.run(
["sudo", "-n", "true"],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
stay_alive_sudo_available = True
stay_alive_log_message("Passwordless sudo available for network commands")
return True
except (subprocess.TimeoutExpired, Exception):
pass
# Passwordless didn't work, check if we have a configured password
password = load_sudo_password()
if password:
try:
# Test sudo with password using -S flag (read from stdin)
result = subprocess.run(
["sudo", "-S", "true"],
input=password + "\n",
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
stay_alive_sudo_available = True
stay_alive_log_message("Sudo available with configured password")
return True
else:
stay_alive_log_message("WARNING: Configured sudo password is incorrect")
stay_alive_sudo_warning_logged = True
except subprocess.TimeoutExpired:
stay_alive_log_message("WARNING: Sudo password test timed out")
except Exception as e:
stay_alive_log_message(f"WARNING: Sudo password test failed: {e}")
# Neither method worked
if not stay_alive_sudo_warning_logged:
stay_alive_log_message("WARNING: Sudo not available")
stay_alive_log_message("Network commands will be skipped")
stay_alive_log_message("To enable, either:")
stay_alive_log_message(" 1. Set sudo_password in settings, OR")
stay_alive_log_message(" 2. Configure passwordless sudo in /etc/sudoers.d/allsky")
stay_alive_sudo_warning_logged = True
stay_alive_sudo_available = False
return False
def run_sudo_command(cmd_args, description="", timeout=30):
"""
Run a command with sudo, using password from config if needed.
Returns (success, stdout, stderr) tuple.
"""
if platform.system() != "Linux":
return False, "", "Not Linux"
if not check_sudo_available():
return False, "", "Sudo not available"
password = load_sudo_password()
try:
if password:
# Use -S flag to read password from stdin
full_cmd = ["sudo", "-S"] + cmd_args
result = subprocess.run(
full_cmd,
input=password + "\n",
capture_output=True,
text=True,
timeout=timeout
)
else:
# Use -n flag for passwordless sudo
full_cmd = ["sudo", "-n"] + cmd_args
result = subprocess.run(
full_cmd,
capture_output=True,
text=True,
timeout=timeout
)
success = result.returncode == 0
# Filter out password prompt from stderr if present
stderr = result.stderr
if stderr:
stderr = '\n'.join(
line for line in stderr.split('\n')
if '[sudo]' not in line and 'password' not in line.lower()
)
return success, result.stdout, stderr
except subprocess.TimeoutExpired:
return False, "", "Command timed out"
except Exception as e:
return False, "", str(e)
def check_network_connectivity():
"""
Check if network connectivity is available by attempting to connect to a known host.
Returns True if connected, False otherwise.
"""
global stay_alive_last_successful_ping
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(STAY_ALIVE_CONNECTION_TIMEOUT_SECONDS)
result = sock.connect_ex((STAY_ALIVE_PING_HOST, STAY_ALIVE_PING_PORT))
sock.close()
if result == 0:
stay_alive_last_successful_ping = datetime.now()
return True
return False
except socket.error as e:
stay_alive_log_message(f"Socket error during connectivity check: {str(e)}")
return False
except Exception as e:
stay_alive_log_message(f"Unexpected error during connectivity check: {str(e)}")
return False
def get_reboot_attempts_in_tracking_period():
"""
Get the number of reboot attempts within the current tracking period.
Also cleans up old entries outside the tracking period.
"""
global stay_alive_reboot_attempts
current_time = datetime.now()
cutoff_time = current_time - timedelta(seconds=STAY_ALIVE_TRACKING_PERIOD_SECONDS)
# Filter out old attempts and keep only those within the tracking period
stay_alive_reboot_attempts = [
timestamp for timestamp in stay_alive_reboot_attempts
if timestamp > cutoff_time
]
return len(stay_alive_reboot_attempts)
def record_reboot_attempt():
"""Record a reboot attempt with the current timestamp"""
global stay_alive_reboot_attempts
stay_alive_reboot_attempts.append(datetime.now())
def get_time_until_next_tracking_period():
"""
Calculate how long until the next tracking period starts.
Returns seconds until the oldest attempt expires from the tracking window.
"""
global stay_alive_reboot_attempts
if not stay_alive_reboot_attempts:
return 0
oldest_attempt = min(stay_alive_reboot_attempts)
time_elapsed = (datetime.now() - oldest_attempt).total_seconds()
time_remaining = STAY_ALIVE_TRACKING_PERIOD_SECONDS - time_elapsed
return max(0, time_remaining)
def attempt_network_reconnection():
"""
Attempt to reconnect to the network using various methods.
Returns True if reconnection succeeded, False otherwise.
Strategy:
1. First, wait briefly and check if network recovers on its own
2. If sudo is available (passwordless or with configured password), try network restart commands
3. Wait for network to stabilize and check again
"""
stay_alive_log_message("Attempting network reconnection...")
# First, wait a moment and check if the network recovers naturally
# (This often works for brief connectivity blips)
stay_alive_log_message("Waiting 5s for natural network recovery...")
time.sleep(5)
if check_network_connectivity():
stay_alive_log_message("Network recovered naturally!")
return True
# Check if we can run sudo commands (passwordless or with password)
sudo_available = check_sudo_available()
if platform.system() == "Linux":
if sudo_available:
# Linux-specific network restart commands
# Commands are specified without sudo prefix - run_sudo_command adds it
reconnection_commands = [
# Try dhclient first as it's less disruptive
(["dhclient", "-r"], "Release DHCP lease"),
(["dhclient"], "Renew DHCP lease"),
# Try bringing WiFi interface down and up
(["ip", "link", "set", "wlan0", "down"], "Disable WiFi"),
(["ip", "link", "set", "wlan0", "up"], "Enable WiFi"),
# Try ethernet as well
(["ip", "link", "set", "eth0", "down"], "Disable Ethernet"),
(["ip", "link", "set", "eth0", "up"], "Enable Ethernet"),
# Last resort: restart NetworkManager
(["systemctl", "restart", "NetworkManager"], "Restart NetworkManager"),
]
for cmd_args, description in reconnection_commands:
stay_alive_log_message(f"{description}...")
success, stdout, stderr = run_sudo_command(cmd_args, description, timeout=30)
if success:
stay_alive_log_message(f" Success")
else:
# Don't log full error for non-existent interfaces (common)
if "Cannot find device" in stderr or "does not exist" in stderr:
stay_alive_log_message(f" Skipped (interface not found)")
elif stderr:
stay_alive_log_message(f" Failed: {stderr.strip()[:100]}")
else:
stay_alive_log_message(f" Failed")
# Brief pause between commands
time.sleep(1)
# Check if network came back after each command
if check_network_connectivity():
stay_alive_log_message("Network reconnection successful!")
return True
else:
stay_alive_log_message("Sudo not available - skipping network commands")
stay_alive_log_message("Set sudo_password in settings or configure passwordless sudo")
elif platform.system() == "Windows":
# Windows commands don't need sudo
reconnection_commands = [
(["ipconfig", "/release"], "Release IP"),
(["ipconfig", "/renew"], "Renew IP"),
]
for cmd, description in reconnection_commands:
try:
stay_alive_log_message(f"{description}...")
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode == 0:
stay_alive_log_message(f" Success")
else:
stay_alive_log_message(f" Failed: {result.stderr.strip()[:100]}")
except subprocess.TimeoutExpired:
stay_alive_log_message(f" Timeout")
except Exception as e:
stay_alive_log_message(f" Error: {str(e)[:50]}")
time.sleep(1)
# Final wait for network to stabilize
stay_alive_log_message("Waiting 10s for network to stabilize...")
time.sleep(10)
# Final connectivity check
if check_network_connectivity():
stay_alive_log_message("Network reconnection successful!")
return True
stay_alive_log_message("Network reconnection failed - may need system reboot")
return False
def perform_system_reboot():
"""
Perform a system reboot to attempt to restore network connectivity.
Records the reboot attempt before initiating.
Returns True if reboot was initiated, False if it couldn't be performed.
"""
record_reboot_attempt()
stay_alive_log_message("INITIATING SYSTEM REBOOT...")
# Save any configuration before reboot
try:
save_config()
except Exception as e:
stay_alive_log_message(f"Failed to save config before reboot: {str(e)}")
# Give a moment for logs to be written
time.sleep(2)
try:
if platform.system() == "Linux":
# Check if we can use sudo (passwordless or with password)
if not check_sudo_available():
stay_alive_log_message("ERROR: Cannot reboot - sudo not available")
stay_alive_log_message("Set sudo_password in settings or configure passwordless sudo")
return False
# Use the run_sudo_command helper which handles password if needed
success, stdout, stderr = run_sudo_command(["reboot"], "System reboot", timeout=10)
if not success:
stay_alive_log_message(f"Reboot command failed: {stderr.strip()}")
return False
return True
elif platform.system() == "Windows":
# Use shutdown command on Windows (doesn't need sudo)
subprocess.run(["shutdown", "/r", "/t", "5", "/c", "AllSky stay-alive reboot"], check=True)
return True
else:
stay_alive_log_message(f"Unsupported platform for reboot: {platform.system()}")
return False
except Exception as e:
stay_alive_log_message(f"Failed to initiate reboot: {str(e)}")
return False
def reset_stay_alive_tracking():
"""Reset all stay-alive tracking data after successful reconnection"""
global stay_alive_reboot_attempts, stay_alive_last_successful_ping
stay_alive_reboot_attempts = []
stay_alive_last_successful_ping = datetime.now()
stay_alive_log_message("Stay-alive tracking reset after successful connection")
def stay_alive_monitor_loop():
"""
Background thread that monitors network connectivity and takes action if connection is lost.
"""
global stay_alive_stop_flag, stay_alive_last_successful_ping
stay_alive_log_message("Stay-alive monitor started")
stay_alive_log_message(f"Ping host: {STAY_ALIVE_PING_HOST}:{STAY_ALIVE_PING_PORT}")
stay_alive_log_message(f"Check interval: {STAY_ALIVE_CHECK_INTERVAL_SECONDS}s")
stay_alive_log_message(f"Max reboots per period: {STAY_ALIVE_MAX_REBOOT_ATTEMPTS}")
stay_alive_log_message(f"Tracking period: {STAY_ALIVE_TRACKING_PERIOD_SECONDS}s ({STAY_ALIVE_TRACKING_PERIOD_SECONDS/3600:.1f} hours)")
waiting_for_next_period = False
while not stay_alive_stop_flag:
try:
# Check if we're in a waiting period due to max reboots
reboot_count = get_reboot_attempts_in_tracking_period()
if reboot_count >= STAY_ALIVE_MAX_REBOOT_ATTEMPTS:
if not waiting_for_next_period:
time_remaining = get_time_until_next_tracking_period()
stay_alive_log_message(
f"Max reboot attempts ({STAY_ALIVE_MAX_REBOOT_ATTEMPTS}) reached. "
f"Waiting {time_remaining/60:.1f} minutes until next attempt window."
)
waiting_for_next_period = True
# Still check connectivity - we might recover naturally
if check_network_connectivity():
stay_alive_log_message("Connection restored during waiting period!")
reset_stay_alive_tracking()
waiting_for_next_period = False
# Sleep and continue checking
for _ in range(STAY_ALIVE_CHECK_INTERVAL_SECONDS):
if stay_alive_stop_flag:
break
time.sleep(1)
continue
waiting_for_next_period = False
# Check network connectivity
if check_network_connectivity():
# Connection is good
pass
else:
# Connection lost - attempt recovery
stay_alive_log_message("Network connectivity lost!")
stay_alive_log_message(f"Reboot attempts in current period: {reboot_count}/{STAY_ALIVE_MAX_REBOOT_ATTEMPTS}")
# Try reconnection attempts first
reconnection_successful = False
for attempt in range(STAY_ALIVE_MAX_RECONNECT_ATTEMPTS):
stay_alive_log_message(f"Reconnection attempt {attempt + 1}/{STAY_ALIVE_MAX_RECONNECT_ATTEMPTS}")
if attempt_network_reconnection():
reconnection_successful = True
stay_alive_log_message("Network recovered without reboot!")
reset_stay_alive_tracking()
break
# Wait before next attempt
stay_alive_log_message(f"Waiting {STAY_ALIVE_RETRY_DELAY_SECONDS}s before next attempt...")
for _ in range(STAY_ALIVE_RETRY_DELAY_SECONDS):
if stay_alive_stop_flag:
break
time.sleep(1)
if stay_alive_stop_flag:
break
# If reconnection failed, consider reboot
if not reconnection_successful and not stay_alive_stop_flag:
if reboot_count < STAY_ALIVE_MAX_REBOOT_ATTEMPTS:
stay_alive_log_message(
f"All reconnection attempts failed. Initiating reboot "
f"(attempt {reboot_count + 1}/{STAY_ALIVE_MAX_REBOOT_ATTEMPTS})"
)
perform_system_reboot()
# If we get here, reboot failed
stay_alive_log_message("Reboot command may have failed")
else:
stay_alive_log_message("Max reboot attempts reached, waiting for next period")
# Wait for next check interval
for _ in range(STAY_ALIVE_CHECK_INTERVAL_SECONDS):
if stay_alive_stop_flag:
break
time.sleep(1)
except Exception as e:
stay_alive_log_message(f"Error in stay-alive monitor: {str(e)}")
import traceback
traceback.print_exc()