Skip to content

Instantly share code, notes, and snippets.

@pepitooo
Created May 4, 2021 10:02
Show Gist options
  • Save pepitooo/ed9093b68469d6eee7c54b6f2c3742d2 to your computer and use it in GitHub Desktop.
Save pepitooo/ed9093b68469d6eee7c54b6f2c3742d2 to your computer and use it in GitHub Desktop.
Post lm-sensor to HASS
#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
from urllib import parse
from requests import post
def get_sensors_data():
sensors_data = subprocess.check_output("/usr/bin/sensors -j", shell=True)
return json.loads(sensors_data)
def post_to_hass(hass_url, hass_api, states_root_key, data, dry_run=False, print_hass_config=False):
if print_hass_config:
dry_run = True
hass = parse.urlparse(hass_url)
headers = {
"Authorization": f"Bearer {hass_api}",
"content-type": "application/json"
}
# for configurations.yaml purposes
if print_hass_config:
print("input_number:")
for interface_name in data:
interface_values = data[interface_name]
for sensor in interface_values:
if isinstance(data[interface_name][sensor], dict) and isinstance(sensor, str):
# for configurations.yaml purposes
has_value = False
has_min = False
has_max = False
for sensor_name in data[interface_name][sensor]:
if sensor_name.endswith('_input') or sensor_name.endswith('_average'):
# print(f"{interface_name}_{sensor_name}:{data[interface_name][sensor][sensor_name]}")
hass_interface_name = interface_name.replace('-', '_')
hass_sensor_name = sensor_name.replace('-', '_')
# for configurations.yaml purposes
has_value = True
if print_hass_config:
print(f" {states_root_key}_{hass_interface_name}_{hass_sensor_name}:")
print(f" name: {sensor}")
else:
url = hass._replace(path=f"/api/states/input_number.{states_root_key}_{hass_interface_name}_{hass_sensor_name}").geturl()
state = dict(state=data[interface_name][sensor][sensor_name])
if not dry_run:
post(url, headers=headers, json=state, verify=False)
else:
print(url)
print(state)
# for configurations.yaml purposes
if print_hass_config and sensor_name.endswith('_min'):
has_min = True
print(f" min: {data[interface_name][sensor][sensor_name]}")
# for configurations.yaml purposes
if print_hass_config and sensor_name.endswith('_max') and float(data[interface_name][sensor][sensor_name]) > 0:
has_max = True
print(f" max: {data[interface_name][sensor][sensor_name]}")
# for configurations.yaml purposes
if print_hass_config and has_value and not has_min:
print(" min: 0")
# for configurations.yaml purposes
if print_hass_config and has_value and not has_max:
print(" max: 20000")
def parse_args(args):
"""
Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace`
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-u', '--url', dest='hass_url', help='url to homeassistant ex: http://192.168.0.35:8123', required=True)
parser.add_argument(
'-a', '--api', dest='hass_api_key', help="API key, Long-lived access token", required=True)
parser.add_argument(
'-s', '--states_root_key', dest='states_root_key', help="where it will be send to hass", required=True)
parser.add_argument(
'-d', '--dry_run', action='store_true', help="don't post data to hass")
parser.add_argument(
'-c', '--print_hass_config', action='store_true', help="print home assistant config for configuration.yaml ")
return parser.parse_args(args)
def main(args):
args_parsed = parse_args(args)
sensors_data = get_sensors_data()
post_to_hass(args_parsed.hass_url, args_parsed.hass_api_key, args_parsed.states_root_key, sensors_data,
args_parsed.dry_run, args_parsed.print_hass_config)
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment