diff --git a/README.md b/README.md index 99eebff..e55aed4 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ services: - INTERVAL=60 - MONITORED_CONDITIONS=status,capacity - BATTERY_HEALTH=1 + - TIME_REMAINING=1 volumes: - /sys/class/power_supply:/sys/class/power_supply:ro restart: unless-stopped @@ -59,8 +60,10 @@ You can specify only those conditions that you'd like to track. The default is t ``` alarm,capacity,capacity_level,present,status,voltage_now ``` -# Battery health calculation -The default is to also provide a battery health percentage calculation by dividing `energy_full` by `energy_full_design`. This can be disabled by setting `BATTERY_HEALTH` to `0` in your `docker-compose.yaml`. + +# Battery health and time remaining calculations +The default is to also provide a battery health percentage calculation by dividing `energy_full` by `energy_full_design`. This can be disabled by setting `BATTERY_HEALTH` to `0` in your `docker-compose.yaml`. +Similiarly, an estimate of time remaining on battery (in hours) is calculated by dividing `energy_now` by `power_now`. This can be disabled by setting `TIME_REMAINING` to `0` in your `docker-compose.yaml`. # Example Home Assistant configuration ```yaml diff --git a/battery2mqtt.py b/battery2mqtt.py index e6cc15e..6dfddd4 100644 --- a/battery2mqtt.py +++ b/battery2mqtt.py @@ -12,6 +12,7 @@ MQTT_TOPIC = os.getenv('MQTT_TOPIC', 'server') INTERVAL = int(os.getenv('INTERVAL', 60)) MONITORED_CONDITIONS = os.environ.get('MONITORED_CONDITIONS','alarm,capacity,capacity_level,present,status,voltage_now') BATTERY_HEALTH = os.getenv('BATTERY_HEALTH', 1) +TIME_REMAINING = os.getenv('TIME_REMAINING', 1) client = mqtt.Client("battery2mqtt") client.username_pw_set(MQTT_USER, MQTT_PASSWORD) @@ -24,6 +25,7 @@ dirs = os.listdir(path) payload = {} health_calc = {} +time_remaining = {} while True: for dir in dirs: @@ -44,10 +46,18 @@ while True: for name in ['energy_full_design', 'energy_full']: with open(path + dir + '/' + name, 'r') as file: health_calc[name] = int(file.read().replace('\n','')) - json.dumps(health_calc) payload['battery_health'] = round((health_calc['energy_full'] / health_calc['energy_full_design']) * 100,2) except: pass + + if TIME_REMAINING == '1': + try: + for name in ['energy_now', 'power_now']: + with open(path + dir + '/' + name, 'r') as file: + time_remaining[name] = int(file.read().replace('\n','')) + payload['time_remaining'] = round((time_remaining['energy_now'] / time_remaining['power_now']),2) + except: + pass client.connect(MQTT_HOST) client.publish("battery2mqtt/" + MQTT_TOPIC + '/' + dir, json.dumps(payload), qos=MQTT_QOS, retain=False)