|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | + |
| 4 | +"""OpenKnot Broker Daemon""" |
| 5 | + |
| 6 | + |
| 7 | +from __future__ import print_function |
| 8 | + |
| 9 | + |
| 10 | +import os |
| 11 | +import sys |
| 12 | +import logging |
| 13 | +from os import environ |
| 14 | +from logging import getLogger |
| 15 | +from json import dumps, loads |
| 16 | +from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser |
| 17 | + |
| 18 | + |
| 19 | +from circuits.web import Controller, Server |
| 20 | +from circuits import handler, Component, Debugger |
| 21 | + |
| 22 | + |
| 23 | +from .events import message |
| 24 | +from .mqtt import mqtt, MQTT |
| 25 | +from .utils import parse_bind, waitfor |
| 26 | + |
| 27 | + |
| 28 | +def setup_logging(args): |
| 29 | + logstream = sys.stderr if args.logfile is None else open(args.logfile, "a") |
| 30 | + |
| 31 | + logging.basicConfig( |
| 32 | + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", |
| 33 | + level=logging.DEBUG if args.debug else logging.INFO, |
| 34 | + stream=logstream, |
| 35 | + ) |
| 36 | + |
| 37 | + return getLogger(__name__) |
| 38 | + |
| 39 | + |
| 40 | +def setup_mqtt(args, logger): |
| 41 | + host, port = parse_bind(args.url) |
| 42 | + |
| 43 | + logger.debug("Waiting for MQTT Service on {0:s}:{1:d} ...".format(host, port)) |
| 44 | + |
| 45 | + if not waitfor(host, port): |
| 46 | + logger.error("Timed out waiting for MQTT Service on {0:s}:{1:d} ...".format(host, port)) |
| 47 | + raise SystemExit(1) |
| 48 | + |
| 49 | + |
| 50 | +class JSONSerializer(Component): |
| 51 | + |
| 52 | + channel = "web" |
| 53 | + |
| 54 | + # 1 higher than the default response handler |
| 55 | + @handler("response", priority=1.0) |
| 56 | + def serialize_response_body(self, response): |
| 57 | + if isinstance(response.body, dict): |
| 58 | + response.headers["Content-Type"] = "application/json" |
| 59 | + response.body = dumps(response.body) |
| 60 | + |
| 61 | + |
| 62 | +class Dispatcher(Component): |
| 63 | + |
| 64 | + def message(self, payload): |
| 65 | + protocol = payload.get("protocol", "unknown") |
| 66 | + |
| 67 | + self.fire(mqtt(protocol, payload)) |
| 68 | + |
| 69 | + |
| 70 | +class API(Controller): |
| 71 | + |
| 72 | + channel = "/message" |
| 73 | + |
| 74 | + def POST(self, event, *args, **kwargs): |
| 75 | + req, res = event.args[:2] |
| 76 | + payload = loads(req.body.read()) |
| 77 | + |
| 78 | + self.fire(message(payload)) |
| 79 | + |
| 80 | + return {"success": True} |
| 81 | + |
| 82 | + |
| 83 | +class App(Component): |
| 84 | + |
| 85 | + def init(self, args): |
| 86 | + self.args = args |
| 87 | + |
| 88 | + self.logger = getLogger(__name__) |
| 89 | + |
| 90 | + if self.args.debug: |
| 91 | + Debugger().register(self) |
| 92 | + |
| 93 | + bind = parse_bind(self.args.bind) |
| 94 | + |
| 95 | + MQTT(args.url).register(self) |
| 96 | + |
| 97 | + Server(bind).register(self) |
| 98 | + JSONSerializer().register(self) |
| 99 | + |
| 100 | + API().register(self) |
| 101 | + |
| 102 | + def signal(self, *args): |
| 103 | + raise SystemExit(0) |
| 104 | + |
| 105 | + |
| 106 | +def parse_args(): |
| 107 | + parser = ArgumentParser( |
| 108 | + description=__doc__, |
| 109 | + formatter_class=ArgumentDefaultsHelpFormatter |
| 110 | + ) |
| 111 | + |
| 112 | + parser.add_argument( |
| 113 | + "-b", "--bind", action="store", dest="bind", metavar="INT", type=str, |
| 114 | + default=environ.get("BIND", "0.0.0.0:80"), |
| 115 | + help="Interface and Port to Bind to" |
| 116 | + ) |
| 117 | + |
| 118 | + parser.add_argument( |
| 119 | + "-d", "--debug", action="store_true", dest="debug", |
| 120 | + default=environ.get("DEBUG", False), |
| 121 | + help="Enable Debug Mode" |
| 122 | + ) |
| 123 | + |
| 124 | + parser.add_argument( |
| 125 | + "-l", "--logfile", action="store", default=None, |
| 126 | + dest="logfile", metavar="FILE", type=str, |
| 127 | + help="Log file to store logs in" |
| 128 | + ) |
| 129 | + |
| 130 | + parser.add_argument( |
| 131 | + "-u", "--url", action="store", dest="url", metavar="URL", type=str, |
| 132 | + default=environ.get("MQTT_PORT", environ.get("URL", None)), required=True, |
| 133 | + help="MQTT URL" |
| 134 | + ) |
| 135 | + |
| 136 | + return parser.parse_args() |
| 137 | + |
| 138 | + |
| 139 | +def main(): |
| 140 | + sys.stdout = os.fdopen(sys.stdout.fileno(), "w", 0) |
| 141 | + |
| 142 | + args = parse_args() |
| 143 | + |
| 144 | + logger = setup_logging(args) |
| 145 | + |
| 146 | + setup_mqtt(args, logger) |
| 147 | + |
| 148 | + App(args).run() |
| 149 | + |
| 150 | + |
| 151 | +if __name__ == "__main__": |
| 152 | + main() |
0 commit comments