From 452887540cb3e92565111017a11ee4b85fbb0188 Mon Sep 17 00:00:00 2001 From: "M.J. Wydra (Jay)" Date: Fri, 4 Dec 2020 20:26:50 -0600 Subject: [PATCH] Initial commit --- Dockerfile | 8 ++++++++ battery2mqtt.py | 43 +++++++++++++++++++++++++++++++++++++++++++ docker-compose.yaml | 14 ++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 Dockerfile create mode 100644 battery2mqtt.py create mode 100644 docker-compose.yaml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1e48349 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,8 @@ +FROM python:3-alpine +MAINTAINER Tediore + +ADD battery2mqtt.py / + +RUN pip install paho.mqtt + +CMD [ "python", "./battery2mqtt.py" ] \ No newline at end of file diff --git a/battery2mqtt.py b/battery2mqtt.py new file mode 100644 index 0000000..da43311 --- /dev/null +++ b/battery2mqtt.py @@ -0,0 +1,43 @@ +import os +import json +from time import sleep +import paho.mqtt.client as mqtt + +MQTT_HOST = os.getenv('MQTT_HOST') +MQTT_PORT = int(os.getenv('MQTT_PORT', 1883)) +MQTT_USER = os.getenv('MQTT_USER') +MQTT_PASSWORD = os.getenv('MQTT_PASSWORD') +MQTT_QOS = int(os.getenv('MQTT_QOS', 1)) +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') + +client = mqtt.Client("battery2mqtt") +client.username_pw_set(MQTT_USER, MQTT_PASSWORD) + +monitored_conditions = MONITORED_CONDITIONS.split(',') + +path = "/sys/class/power_supply" + +dirs = os.listdir(path) + +payload = {} + +while True: + for dir in dirs: + for name in monitored_conditions: + try: + with open(path + '/' + dir + '/' + name, 'r') as file: + if name in ['alarm', 'capacity', 'present']: + payload[name] = int(file.read().replace('\n','')) + elif 'voltage' in name: + payload[name] = round(float(file.read().replace('\n','')) / 1000000,2) + else: + payload[name] = file.read().replace('\n','') + except: + payload[name] = "condition not found" + + client.connect(MQTT_HOST) + client.publish("battery2mqtt/" + MQTT_TOPIC + '/' + dir, json.dumps(payload), qos=MQTT_QOS, retain=False) + + sleep(INTERVAL) diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..bf98730 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,14 @@ + battery2mqtt: + container_name: battery2mqtt + image: battery2mqtt:latest + environment: + - MQTT_HOST=10.0.0.2 + - MQTT_PORT=1883 + - MQTT_USER=user + - MQTT_PASSWORD=password + - MQTT_QOS=1 + - INTERVAL=60 + - MONITORED_CONDITIONS=status,capacity + volumes: + - /sys/class/power_supply:/sys/class/power_supply:ro + restart: unless-stopped