Skip to content

Commit

Permalink
Change attributes of disk usage
Browse files Browse the repository at this point in the history
Comment on code
Simplify JSON discovery code
  • Loading branch information
bkbilly committed Mar 7, 2023
1 parent cb1885c commit 4185084
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 22 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
__pycache__
config.yaml
*.egg-info
dist/
dist/
build/
42 changes: 29 additions & 13 deletions lnxlink/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,25 @@


class LNXlink():
client = mqtt.Client()
pref_topic = 'lnxlink'

def __init__(self, config_path):
print(f"LNXLink {version} started: {platform.python_version()}")

# Read configuration from yaml file
self.pref_topic = 'lnxlink'
self.config = self.read_config(config_path)

# Run each addon included in the modules folder
self.Addons = {}
for service, addon in modules.parse_modules(self.config['modules']).items():
self.Addons[addon.service] = addon(self)

# Setup MQTT
self.client = mqtt.Client()
self.setup_mqtt()

def monitor_run(self):
'''Gets information from each Addon and sends it to MQTT'''
if self.config['modules'] is not None:
for service in self.config['modules']:
addon = self.Addons[service]
Expand All @@ -55,13 +60,15 @@ def monitor_run(self):
traceback.print_exc()

def monitor_run_thread(self):
'''Runs method to get sensor information every prespecified interval'''
self.monitor_run()

interval = self.config.get('update_interval', 5)
interval = self.config.get('update_interval', 1)
self.monitor = threading.Timer(interval, self.monitor_run_thread)
self.monitor.start()

def setup_mqtt(self):
'''Creates the mqtt object'''
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
Expand All @@ -71,6 +78,7 @@ def setup_mqtt(self):
self.client.loop_start()

def read_config(self, config_path):
'''Reads the config file and prepares module names for import'''
with open(config_path) as file:
config = yaml.load(file, Loader=yaml.FullLoader)

Expand All @@ -82,6 +90,8 @@ def read_config(self, config_path):
return config

def on_connect(self, client, userdata, flags, rc):
'''Callback for MQTT connect which reports the connection status
back to MQTT server'''
print(f"Connected to MQTT with code {rc}")
client.subscribe(f"{self.pref_topic}/commands/#")
if self.config['mqtt']['lwt']['enabled']:
Expand All @@ -95,6 +105,7 @@ def on_connect(self, client, userdata, flags, rc):
self.setup_discovery()

def disconnect(self, *args):
'''Reports to MQTT server that the service has stopped'''
print("Disconnected from MQTT.")
if self.config['mqtt']['lwt']['enabled']:
self.client.publish(
Expand All @@ -110,6 +121,7 @@ def disconnect(self, *args):
self.client.disconnect()

def temp_connection_callback(self, status):
'''Report the connection status to MQTT server'''
if self.config['mqtt']['lwt']['enabled']:
if status:
self.client.publish(
Expand All @@ -127,6 +139,7 @@ def temp_connection_callback(self, status):
)

def on_message(self, client, userdata, msg):
'''MQTT message is received with a module command to excecute'''
topic = msg.topic.replace(f"{self.pref_topic}/commands/", "")
message = msg.payload
print(f"Message received: {topic}")
Expand All @@ -147,7 +160,8 @@ def on_message(self, client, userdata, msg):
except Exception as e:
traceback.print_exc()

def setup_discovery_monitoring(self, addon, service, discovery_template):
def setup_discovery_monitoring(self, discovery_template, addon, service):
'''Send discovery information on Home Assistant for sensors'''
subtopic = addon.name.lower().replace(' ', '/')
state_topic = f"{self.pref_topic}/{self.config['mqtt']['statsPrefix']}/{subtopic}"

Expand All @@ -157,14 +171,12 @@ def setup_discovery_monitoring(self, addon, service, discovery_template):
discovery['state_topic'] = state_topic
if addon.getInfo.__annotations__.get('return') == dict:
discovery['json_attributes_topic'] = state_topic
discovery['value_template'] = "{{ value_json.status }}"
discovery['json_attributes_template'] = "{{ value_json | tojson }}"
if hasattr(addon, 'icon'):
discovery['icon'] = addon.icon
if hasattr(addon, 'unit'):
if addon.unit == 'json':
discovery['value_template'] = "{{ value_json.status }}"
discovery['json_attributes_template'] = "{{ value_json | tojson }}"
else:
discovery['unit_of_measurement'] = addon.unit
discovery['unit_of_measurement'] = addon.unit
if hasattr(addon, 'title'):
discovery['title'] = addon.title
if hasattr(addon, 'entity_picture'):
Expand All @@ -180,8 +192,11 @@ def setup_discovery_monitoring(self, addon, service, discovery_template):
f"homeassistant/{sensor_type}/lnxlink/{discovery['unique_id']}/config",
payload=json.dumps(discovery),
retain=self.config['mqtt']['lwt']['retain'])
else:
print(f"Can't find sensor_type attribute for {discovery['name']}")

def setup_discovery_control(self, addon, service, control_name, options, discovery_template):
def setup_discovery_control(self, discovery_template, addon, service, control_name, options):
'''Send discovery information on Home Assistant for controls'''
subtopic = addon.name.lower().replace(' ', '/')
state_topic = f"{self.pref_topic}/{self.config['mqtt']['statsPrefix']}/{subtopic}"
discovery = discovery_template.copy()
Expand Down Expand Up @@ -215,6 +230,7 @@ def setup_discovery_control(self, addon, service, control_name, options, discove
retain=self.config['mqtt']['lwt']['retain'])

def setup_discovery(self):
'''First time setup of discovery for Home Assistant'''
discovery_template = {
"availability": {
"topic": f"{self.pref_topic}/lwt",
Expand All @@ -233,14 +249,14 @@ def setup_discovery(self):
addon = self.Addons[service]
if hasattr(addon, 'getInfo'):
try:
self.setup_discovery_monitoring(addon, service, discovery_template)
self.setup_discovery_monitoring(discovery_template, addon, service)
except Exception as e:
traceback.print_exc()
if hasattr(addon, 'exposedControls'):
for control_name, options in addon.exposedControls().items():
try:
control_name = control_name.lower().replace(' ', '_')
self.setup_discovery_control(addon, service, control_name, options, discovery_template)
self.setup_discovery_control(discovery_template, addon, service, control_name, options)
except Exception as e:
traceback.print_exc()

Expand All @@ -267,7 +283,7 @@ def main():
monitor_suspend.start()
monitor_gracefulkiller = GracefulKiller(lnxlink.temp_connection_callback)
while not monitor_gracefulkiller.kill_now:
time.sleep(1)
time.sleep(0.2)
monitor_suspend.stop()
lnxlink.disconnect()

Expand Down
2 changes: 1 addition & 1 deletion lnxlink/modules/battery.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def __init__(self, lnxlink):
self.sensor_type = 'sensor'
self.icon = 'mdi:battery'
self.device_class = 'battery'
self.unit = 'json'
self.unit = '%'

def getInfo(self) -> dict:
stdout = subprocess.run(
Expand Down
10 changes: 5 additions & 5 deletions lnxlink/modules/disk_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ def __init__(self, lnxlink):
self.name = 'Disk Usage'
self.sensor_type = 'sensor'
self.icon = 'mdi:harddisk'
self.unit = 'json'

def getInfo(self) -> dict:
disks = {"status": False}
for disk in psutil.disk_partitions():
if disk.fstype == 'squashfs':
continue
disks[disk.device] = {}
disk_stats = psutil.disk_usage(disk.mountpoint)
disks[f"total {disk.device}"] = self._bytetomb(disk_stats.total)
disks[f"used {disk.device}"] = self._bytetomb(disk_stats.used)
disks[f"free {disk.device}"] = self._bytetomb(disk_stats.free)
disks[f"percent {disk.device}"] = disk_stats.percent
disks[disk.device]["total"] = self._bytetomb(disk_stats.total)
disks[disk.device]["used"] = self._bytetomb(disk_stats.used)
disks[disk.device]["free"] = self._bytetomb(disk_stats.free)
disks[disk.device]["percent"] = disk_stats.percent
if disk_stats.percent > 80:
disks["status"] = True
return disks
Expand Down
1 change: 0 additions & 1 deletion lnxlink/modules/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ def __init__(self, lnxlink):
self.name = 'Media Info'
self.sensor_type = 'sensor'
self.icon = 'mdi:music'
self.unit = 'json'
self.players = []

def exposedControls(self):
Expand Down
1 change: 0 additions & 1 deletion lnxlink/modules/nvidia_gpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ def __init__(self, lnxlink):
self.name = 'Nvidia GPU'
self.sensor_type = 'sensor'
self.icon = 'mdi:expansion-card-variant'
self.unit = 'json'

def getInfo(self) -> dict:
stdout = subprocess.run(
Expand Down

0 comments on commit 4185084

Please sign in to comment.