#!/usr/bin/env python3 import sys import json import logging import sentry_sdk import pika import requests from sentry_sdk.integrations.logging import LoggingIntegration import config import uuid from mqtt_helper import MQTT """ Main entry point """ __author__ = "@tormakris" __copyright__ = "Copyright 2020, Birbnetes Team" __module_name__ = "app" __version__text__ = "1" if config.SENTRY_DSN: sentry_logging = LoggingIntegration( level=logging.DEBUG, # Capture info and above as breadcrumbs event_level=logging.ERROR # Send errors as events ) sentry_sdk.init( dsn=config.SENTRY_DSN, send_default_pii=True, integrations=[sentry_logging], release=config.RELEASE_ID, environment=config.RELEASEMODE ) def setup_rabbit(mqtt_: MQTT) -> None: logging.info("Connecting to RabbitMQ") credentials = pika.PlainCredentials(config.RABBIT_USERNAME, config.RABBIT_PASSWORD) connection = pika.BlockingConnection(pika.ConnectionParameters(host=config.RABBIT_HOSTNAME, credentials=credentials, heartbeat=0, socket_timeout=5)) channel = connection.channel() channel.exchange_declare(exchange=config.RABBIT_EXCHANGE, exchange_type='fanout') queue = channel.queue_declare(durable=True, auto_delete=True, queue=uuid.uuid4().urn.split(':')[2], exclusive=True).method.queue channel.queue_bind(exchange=config.RABBIT_EXCHANGE, queue=queue) channel.basic_consume(queue=queue, on_message_callback=on_message_creator(mqtt_), auto_ack=True) logging.debug("Starting consumption") channel.start_consuming() def on_message_creator(mqtt_: MQTT): """ This generator is used, so that the mqtt object can be injected just when the callback is registered """ def on_message(channel, method_frame, header_frame, body): msg_json = json.loads(body) if 'probability' not in msg_json: logging.error("Malformed message from broker") if msg_json['probability'] > 0.5: r = requests.get(f"http://{config.INPUT_HOSTNAME}/sample/{msg_json['tag']}") r.raise_for_status() if 'device_id' not in r.json(): logging.error("Input-service response invalid") logging.info(f"Sending alert command to device {r.json()['device_id']}") mqtt_.publish(subtopic=r.json()['device_id'], message=json.dumps({"command": "doAlert"})) return on_message if __name__ == "__main__": logging.basicConfig(stream=sys.stdout, format="%(asctime)s - %(name)s [%(levelname)s]: %(message)s", level=logging.DEBUG if '--debug' in sys.argv else logging.INFO) logging.info("Guard service starting") mqtt = MQTT() mqtt.topic = config.MQTT_TOPIC mqtt.connect() setup_rabbit(mqtt)