69 lines
2.0 KiB
Python
Executable File
69 lines
2.0 KiB
Python
Executable File
#! /usr/bin/env python3
|
|
|
|
import socket
|
|
import signal
|
|
import asyncio
|
|
from dataclasses import dataclass
|
|
import aiohttp
|
|
|
|
from mqtthandler.command import command
|
|
from mqtthandler.handler import MQTTConfig, MQTTHandler, task
|
|
|
|
|
|
@dataclass
|
|
class MediaMTXConfig:
|
|
host: str = "http://localhost"
|
|
metrics_path: str = ":9998/metrics"
|
|
username: str | None = "admin"
|
|
password: str | None = "admin"
|
|
|
|
|
|
class MediaMTXHandler(MQTTHandler):
|
|
def __init__(
|
|
self,
|
|
mqtt_config: MQTTConfig,
|
|
handler_id: str,
|
|
mediamtx_config: MediaMTXConfig,
|
|
):
|
|
super().__init__(mqtt_config, handler_id)
|
|
self.config = mediamtx_config
|
|
|
|
@task
|
|
async def retrieve_metrics(self):
|
|
cache = {}
|
|
|
|
while True:
|
|
auth = aiohttp.BasicAuth(login=self.config.username, password=self.config.password)
|
|
async with aiohttp.ClientSession(auth=auth) as session:
|
|
while True:
|
|
async with session.get(f"{self.config.host}{self.config.metrics_path}") as r:
|
|
metrics = await r.text()
|
|
|
|
for line in metrics.split("\n")[:-1]:
|
|
metric, value = line.split(" ")
|
|
topic = metric.replace("_", "/")
|
|
full_topic = f"{self.property_topic}/{topic}"
|
|
|
|
if cache.get(full_topic) != value:
|
|
cache[full_topic] = value
|
|
await self.mqtt_client.publish(full_topic, value, retain=True)
|
|
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
print("Connection dropped!")
|
|
await asyncio.sleep(10)
|
|
|
|
|
|
async def main():
|
|
handler_id = f"mediamtx-{socket.gethostname()}"
|
|
mqtt_config = MQTTConfig(host="127.0.0.1")
|
|
handler = MediaMTXHandler(mqtt_config, handler_id, MediaMTXConfig())
|
|
|
|
signal.signal(signal.SIGINT, lambda signum, frame: handler.stop())
|
|
await handler.run()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|