Skip to content

Commit

Permalink
Merge branch 'master' into updates
Browse files Browse the repository at this point in the history
  • Loading branch information
mmattel authored Mar 23, 2024
2 parents f370231 + fae97d7 commit d887b32
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 38 deletions.
62 changes: 41 additions & 21 deletions src/sensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@
import sys
import os
import shutil
import json
# import os.path

class ProperyBag(dict):
class PropertyBag(dict):
def to_string(self, device_name:str):
return str.replace(str.replace(str.replace(self.__str__(), "{device_name}", device_name), "{", ''), "}", '')
for key in self.keys():
self[key] = str.replace(self[key], "{device_name}", device_name)
return str.replace(str.replace(json.dumps(self), "{", ''), "}", '')

# Only needed if using alternate method of obtaining CPU temperature (see commented out code for approach)
#from os import walk
Expand Down Expand Up @@ -56,8 +59,10 @@ def to_string(self, device_name:str):
row = line.strip().split("=")
OS_DATA[row[0]] = row[1].strip('"')

old_net_data = psutil.net_io_counters()
previous_time = time.time() - 10
old_net_data_tx = psutil.net_io_counters()[0]
previous_time_tx = time.time() - 10
old_net_data_rx = psutil.net_io_counters()[1]
previous_time_rx = time.time() - 10
UTC = pytz.utc
DEFAULT_TIME_ZONE = None

Expand Down Expand Up @@ -176,19 +181,37 @@ def get_memory_usage():
def get_load(arg):
return round(psutil.getloadavg()[arg] / psutil.cpu_count() * 100, 1)

def get_net_data(arg):
global old_net_data
global previous_time
current_net_data = psutil.net_io_counters()
def get_net_data_tx(interface = True):
global old_net_data_tx
global previous_time_tx
current_net_data = []
if type(interface) == str:
current_net_data = psutil.net_io_counters(pernic=True)[interface][0]
else:
current_net_data = psutil.net_io_counters()[0]
current_time = time.time()
if current_time == previous_time_tx:
current_time += 1
net_data = (current_net_data - old_net_data_tx) * 8 / (current_time - previous_time_tx) / 1024
previous_time_tx = current_time
old_net_data_tx = current_net_data
return f"{net_data:.2f}"

def get_net_data_rx(interface = True):
global old_net_data_rx
global previous_time_rx
current_net_data = []
if type(interface) == str:
current_net_data = psutil.net_io_counters(pernic=True)[interface][1]
else:
current_net_data = psutil.net_io_counters()[1]
current_time = time.time()
if current_time == previous_time:
if current_time == previous_time_rx:
current_time += 1
net_data = (current_net_data[0] - old_net_data[0]) / (current_time - previous_time) * 8 / 1024
net_data = (net_data, (current_net_data[1] - old_net_data[1]) / (current_time - previous_time) * 8 / 1024)
previous_time = current_time
old_net_data = current_net_data
net_data = ['%.2f' % net_data[0], '%.2f' % net_data[1]]
return net_data[arg]
net_data = (current_net_data - old_net_data_rx) * 8 / (current_time - previous_time_rx) / 1024
previous_time_rx = current_time
old_net_data_rx = current_net_data
return f"{net_data:.2f}"

def get_cpu_usage():
return str(psutil.cpu_percent(interval=None))
Expand Down Expand Up @@ -320,11 +343,8 @@ def zpool_base(pool) -> dict:
'icon': 'monitor',
'sensor_type': 'switch',
'function': get_display_status,
'prop': ProperyBag({
'availability_topic' : "system-sensors/sensor/{device_name}/availability",
'prop': PropertyBag({
'command_topic' : 'system-sensors/sensor/{device_name}/command',
'state_topic' : 'system-sensors/sensor/{device_name}/state',
'value_template' : '{{value_json.display}}',
'state_off' : '0',
'state_on' : '1',
'payload_off' : 'display_off',
Expand Down Expand Up @@ -384,14 +404,14 @@ def zpool_base(pool) -> dict:
'unit': 'Kbps',
'icon': 'server-network',
'sensor_type': 'sensor',
'function': lambda: get_net_data(0)},
'function': get_net_data_tx},
'net_rx':
{'name': 'Network Download',
'state_class':'measurement',
'unit': 'Kbps',
'icon': 'server-network',
'sensor_type': 'sensor',
'function': lambda: get_net_data(1)},
'function': get_net_data_rx},
'swap_usage':
{'name':'Swap Usage',
'state_class':'measurement',
Expand Down
4 changes: 2 additions & 2 deletions src/settings_example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ sensors:
load_1m: true
load_5m: true
load_15m: true
net_tx: true
net_rx: true
net_tx: "enp1s0" # true for all interfaces, otherwise the name of the interface
net_rx: true # true for all interfaces, otherwise the name of the interface
swap_usage: true
power_status: true
last_boot: true
Expand Down
36 changes: 21 additions & 15 deletions src/system_sensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,14 @@ def update_sensors():
payload_str = f'{{'
for sensor, attr in sensors.items():
# Skip sensors that have been disabled or are missing
if sensor in external_drives or (settings['sensors'][sensor] is not None and settings['sensors'][sensor] == True):
if sensor in external_drives:
payload_str += f'"{sensor}": "{attr["function"]()}",'
elif settings['sensors'][sensor] is not None:
if settings['sensors'][sensor] == True:
payload_str += f'"{sensor}": "{attr["function"]()}",'
elif settings['sensors'][sensor] is not False:
payload_str += f'"{sensor}": "{attr["function"](settings["sensors"][sensor])}",'

payload_str = payload_str[:-1]
payload_str += f'}}'
mqttClient.publish(
Expand All @@ -73,20 +79,20 @@ def send_config_message(mqttClient):
mqttClient.publish(
topic=f'homeassistant/{attr["sensor_type"]}/{devicename}/{sensor}/config',
payload = (f'{{'
+ (f'"device_class":"{attr["class"]}",' if 'class' in attr else '')
+ (f'"state_class":"{attr["state_class"]}",' if 'state_class' in attr else '')
+ f'"name":"{deviceNameDisplay} {attr["name"]}",'
+ f'"state_topic":"system-sensors/sensor/{devicename}/state",'
+ (f'"unit_of_measurement":"{attr["unit"]}",' if 'unit' in attr else '')
+ f'"value_template":"{{{{value_json.{sensor}}}}}",'
+ f'"unique_id":"{devicename}_{attr["sensor_type"]}_{sensor}",'
+ f'"availability_topic":"system-sensors/sensor/{devicename}/availability",'
+ f'"device":{{"identifiers":["{devicename}_sensor"],'
+ f'"name":"{deviceNameDisplay} Sensors","model":"{deviceModel}", "manufacturer":"{deviceManufacturer}"}}'
+ (f',"icon":"mdi:{attr["icon"]}"' if 'icon' in attr else '')
+ (f',{attr["prop"]}' if 'prop' in attr else '')
+ f'}}'
),
+ (f'"device_class":"{attr["class"]}",' if 'class' in attr else '')
+ (f'"state_class":"{attr["state_class"]}",' if 'state_class' in attr else '')
+ f'"name":"{deviceNameDisplay} {attr["name"]}",'
+ f'"state_topic":"system-sensors/sensor/{devicename}/state",'
+ (f'"unit_of_measurement":"{attr["unit"]}",' if 'unit' in attr else '')
+ f'"value_template":"{{{{value_json.{sensor}}}}}",'
+ f'"unique_id":"{devicename}_{attr["sensor_type"]}_{sensor}",'
+ f'"availability_topic":"system-sensors/sensor/{devicename}/availability",'
+ f'"device":{{"identifiers":["{devicename}_sensor"],'
+ f'"name":"{deviceNameDisplay} Sensors","model":"{deviceModel}", "manufacturer":"{deviceManufacturer}"}}'
+ (f',"icon":"mdi:{attr["icon"]}"' if 'icon' in attr else '')
+ (f',{attr["prop"].to_string(devicename)}' if 'prop' in attr else '')
+ f'}}'
),
qos=1,
retain=True,
)
Expand Down

0 comments on commit d887b32

Please # to comment.