commit d4387f6a2ef55278b92784ea4035aa631e0a1950 Author: s3lph Date: Sun Oct 1 17:36:49 2023 +0200 feat: initial commit, first tests diff --git a/config.yml b/config.yml new file mode 100644 index 0000000..7ec8db6 --- /dev/null +++ b/config.yml @@ -0,0 +1,8 @@ +--- + +log_level: INFO +mqtt_host: mqtt.lan.kabelsalat.ch +endpoints: + - "https://fixme.ch/cgi-bin/spaceapi.py" + - "https://spaceapi.kabelsalat.ch/" + - "https://status.crdmp.ch/" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3dc628c --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +loguru +paho-mqtt +requests +PyYAML diff --git a/spaceapi-mqtt-aggregator.py b/spaceapi-mqtt-aggregator.py new file mode 100755 index 0000000..2f01d8f --- /dev/null +++ b/spaceapi-mqtt-aggregator.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 + +import argparse +import json +import time +import sys + +import requests +import paho.mqtt.client as mqtt +import yaml + +from loguru import logger + + +class SpaceApiMqttAggregator: + + STATE_NAME_MAP = { + None: 'unknown', + True: 'open', + False: 'closed', + } + + STATE_NUM_MAP = { + None: -1, + True: 1, + False: 0, + } + + def __init__(self, ns): + with open(ns.config, 'r') as f: + config = yaml.safe_load(f) + logger.remove(0) + logger.add(sys.stderr, level=config.get('log_level', 'WARNING')) + self.mqtt_host = config.get('mqtt_host', 'localhost') + self.mqtt_port = config.get('mqtt_port', 1883) + self.interval = config.get('interval', 300) + self.endpoints = config.get('endpoints', []) + while True: + self.update() + time.sleep(self.interval) + + + def update(self): + client = mqtt.Client() + client.connect(self.mqtt_host, self.mqtt_port, 60) + + for i, e in enumerate(self.endpoints): + try: + j = requests.get(e).json() + space = j['space'] + state = j['state'].get('open') + logger.info(f'{e}: Space {space} is {self.STATE_NAME_MAP[state]}') + client.publish(f'spaceapi/{space}/state', self.STATE_NAME_MAP[state]) + client.publish(f'spaceapimap/{i}', self.STATE_NUM_MAP[state]) + except: + logger.exception(f'An error occurred while updating "{e}"') + + +def main(): + ap = argparse.ArgumentParser('spaceapi-mqtt-aggregator') + ap.add_argument('--config', default='config.yml', help='Path to the config file') + ns = ap.parse_args() + SpaceApiMqttAggregator(ns) + +if __name__ == '__main__': + main()