Repository navigation
Expand file tree
/
Copy pathlcd_display.py
More file actions
100 lines (90 loc) · 3.78 KB
/
Copy pathlcd_display.py
File metadata and controls
100 lines (90 loc) · 3.78 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
import time
import tm1637
import json
import logging
import os
from typing import Dict, Any
def load_config(file_path: str) -> Dict[str, Any]:
try:
with open(file_path, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError) as e:
raise ConfigError(f"Error loading configuration: {e}")
class ConfigError(Exception):
pass
class LCDManager:
def __init__(self, config: Dict[str, Any]):
self.config = config
self.setup_logging()
self.displays = self._initialize_displays()
self.display_settings = {
"update_interval": self.config['sensors']['temperature'].get('update_interval', 1),
"temperature_format": "{:.1f}",
"time_format": "%H%M"
}
def setup_logging(self):
if self.config['error_logging']['enabled']:
log_dir = self.config['error_logging']['log_directory']
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, 'lcd_errors.log')
logging.basicConfig(
filename=log_file,
level=logging.ERROR,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def _initialize_displays(self) -> Dict[str, tm1637.TM1637]:
displays = {}
temp_displays = self.config['sensors']['temperature']['displays']
for key, display_info in temp_displays.items():
try:
displays[key] = tm1637.TM1637(
clk=display_info['clk_pin'],
dio=display_info['dio_pin'],
brightness=7
)
## displays[key].brightness(2) # Set brightness to maximum
except Exception as e:
logging.error(f"Error initializing display {key}: {e}")
return displays
def display_temperature(self, display_key: str, temp: float) -> None:
try:
temp_str = self.display_settings['temperature_format'].format(temp)
int_part, frac_part = temp_str.split(".")
display_str = f"{int_part[:2]} {frac_part[0]}"
self.displays[display_key].show(display_str)
except (ValueError, TypeError, KeyError) as e:
logging.error(f"Error displaying temperature on {display_key}: {e}")
def display_time(self) -> None:
current_time = time.strftime(self.display_settings['time_format'])
self.displays['H'].show(current_time, colon=True)
def update_displays(self, temperatures: Dict[str, float]) -> None:
temp_displays = self.config['sensors']['temperature']['displays']
for key, display_info in temp_displays.items():
if key != 'H': # 'H' is reserved for time display
sensor_name = display_info['name']
if sensor_name in temperatures:
self.display_temperature(key, temperatures[sensor_name])
else:
logging.error(f"Temperature for '{sensor_name}' not found in provided temperatures.")
self.display_time()
def main():
try:
config = load_config('config.json')
lcd_manager = LCDManager(config)
while True:
# Simulate temperature readings (replace with actual data source)
temperatures = {
'pool_water': 19.5,
'solar_collector_output': 30.3,
'ambient': 23.3
}
lcd_manager.update_displays(temperatures)
time.sleep(lcd_manager.display_settings['update_interval'])
except ConfigError as e:
logging.error(f"Configuration error: {e}")
except KeyboardInterrupt:
print("Program terminated by user")
except Exception as e:
logging.exception("An unexpected error occurred")
if __name__ == "__main__":
main()