Skip to content

Commit 377410c

Browse files
author
Senne Vande Sompele
committed
power monitor changed to latest version
1 parent cac210f commit 377410c

File tree

4 files changed

+49
-74
lines changed

4 files changed

+49
-74
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ You need to have at least __python 3.6__ installed to use System Sensors.
3434
| deviceName | true | \ | device name is sent with topic
3535
| client_id | true | \ | client id to connect to the MQTT broker
3636
| timezone | true | \ | Your local timezone (you can find the list of timezones here: [time zones](https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568))
37-
| power_integer_state | false | false | Return the power state in text or integer form
37+
| power_integer_state(Deprecated) | false | false | Deprecated
3838
| update_interval | false | 60 | The update interval to send new values to the MQTT broker
3939
| check_available_updates | false | false | Check the # of avaiblable updates
4040
| check_wifi_strength | false | false | Check the wifi strength

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
paho-mqtt==1.5.0
22
psutil==5.6.6
33
pytz==2019.2
4-
PyYAML==5.2
4+
PyYAML==5.2
5+
rpi_bad_power==0.0.3

src/settings_example.yaml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ mqtt:
66
deviceName: test
77
client_id: test
88
timezone: Europe/Brussels
9-
power_integer_state: false #defaults to false
109
update_interval: 60 #Defaults to 60
1110
check_wifi_strength: true
1211
check_available_updates: true

src/system_sensors.py

Lines changed: 46 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from datetime import timedelta
99
from re import findall
1010
from subprocess import check_output
11-
11+
from rpi_bad_power import new_under_voltage
1212
import paho.mqtt.client as mqtt
1313
import psutil
1414
import pytz
@@ -18,7 +18,6 @@
1818

1919
try:
2020
import apt
21-
2221
apt_disabled = False
2322
except ImportError:
2423
apt_disabled = True
@@ -34,9 +33,9 @@
3433
OS_DATA[row[0]] = row[1]
3534

3635
mqttClient = None
37-
SYSFILE = "/sys/devices/platform/soc/soc:firmware/get_throttled"
3836
WAIT_TIME_SECONDS = 60
3937
deviceName = None
38+
_underVoltage = None
4039

4140
class ProgramKilled(Exception):
4241
pass
@@ -65,6 +64,11 @@ def run(self):
6564
self.execute(*self.args, **self.kwargs)
6665

6766

67+
def write_message_to_console(message):
68+
print(message)
69+
sys.stdout.flush()
70+
71+
6872
def utc_from_timestamp(timestamp: float) -> dt.datetime:
6973
"""Return a UTC time from a timestamp."""
7074
return UTC.localize(dt.datetime.utcfromtimestamp(timestamp))
@@ -95,40 +99,28 @@ def on_message(client, userdata, message):
9599

96100
def updateSensors():
97101
payload_str = (
98-
'{"temperature": '
99-
+ get_temp()
100-
+ ', "disk_use": '
101-
+ get_disk_usage("/")
102-
+ ', "memory_use": '
103-
+ get_memory_usage()
104-
+ ', "cpu_usage": '
105-
+ get_cpu_usage()
106-
+ ', "swap_usage": '
107-
+ get_swap_usage()
108-
+ ', "power_status": "'
109-
+ get_rpi_power_status()
110-
+ '", "last_boot": "'
111-
+ get_last_boot()
112-
+ '", "last_message": "'
113-
+ get_last_message()
114-
+ '"'
102+
'{'
103+
+ f'"temperature": {get_temp()},'
104+
+ f'"disk_use": {get_disk_usage("/")},'
105+
+ f'"memory_use": {get_memory_usage()},'
106+
+ f'"cpu_usage": {get_cpu_usage()},'
107+
+ f'"swap_usage": {get_swap_usage()},'
108+
+ f'"power_status": "{get_rpi_power_status()}",'
109+
+ f'"last_boot": "{get_last_boot()}",'
110+
+ f'"last_message": "{get_last_message()}"'
115111
)
116112
if "check_available_updates" in settings and settings["check_available_updates"] and not apt_disabled:
117-
payload_str = payload_str + ', "updates": ' + get_updates()
113+
payload_str = payload_str + f', "updates": {get_updates()}'
118114
if "check_wifi_strength" in settings and settings["check_wifi_strength"]:
119-
payload_str = payload_str + ', "wifi_strength": ' + get_wifi_strength()
115+
payload_str = payload_str + f', "wifi_strength": {get_wifi_strength()}'
120116
if "external_drives" in settings:
121117
for drive in settings["external_drives"]:
122118
payload_str = (
123-
payload_str
124-
+ ', "disk_use_'
125-
+ drive.lower()
126-
+ '": '
127-
+ get_disk_usage(settings["external_drives"][drive])
119+
payload_str + f', "disk_use_{drive.lower()}": {get_disk_usage(settings["external_drives"][drive])}'
128120
)
129121
payload_str = payload_str + "}"
130122
mqttClient.publish(
131-
topic="system-sensors/sensor/" + deviceName + "/state",
123+
topic=f"system-sensors/sensor/{deviceName}/state",
132124
payload=payload_str,
133125
qos=1,
134126
retain=False,
@@ -183,55 +175,31 @@ def get_wifi_strength(): # check_output(["/proc/net/wireless", "grep wlan0"])
183175

184176

185177
def get_rpi_power_status():
186-
_throttled = open(SYSFILE, "r").read()[:-1]
187-
_throttled = _throttled[:4]
188-
189-
if "power_integer_state" in settings and settings["power_integer_state"]:
190-
return _throttled
191-
else:
192-
if _throttled == "0":
193-
return "Everything is working as intended"
194-
elif _throttled == "1000":
195-
return "Under-voltage was detected, consider getting a uninterruptible power supply for your Raspberry Pi."
196-
elif _throttled == "2000":
197-
return "Your Raspberry Pi is limited due to a bad powersupply, replace the power supply cable or power supply itself."
198-
elif _throttled == "3000":
199-
return "Your Raspberry Pi is limited due to a bad powersupply, replace the power supply cable or power supply itself."
200-
elif _throttled == "4000":
201-
return "The Raspberry Pi is throttled due to a bad power supply this can lead to corruption and instability, please replace your changer and cables."
202-
elif _throttled == "5000":
203-
return "The Raspberry Pi is throttled due to a bad power supply this can lead to corruption and instability, please replace your changer and cables."
204-
elif _throttled == "8000":
205-
return "Your Raspberry Pi is overheating, consider getting a fan or heat sinks."
206-
else:
207-
return "There is a problem with your power supply or system."
178+
return _underVoltage.get()
208179

209180

210181
def check_settings(settings):
211182
if "mqtt" not in settings:
212-
print("Mqtt not defined in settings.yaml! Please check the documentation")
213-
sys.stdout.flush()
183+
write_message_to_console("Mqtt not defined in settings.yaml! Please check the documentation")
214184
sys.exit()
215185
if "hostname" not in settings["mqtt"]:
216-
print("Hostname not defined in settings.yaml! Please check the documentation")
217-
sys.stdout.flush()
186+
write_message_to_console("Hostname not defined in settings.yaml! Please check the documentation")
218187
sys.exit()
219188
if "timezone" not in settings:
220-
print("Timezone not defined in settings.yaml! Please check the documentation")
221-
sys.stdout.flush()
189+
write_message_to_console("Timezone not defined in settings.yaml! Please check the documentation")
222190
sys.exit()
223191
if "deviceName" not in settings:
224-
print("deviceName not defined in settings.yaml! Please check the documentation")
225-
sys.stdout.flush()
192+
write_message_to_console("deviceName not defined in settings.yaml! Please check the documentation")
226193
sys.exit()
227194
if "client_id" not in settings:
228-
print("client_id not defined in settings.yaml! Please check the documentation")
229-
sys.stdout.flush()
195+
write_message_to_console("client_id not defined in settings.yaml! Please check the documentation")
230196
sys.exit()
197+
if "power_integer_state" in settings:
198+
write_message_to_console("power_integer_state is deprecated please remove this option power state is now a binary_sensor!")
231199

232200

233201
def send_config_message(mqttClient):
234-
print("send config message")
202+
write_message_to_console("send config message")
235203
mqttClient.publish(
236204
topic=f"homeassistant/sensor/{deviceName}/{deviceName}Temp/config",
237205
payload='{"device_class":"temperature",'
@@ -304,15 +272,22 @@ def send_config_message(mqttClient):
304272
retain=True,
305273
)
306274
mqttClient.publish(
307-
topic=f"homeassistant/sensor/{deviceName}/{deviceName}PowerStatus/config",
308-
payload=f"{{\"name\":\"{deviceName} PowerStatus\","
275+
topic=f"homeassistant/binary_sensor/{deviceName}/{deviceName}PowerStatus/config",
276+
payload='{"device_class":"problem",'
277+
+ f"\"name\":\"{deviceName} UnderVoltage\","
309278
+ f"\"state_topic\":\"system-sensors/sensor/{deviceName}/state\","
310279
+ '"value_template":"{{value_json.power_status}}",'
311280
+ f"\"unique_id\":\"{deviceName.lower()}_sensor_power_status\","
312281
+ f"\"availability_topic\":\"system-sensors/sensor/{deviceName}/availability\","
313282
+ f"\"device\":{{\"identifiers\":[\"{deviceName.lower()}_sensor\"],"
314-
+ f"\"name\":\"{deviceName} Sensors\",\"model\":\"RPI {deviceName}\", \"manufacturer\":\"RPI\"}},"
315-
+ f"\"icon\":\"mdi:power-plug\"}}",
283+
+ f"\"name\":\"{deviceName} Sensors\",\"model\":\"RPI {deviceName}\", \"manufacturer\":\"RPI\"}}"
284+
+ f"}}",
285+
qos=1,
286+
retain=True,
287+
)
288+
mqttClient.publish(
289+
topic=f"homeassistant/sensor/{deviceName}/{deviceName}PowerStatus/config",
290+
payload='',
316291
qos=1,
317292
retain=True,
318293
)
@@ -349,7 +324,7 @@ def send_config_message(mqttClient):
349324
if "check_available_updates" in settings and settings["check_available_updates"]:
350325
# import apt
351326
if(apt_disabled):
352-
print("import of apt failed!")
327+
write_message_to_console("import of apt failed!")
353328
else:
354329
mqttClient.publish(
355330
topic=f"homeassistant/sensor/{deviceName}/{deviceName}Updates/config",
@@ -410,10 +385,10 @@ def _parser():
410385

411386
def on_connect(client, userdata, flags, rc):
412387
if rc == 0:
413-
print("Connected to broker")
388+
write_message_to_console("Connected to broker")
414389
client.subscribe("hass/status")
415390
else:
416-
print("Connection failed")
391+
write_message_to_console("Connection failed")
417392

418393

419394
if __name__ == "__main__":
@@ -443,7 +418,8 @@ def on_connect(client, userdata, flags, rc):
443418
try:
444419
send_config_message(mqttClient)
445420
except:
446-
print("something whent wrong")
421+
write_message_to_console("something whent wrong")
422+
_underVoltage = new_under_voltage()
447423
job = Job(interval=timedelta(seconds=WAIT_TIME_SECONDS), execute=updateSensors)
448424
job.start()
449425

@@ -454,11 +430,10 @@ def on_connect(client, userdata, flags, rc):
454430
sys.stdout.flush()
455431
time.sleep(1)
456432
except ProgramKilled:
457-
print("Program killed: running cleanup code")
433+
write_message_to_console("Program killed: running cleanup code")
458434
mqttClient.publish(f"system-sensors/sensor/{deviceName}/availability", "offline", retain=True)
459435
mqttClient.disconnect()
460436
mqttClient.loop_stop()
461437
sys.stdout.flush()
462438
job.stop()
463439
break
464-

0 commit comments

Comments
 (0)