-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclock.py
More file actions
857 lines (715 loc) · 29.6 KB
/
clock.py
File metadata and controls
857 lines (715 loc) · 29.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
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
"""RPI-Clock: GPS-synchronized timekeeper with weather display.
This module provides a Raspberry Pi-based clock that synchronizes time via GPS
and displays current time, temperature, feels-like temperature, and humidity
on a 7-segment LED display.
"""
import ntplib
import configparser
import requests
import adafruit_ht16k33.segments as segments
import busio
import board
import os
import sys
import time
import signal
import types
from pathlib import Path
from typing import Callable, Optional, Tuple, Dict, Any
# Change to /tmp directory to avoid GPIO permission issues
# The lgpio library tries to create notification files in the current working directory
# /opt/rpi-clock has restrictive permissions, so we switch to system temp directory
os.chdir("/tmp")
# Constants - avoid repeated lookups
API_REFRESH_CYCLES: int = 10
API_ENDPOINT: str = "https://api.openweathermap.org/data/2.5/weather"
CONFIG_FILE: str = "/opt/rpi-clock/config.ini"
# Pre-compile regex patterns and cache config values
config: configparser.ConfigParser = configparser.ConfigParser()
config.read_dict(
{
"Weather": {"api_key": "your_api_key_here", "zip_code": "your_zip_code_here"},
"Display": {
"time_format": "12",
"temp_unit": "C",
"smooth_scroll": "false",
"brightness": "0.8",
},
"NTP": {"preferred_server": "127.0.0.1"},
"Cycle": {
"time_display": "2",
"temp_display": "3",
"feels_like_display": "3",
"humidity_display": "2",
},
"CustomText": {
"enabled": "false",
"text": "",
"interval_minutes": "15",
"display_duration": "3",
},
}
)
config.read(CONFIG_FILE)
def validate_config() -> bool:
"""Validate configuration file and values.
Returns:
bool: True if configuration is valid, False otherwise
"""
errors = []
# Check if config file exists and was read
if not Path(CONFIG_FILE).exists():
errors.append(f"Configuration file not found: {CONFIG_FILE}")
return False
# Validate required sections
required_sections = ["Weather", "Display", "NTP", "Cycle", "CustomText"]
for section in required_sections:
if not config.has_section(section):
errors.append(f"Missing configuration section: [{section}]")
# Validate Weather section
if config.has_section("Weather"):
api_key = config.get("Weather", "api_key", fallback="")
if not api_key.strip():
errors.append(
"Weather API key is empty - get one from "
"https://openweathermap.org/api_keys/"
)
elif api_key == "your_openweathermap_api_key_here":
errors.append("Weather API key not configured - please edit config.ini")
zip_code = config.get("Weather", "zip_code", fallback="")
if not zip_code.strip():
errors.append("ZIP code is empty - please configure your location")
elif zip_code == "your_zip_code_here":
errors.append("ZIP code not configured - please edit config.ini")
elif not zip_code.isdigit() or len(zip_code) != 5:
errors.append("ZIP code must be 5 digits")
# Validate Display section
if config.has_section("Display"):
time_format = config.get("Display", "time_format", fallback="")
if time_format not in ["12", "24"]:
errors.append("time_format must be '12' or '24'")
temp_unit = config.get("Display", "temp_unit", fallback="")
if temp_unit not in ["C", "F"]:
errors.append("temp_unit must be 'C' or 'F'")
smooth_scroll = config.get("Display", "smooth_scroll", fallback="")
if smooth_scroll.lower() not in ["true", "false"]:
errors.append("smooth_scroll must be 'true' or 'false'")
brightness = config.get("Display", "brightness", fallback="")
try:
brightness_val = float(brightness)
if brightness_val < 0.0 or brightness_val > 1.0:
errors.append("brightness must be between 0.0 and 1.0")
except (ValueError, TypeError):
errors.append("brightness must be a valid number between 0.0 and 1.0")
# Validate Cycle section
if config.has_section("Cycle"):
cycle_options = [
"time_display",
"temp_display",
"feels_like_display",
"humidity_display",
]
for option in cycle_options:
try:
value = config.getint("Cycle", option)
if value < 1 or value > 60:
errors.append(f"{option} must be between 1 and 60 seconds")
except (ValueError, TypeError):
errors.append(f"{option} must be a valid integer")
# Validate CustomText section
if config.has_section("CustomText"):
enabled = config.get("CustomText", "enabled", fallback="")
if enabled.lower() not in ["true", "false"]:
errors.append("CustomText enabled must be 'true' or 'false'")
elif enabled.lower() == "true":
custom_text = config.get("CustomText", "text", fallback="")
if not custom_text.strip():
errors.append("CustomText text cannot be empty when enabled")
elif len(custom_text) > 50:
errors.append(
"CustomText text should be 50 characters or less for optimal display"
)
try:
interval = config.getint("CustomText", "interval_minutes")
if interval < 1 or interval > 1440: # 1 minute to 24 hours
errors.append(
"CustomText interval_minutes must be between 1 and 1440"
)
except (ValueError, TypeError):
errors.append("CustomText interval_minutes must be a valid integer")
try:
duration = config.getint("CustomText", "display_duration")
if duration < 1 or duration > 60:
errors.append(
"CustomText display_duration must be between 1 and 60 seconds"
)
except (ValueError, TypeError):
errors.append("CustomText display_duration must be a valid integer")
# Print errors if any
if errors:
print("✗ Configuration validation failed:")
for error in errors:
print(f" - {error}")
print(f"\nPlease edit {CONFIG_FILE} to fix these issues")
return False
print("✓ Configuration validation passed")
return True
# Validate configuration before proceeding
if not validate_config():
print("Configuration validation failed - exiting")
sys.exit(1)
# Cache all config values at startup
API_KEY: str = config["Weather"]["api_key"]
ZIP_CODE: str = config["Weather"]["zip_code"]
TIME_FORMAT: str = config["Display"]["time_format"]
TEMP_UNIT: str = config["Display"]["temp_unit"]
SMOOTH_SCROLL: bool = config.getboolean("Display", "smooth_scroll")
BRIGHTNESS: float = config.getfloat("Display", "brightness")
PREFERRED_NTP_SERVER: str = config["NTP"]["preferred_server"]
TIME_DISPLAY: int = config.getint("Cycle", "time_display")
TEMP_DISPLAY: int = config.getint("Cycle", "temp_display")
FEELS_LIKE_DISPLAY: int = config.getint("Cycle", "feels_like_display")
HUMIDITY_DISPLAY: int = config.getint("Cycle", "humidity_display")
CUSTOM_TEXT_ENABLED: bool = config.getboolean("CustomText", "enabled")
CUSTOM_TEXT: str = config.get("CustomText", "text", fallback="")
CUSTOM_TEXT_INTERVAL: int = config.getint("CustomText", "interval_minutes")
CUSTOM_TEXT_DURATION: int = config.getint("CustomText", "display_duration")
CUSTOM_TEXT_INTERVAL_SECONDS: int = CUSTOM_TEXT_INTERVAL * 60
# Pre-compute conversion factor
C_TO_F_FACTOR: float = 9 / 5 # Avoid repeated division
SCROLL_DELAY: float = 0.12 # Seconds per marquee step for smooth feel
# Global variables
cached_weather_info: Optional[Tuple[float, float, int]] = None
display: Optional[segments.Seg7x4] = None
ntp_client: Optional[ntplib.NTPClient] = None # Reuse NTP client
SESSION: Optional[requests.Session] = None # Reusable HTTP session
WEATHER_PARAMS: Optional[Dict[str, str]] = None # Prebuilt OpenWeather params
# Display write cache
last_display_text: Optional[str] = None
last_time_minute: Optional[int] = None
last_custom_text_time: Optional[float] = None
def signal_handler(sig: int, frame: Any) -> None:
"""Handle graceful shutdown on SIGINT (Ctrl+C) or SIGTERM.
Args:
sig: Signal number
frame: Current stack frame
"""
if display:
display.fill(0)
display.show()
sys.exit(0)
def check_hardware_prerequisites() -> bool:
"""Check hardware prerequisites before attempting display initialization.
Returns:
bool: True if all hardware prerequisites are met, False otherwise
"""
print("Checking hardware prerequisites...")
# Check if I2C modules are loaded
try:
with open("/proc/modules", "r") as f:
modules = f.read()
if "i2c_dev" not in modules:
print("✗ I2C device module not loaded")
print(" Run: sudo modprobe i2c_dev")
return False
if "i2c_bcm2835" not in modules:
print("✗ I2C BCM2835 module not loaded")
print(" Run: sudo modprobe i2c_bcm2835")
return False
except Exception as e:
print(f"✗ Cannot check I2C modules: {e}")
return False
# Check if I2C device files exist
if not Path("/dev/i2c-1").exists():
print("✗ I2C device file /dev/i2c-1 not found")
print(" I2C interface may not be enabled")
print(" Run: sudo raspi-config nonint do_i2c 0")
print(" Then reboot the system")
return False
# Check if user has I2C permissions
try:
import grp
i2c_group = grp.getgrnam("i2c")
if i2c_group.gr_gid not in os.getgroups():
print("✗ User not in i2c group")
print(" Run: sudo usermod -a -G i2c $USER")
print(" Then logout and login again")
return False
except Exception as e:
print(f"✗ Cannot check I2C permissions: {e}")
return False
print("✓ Hardware prerequisites check passed")
return True
def scan_i2c_devices() -> bool:
"""Scan I2C bus for devices and check for display.
Returns:
bool: True if display is found at expected address, False otherwise
"""
print("Scanning I2C bus for devices...")
try:
i2c = busio.I2C(board.SCL, board.SDA)
devices = i2c.scan()
if not devices:
print("✗ No I2C devices found on bus")
print(" Check your wiring:")
print(" - VIN (red) → Pi pin 2 (5V)")
print(" - IO (orange) → Pi pin 1 (3.3V) - REQUIRED")
print(" - GND (black) → Pi pin 6 (GND)")
print(" - SDA (yellow) → Pi pin 3 (GPIO 2)")
print(" - SCL (white) → Pi pin 5 (GPIO 3)")
return False
print(f"✓ Found I2C devices at addresses: {[hex(addr) for addr in devices]}")
if 0x70 in devices:
print("✓ Display found at address 0x70")
return True
else:
print("✗ Display NOT found at address 0x70")
print(" Expected device at 0x70 (7-segment display)")
print(" Check your wiring:")
print(" - VIN (red) → Pi pin 2 (5V)")
print(" - IO (orange) → Pi pin 1 (3.3V) - REQUIRED")
print(" - GND (black) → Pi pin 6 (GND)")
print(" - SDA (yellow) → Pi pin 3 (GPIO 2)")
print(" - SCL (white) → Pi pin 5 (GPIO 3)")
print(" - Ensure all connections are secure")
return False
except OSError as e:
if e.errno == 121: # Remote I/O error
print("✗ I2C Remote I/O error - device not responding")
print(" This usually indicates a wiring problem")
print(" Check your connections:")
print(" - VIN (red) → Pi pin 2 (5V)")
print(" - IO (orange) → Pi pin 1 (3.3V) - REQUIRED")
print(" - GND (black) → Pi pin 6 (GND)")
print(" - SDA (yellow) → Pi pin 3 (GPIO 2)")
print(" - SCL (white) → Pi pin 5 (GPIO 3)")
elif e.errno == 5: # Input/output error
print("✗ I2C Input/Output error")
print(" Check I2C interface is enabled and user has permissions")
else:
print(f"✗ I2C communication error: {e}")
return False
except Exception as e:
print(f"✗ Unexpected error scanning I2C devices: {e}")
return False
def initialize_display() -> bool:
"""Initialize the 7-segment display with comprehensive error handling.
Returns:
bool: True if display initialized successfully, False otherwise
"""
global display
# First check hardware prerequisites
if not check_hardware_prerequisites():
print("✗ Hardware prerequisites not met - cannot initialize display")
return False
# Scan for I2C devices
if not scan_i2c_devices():
print("✗ I2C device scan failed - cannot initialize display")
return False
# Now attempt to initialize the display
try:
print("Initializing 7-segment display...")
i2c = busio.I2C(board.SCL, board.SDA)
display = segments.Seg7x4(i2c)
display.brightness = BRIGHTNESS
print(
f"✓ 7-segment display initialized successfully (brightness: {BRIGHTNESS})"
)
# Test the display with a simple message
display.fill(0)
display.print("INIT")
display.show()
time.sleep(1)
display.fill(0)
display.show()
return True
except ValueError as e:
if "No I2C device at address" in str(e):
print("✗ Display not found at expected address 0x70")
print(" This indicates a wiring problem:")
print(" - Check all connections are secure")
print(" - Ensure VIN (red) is connected to 5V")
print(" - Ensure IO (orange) is connected to 3.3V - REQUIRED")
print(" - Verify SDA/SCL connections")
print(" - Try power cycling the display")
else:
print(f"✗ Display address error: {e}")
return False
except OSError as e:
if e.errno == 121: # Remote I/O error
print("✗ I2C Remote I/O error during display initialization")
print(" Device not responding - check wiring:")
print(" - VIN (red) → Pi pin 2 (5V)")
print(" - IO (orange) → Pi pin 1 (3.3V) - REQUIRED")
print(" - GND (black) → Pi pin 6 (GND)")
print(" - SDA (yellow) → Pi pin 3 (GPIO 2)")
print(" - SCL (white) → Pi pin 5 (GPIO 3)")
elif e.errno == 5: # Input/output error
print("✗ I2C Input/Output error during display initialization")
print(" Check I2C interface and permissions")
else:
print(f"✗ I2C communication error: {e}")
return False
except Exception as e:
print(f"✗ Display initialization failed: {e}")
print(" Run i2c-test.sh for detailed diagnostics")
print(" Check wiring and I2C setup")
return False
def initialize_ntp() -> bool:
"""Initialize NTP client once.
Returns:
bool: True if NTP client initialized successfully, False otherwise
"""
global ntp_client
try:
ntp_client = ntplib.NTPClient()
print("✓ NTP client initialized successfully")
return True
except Exception as e:
print(f"✗ NTP client initialization failed: {e}")
print(" NTP functionality will be limited")
return False
def initialize_http_session() -> bool:
"""Initialize a reusable HTTP session and prebuild request params.
Returns:
bool: True if HTTP session initialized successfully, False otherwise
"""
global SESSION, WEATHER_PARAMS
try:
SESSION = requests.Session()
WEATHER_PARAMS = {"zip": ZIP_CODE, "appid": API_KEY, "units": "metric"}
print("✓ HTTP session initialized successfully")
return True
except Exception as e:
print(f"✗ HTTP session initialization failed: {e}")
print(" Weather functionality will be limited")
SESSION = None
WEATHER_PARAMS = None
return False
def celsius_to_fahrenheit(celsius: float) -> float:
"""Convert Celsius temperature to Fahrenheit - optimized.
Args:
celsius: Temperature in Celsius
Returns:
float: Temperature in Fahrenheit
"""
return (celsius * C_TO_F_FACTOR) + 32
def write_display(text: str) -> None:
"""Write text to display only if it changed.
Args:
text: Text to display on the 7-segment display
"""
global last_display_text
if not display:
return
if text != last_display_text:
display.print(text)
display.show()
last_display_text = text
def build_temp_string(temp: float, unit: str) -> str:
"""Create temperature string without truncation for scrolling.
Args:
temp: Temperature value
unit: Temperature unit (C or F)
Returns:
str: Formatted temperature string
"""
if temp < 0:
return f"-{int(abs(temp))}{unit}"
return f"{int(temp)}{unit}"
def display_temperature(temp: float, unit: str) -> None:
"""Display temperature on the 7-segment display.
Args:
temp: Temperature value (float; will be truncated to int for display).
unit: Temperature unit string, e.g. 'C' or 'F'.
"""
if not display:
return
write_display(build_temp_string(temp, unit)[:4].rjust(4))
def display_time() -> None:
"""Display time with optimized formatting."""
if not display:
return
now = time.localtime()
hour = now.tm_hour
if TIME_FORMAT == "12":
hour = hour % 12 or 12 # More efficient than if/else
minute = now.tm_min
# Use format string for better performance
write_display(f"{hour:2d}{minute:02d}")
def display_humidity(humidity: float) -> None:
"""Display humidity with integer rounding.
Args:
humidity: Humidity percentage value
"""
if not display:
return
# Show humidity with "rH" prefix (e.g., "rH50" for 50% humidity)
# Since 7-segment display can't show '%', we use "rH" to indicate relative humidity
write_display(f"rH{int(round(humidity)):02d}")
def scroll_combined_label_value(
label: str, value_text: str, delay: float = SCROLL_DELAY
) -> None:
"""Scroll a combined label and value across the display.
Example: label='Out', value_text='72F' => 'Out 72F ' scrolls once.
Args:
label: Label text to display
value_text: Value text to display
delay: Delay between scroll steps in seconds
"""
if not display:
return
# Compose with padding at end to allow scroll-off
full_text = f"{label} {value_text} "
display.fill(0)
display.marquee(full_text, delay=delay, loop=False)
# Invalidate cache since marquee wrote directly to display
global last_display_text
last_display_text = None
def fetch_weather() -> Optional[Tuple[float, float, int]]:
"""Fetch weather with optimized retry logic.
Returns:
Optional[Tuple[int, int, int]]: (temperature, feels_like, humidity) or None
"""
max_retries = 3
retry_delay = 5
# Use prebuilt params and session
params = WEATHER_PARAMS
for attempt in range(max_retries):
try:
if SESSION is None:
response = requests.get(API_ENDPOINT, params=params, timeout=10)
else:
response = SESSION.get(API_ENDPOINT, params=params, timeout=10)
response.raise_for_status()
weather_data = response.json()
# Extract data once; keep floats through unit conversion so
# celsius_to_fahrenheit receives precise values, not pre-rounded ints
main_data = weather_data["main"]
temperature: float = float(main_data["temp"])
feels_like: float = float(main_data["feels_like"])
humidity: int = int(round(main_data["humidity"]))
# Convert units if needed
if TEMP_UNIT == "F":
temperature = celsius_to_fahrenheit(temperature)
feels_like = celsius_to_fahrenheit(feels_like)
return temperature, feels_like, humidity
except requests.exceptions.Timeout:
print(f"✗ Weather API timeout (attempt {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
time.sleep(retry_delay)
else:
print(" Weather data unavailable - check internet connection")
return None
except requests.exceptions.ConnectionError:
print(
f"✗ Weather API connection error "
f"(attempt {attempt + 1}/{max_retries})"
)
if attempt < max_retries - 1:
time.sleep(retry_delay)
else:
print(" Weather data unavailable - check internet connection")
return None
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
print("✗ Weather API authentication failed - check API key")
elif e.response.status_code == 404:
print("✗ Weather API location not found - check ZIP code")
else:
print(f"✗ Weather API HTTP error: {e}")
return None
except requests.exceptions.RequestException as e:
print(f"✗ Weather API request error: {e}")
if attempt < max_retries - 1:
time.sleep(retry_delay)
else:
return None
except (KeyError, ValueError, TypeError) as e:
print(f"✗ Weather data parsing error: {e}")
print(" Weather API response format may have changed")
return None
return None
def get_current_time() -> time.struct_time:
"""Get current time with cached NTP client.
Returns:
time.struct_time: Current time structure
"""
try:
if ntp_client:
response = ntp_client.request(PREFERRED_NTP_SERVER, version=3, timeout=5)
return time.localtime(response.tx_time)
except ntplib.NTPException as e:
print(f"✗ NTP synchronization failed: {e}")
print(" Using system time - check GPS/NTP configuration")
except Exception as e:
print(f"✗ Time synchronization error: {e}")
return time.localtime()
def display_metric_with_message(
message: str, display_function: Callable[..., None], *args: Any, delay: int = 2
) -> None:
"""Display metric with optimized timing.
Args:
message: Message to display via marquee
display_function: Function to call after message
*args: Arguments to pass to display_function
delay: Delay in seconds after message
"""
if not display:
return
display.fill(0)
display.marquee(message, delay=0.2, loop=False)
time.sleep(delay)
# Marquee changed the display buffer; invalidate cache so next write isn't skipped
global last_display_text
last_display_text = None
display_function(*args)
# display.show() occurs within write_display when content changes
def display_custom_text() -> None:
"""Display custom text with scrolling animation.
Uses the configured custom text and scrolls it across the display
for the configured duration. Respects the smooth_scroll setting.
"""
if not display or not CUSTOM_TEXT_ENABLED or not CUSTOM_TEXT.strip():
return
print(f"Displaying custom text: {CUSTOM_TEXT}")
if SMOOTH_SCROLL:
# Use smooth scrolling with marquee
display.fill(0)
display.marquee(CUSTOM_TEXT, delay=SCROLL_DELAY, loop=False)
else:
# Use static display for the configured duration
write_display(CUSTOM_TEXT[:4]) # Show first 4 characters
# Wait for the configured duration
time.sleep(CUSTOM_TEXT_DURATION)
# Invalidate cache since marquee wrote directly to display
global last_display_text
last_display_text = None
def should_display_custom_text() -> bool:
"""Check if custom text should be displayed based on interval timing.
Returns:
bool: True if custom text should be displayed, False otherwise
"""
if not CUSTOM_TEXT_ENABLED or not CUSTOM_TEXT.strip():
return False
global last_custom_text_time
current_time = time.time()
# If never displayed before, display it
if last_custom_text_time is None:
last_custom_text_time = current_time
return True
# Check if enough time has passed
if current_time - last_custom_text_time >= CUSTOM_TEXT_INTERVAL_SECONDS:
last_custom_text_time = current_time
return True
return False
def main_loop() -> None:
"""Optimized main loop with reduced function calls."""
cycle_counter = 0
global cached_weather_info
if not display:
print("⚠ Running without display - logging weather/time to console only")
while True:
try:
# Time display loop - optimized with monotonic tick and cached redraws
total_seconds = TIME_DISPLAY * 2 # preserve original semantics
# Initial render and minute cache
now_struct = time.localtime()
global last_time_minute
last_time_minute = now_struct.tm_min
display_time()
seconds_elapsed = 0
colon_on = False
next_tick = time.monotonic()
while seconds_elapsed < total_seconds:
colon_on = not colon_on
if display:
display.colon = colon_on
display.show()
# Update time at minute change without redrawing otherwise
now_struct = time.localtime()
if now_struct.tm_min != last_time_minute:
last_time_minute = now_struct.tm_min
display_time()
next_tick += 1.0
sleep_duration = next_tick - time.monotonic()
if sleep_duration > 0:
time.sleep(sleep_duration)
seconds_elapsed += 1
# Check if custom text should be displayed
if should_display_custom_text():
display_custom_text()
# Weather display - only fetch when needed
if cycle_counter == 0 or cached_weather_info is None:
cached_weather_info = fetch_weather()
if cached_weather_info:
temperature, feels_like, humidity = cached_weather_info
if not display:
now_str = time.strftime(
"%I:%M %p" if TIME_FORMAT == "12" else "%H:%M"
)
print(
f"[{now_str}] "
f"Temp: {int(temperature)}{TEMP_UNIT} "
f"Feels: {int(feels_like)}{TEMP_UNIT} "
f"Humidity: {int(round(humidity))}%"
)
if SMOOTH_SCROLL:
# Scroll label + value together for a ticker feel
scroll_combined_label_value(
"Out", build_temp_string(temperature, TEMP_UNIT)
)
scroll_combined_label_value(
"FEEL", build_temp_string(feels_like, TEMP_UNIT)
)
scroll_combined_label_value("rH", f"{int(round(humidity)):02d}")
else:
# Original stepwise messaging
display_metric_with_message(
"Out", display_temperature, temperature, TEMP_UNIT
)
time.sleep(TEMP_DISPLAY)
display_metric_with_message(
"feel", display_temperature, feels_like, TEMP_UNIT
)
time.sleep(FEELS_LIKE_DISPLAY)
display_humidity(humidity)
time.sleep(HUMIDITY_DISPLAY)
cycle_counter = (cycle_counter + 1) % API_REFRESH_CYCLES
except KeyboardInterrupt:
print("\nReceived interrupt signal - shutting down gracefully")
break
except Exception as e:
print(f"✗ Unexpected error in main loop: {e}")
print(" Continuing operation - check system logs for details")
time.sleep(5)
if __name__ == "__main__":
# Set up signal handlers
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
print("RPI-Clock: GPS-synchronized timekeeper with weather display")
print("=" * 60)
# Initialize components with proper error handling
display_ok = initialize_display()
ntp_ok = initialize_ntp()
http_ok = initialize_http_session()
# Warn about non-critical failures
warnings = []
if not display_ok:
warnings.append(
"Display not found - running headless (check wiring or run i2c-test.sh)"
)
if not ntp_ok:
warnings.append("NTP client failed - time sync may be limited")
if not http_ok:
warnings.append("HTTP session failed - weather data may be unavailable")
if warnings:
print("\n⚠️ Warnings:")
for warning in warnings:
print(f" - {warning}")
print(" Clock will continue with limited functionality")
else:
print("\n✓ All components initialized successfully")
print("Starting Raspberry Pi Clock...")
print("=" * 60)
main_loop()