-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheartbeat.py
More file actions
212 lines (185 loc) · 7.28 KB
/
heartbeat.py
File metadata and controls
212 lines (185 loc) · 7.28 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
#!/usr/bin/env python3
"""
Temperature monitoring script that controls a GPIO pin based on temperature threshold.
Turns ON GPIO pin when temperature exceeds threshold, OFF when below.
"""
import time
import argparse
import requests
import shutil
from gpiozero import OutputDevice, LED
def parse_arguments():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description='Monitor temperature and control GPIO pin based on threshold'
)
parser.add_argument(
'--threshold', '-t',
type=float,
default=40.0,
help='Temperature threshold in Celsius (default: 40.0)'
)
parser.add_argument(
'--pin', '-p',
type=int,
default=24,
help='GPIO pin number in BCM numbering (default: 24)'
)
parser.add_argument(
'--heartbeat-pin', '-b',
type=int,
default=23,
help='GPIO pin for heartbeat LED (default: 23, use 0 to disable)'
)
parser.add_argument(
'--grafana-url', '-g',
type=str,
default=None,
help='Grafana URL for health check (optional, e.g., http://localhost:3000)'
)
parser.add_argument(
'--interval', '-i',
type=int,
default=10,
help='Check interval in seconds (default: 10)'
)
parser.add_argument(
'--check-disk', '-d',
action='store_true',
help='Enable disk usage monitoring (activates GPIO if available space < 30%%)'
)
return parser.parse_args()
def get_cpu_temperature():
"""
Alternative method: Read temperature directly from the system.
Works on Raspberry Pi.
"""
try:
with open('/sys/class/thermal/thermal_zone0/temp', 'r') as f:
temp = float(f.read().strip()) / 1000.0
return temp
except FileNotFoundError:
# Fallback to psutil if thermal zone not available
try:
import psutil
temps = psutil.sensors_temperatures()
if 'cpu_thermal' in temps:
return temps['cpu_thermal'][0].current
except:
pass
except Exception as e:
print(f"Error reading temperature: {e}")
return None
def check_grafana_health(grafana_url):
"""
Check if Grafana is healthy and responding.
Returns True if healthy, False otherwise.
"""
try:
response = requests.get(f"{grafana_url}/api/health", timeout=5)
if response.status_code == 200:
data = response.json()
return data.get('database') == 'ok'
return False
except Exception as e:
print(f"Grafana health check failed: {e}")
return False
def get_disk_usage(path='/'):
"""
Get disk usage for the specified path.
Returns tuple of (total, used, free) in GB and percentage available.
"""
try:
stat = shutil.disk_usage(path)
total_gb = stat.total / (1024**3)
used_gb = stat.used / (1024**3)
free_gb = stat.free / (1024**3)
percent_available = (stat.free / stat.total) * 100
return total_gb, used_gb, free_gb, percent_available
except Exception as e:
print(f"Error reading disk usage: {e}")
return None, None, None, None
def control_gpio_by_temperature(threshold, gpio_pin, heartbeat_pin, grafana_url, check_interval, check_disk):
"""
Main control loop: monitors temperature and controls GPIO pin.
Optional heartbeat LED blinks on each temperature check.
Also monitors Grafana health status and optionally disk usage.
"""
# Initialize GPIO devices
gpio_device = OutputDevice(gpio_pin)
heartbeat_led = LED(heartbeat_pin) if heartbeat_pin > 0 else None
print(f"Starting temperature monitoring...")
print(f"Threshold: {threshold}°C")
print(f"GPIO Pin: {gpio_pin} (temperature control)")
if heartbeat_led:
print(f"GPIO Pin: {heartbeat_pin} (heartbeat LED)")
if grafana_url:
print(f"Grafana URL: {grafana_url}")
if check_disk:
print(f"Disk monitoring: enabled (threshold: 30%)")
print(f"Check interval: {check_interval}s")
print("-" * 50)
try:
while True:
# Blink heartbeat LED to show activity
if heartbeat_led:
heartbeat_led.on()
# Get current temperature
temp = get_cpu_temperature()
# Check disk usage if enabled
if check_disk:
total_gb, used_gb, free_gb, percent_available = get_disk_usage('/')
else:
total_gb, used_gb, free_gb, percent_available = None, None, None, None
# Check Grafana health if URL is provided
grafana_healthy = check_grafana_health(grafana_url) if grafana_url else None
if temp is not None:
print(f"Temperature: {temp:.1f}°C", end=" - ")
# Control GPIO based on threshold OR Grafana health OR low disk space
# Turn ON if: temperature exceeds threshold OR Grafana is unhealthy OR disk available < 30%
should_activate = (
temp > threshold or
(grafana_url and not grafana_healthy) or
(check_disk and percent_available is not None and percent_available < 30)
)
if should_activate:
gpio_device.on()
reasons = []
if temp > threshold:
reasons.append("temp above threshold")
if grafana_url and not grafana_healthy:
reasons.append("Grafana unhealthy")
if check_disk and percent_available is not None and percent_available < 30:
reasons.append(f"low disk space ({percent_available:.1f}% available)")
print(f"GPIO {gpio_pin} ON ({', '.join(reasons)})", end="")
else:
gpio_device.off()
print(f"GPIO {gpio_pin} OFF (normal)", end="")
else:
print("Could not read temperature", end="")
# Display Grafana status if enabled
if grafana_url:
grafana_status = "✓ Healthy" if grafana_healthy else "✗ Unhealthy"
print(f" - Grafana: {grafana_status}", end="")
# Display disk usage if enabled
if check_disk and percent_available is not None:
disk_status = f"Disk: {free_gb:.1f}GB free ({percent_available:.1f}%)"
print(f" - {disk_status}")
else:
print() # Just print newline
# Turn off heartbeat LED
if heartbeat_led:
time.sleep(0.1) # Keep LED on for 100ms
heartbeat_led.off()
time.sleep(check_interval)
except KeyboardInterrupt:
print("\nShutting down...")
gpio_device.off()
if heartbeat_led:
heartbeat_led.off()
heartbeat_led.close()
gpio_device.close()
print("GPIO cleaned up. Exiting.")
if __name__ == "__main__":
args = parse_arguments()
control_gpio_by_temperature(args.threshold, args.pin, args.heartbeat_pin, args.grafana_url, args.interval, args.check_disk)