feat: initial commit, first tests

This commit is contained in:
s3lph 2023-10-01 17:36:49 +02:00
commit d4387f6a2e
3 changed files with 78 additions and 0 deletions

8
config.yml Normal file
View file

@ -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/"

4
requirements.txt Normal file
View file

@ -0,0 +1,4 @@
loguru
paho-mqtt
requests
PyYAML

66
spaceapi-mqtt-aggregator.py Executable file
View file

@ -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()