Skip to content

Instantly share code, notes, and snippets.

@andysmithfal
Created November 27, 2019 23:37
Show Gist options
  • Save andysmithfal/97eb32f8e51d0a92747fc74f6ce77268 to your computer and use it in GitHub Desktop.
Save andysmithfal/97eb32f8e51d0a92747fc74f6ce77268 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#script to publish drive usage stats over mqtt
#requires paho-mqtt library:
# $ apt-get install python3-pip
# $ pip3 install paho-mqtt
#
#run this script on cron as required
import shutil
import json
import paho.mqtt.publish as publish
mqtt_host = "127.0.0.1"
mqtt_port = 1883
mqtt_username = ""
mqtt_password = ""
enable_home_assistant_discovery = True
drives = {'boot':'/', 'storage_drive':'/mnt/hdd2tb1' }
messages = []
for name, path in drives.items():
total, used, free = shutil.disk_usage(path)
drive = {'total':(total // (2**30)), 'used': (used // (2**30)), 'free': (free // (2**30))}
topic = "home/server/driveUsage/{}".format(name)
msg = {'topic': topic, 'payload': json.dumps(drive), 'retain':False}
config = {'name':'Server Drive {}'.format(name), 'state_topic': topic, 'unit_of_measurement':'GB', 'value_template':'{{ value_json.free }}', 'json_attributes_topic': topic}
config_msg = {'topic':'homeassistant/sensor/{}/config'.format(name), 'payload':json.dumps(config), 'retain':True}
if enable_home_assistant_discovery:
messages.append(config_msg)
messages.append(msg)
if not mqtt_username:
publish.multiple(messages, hostname=mqtt_host, port=mqtt_port)
else:
publish.multiple(messages, hostname=mqtt_host, port=mqtt_port, auth = {'username':mqtt_username, 'password':mqtt_password})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment