Skip to content
app.py 1.91 KiB
Newer Older
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""API server, with a web client for free"""
Davide Ricci's avatar
Davide Ricci committed
import time
Davide Ricci's avatar
Davide Ricci committed
import logging
Davide Ricci's avatar
Davide Ricci committed
from flask import Flask, request
Davide Ricci's avatar
Davide Ricci committed
from flask_cors import CORS
from api import api_blueprint as api
Davide Ricci's avatar
Davide Ricci committed
from web.server import instance
app.register_blueprint(api, url_prefix='/api')
app.threaded = True
Davide Ricci's avatar
Davide Ricci committed
cors = CORS(app)

@app.route('/all/<string:namespace>')
def get_status(namespace):
Davide Ricci's avatar
Davide Ricci committed
    '''Build a global status for a given namespace'''
Davide Ricci's avatar
Davide Ricci committed
    wait = float(request.args.get('wait', 0))

    # Check for ping before going to all others
    power = f"/api/{namespace}/ping"
    with app.test_client() as client:
        res = client.get(power)
        name = "-".join(power.split("/")[2:]) # "dome-shutter-movement"
        endpoints[name] = res.get_json()
        if not res.get_json()["response"]:            
            return endpoints
    
    for rule in app.url_map.iter_rules():
        if rule.rule.startswith(f"/api/{namespace}/"): # "/api/dome/shutter/movement"
            if "GET" in rule.methods:
                with app.test_client() as client:
                    res = client.get(rule.rule)
                    name = "-".join(rule.rule.split("/")[2:]) # "dome-shutter-movement"
                    endpoints[name] = res.get_json()
Davide Ricci's avatar
Davide Ricci committed
                    time.sleep(wait)
Davide Ricci's avatar
Davide Ricci committed

if __name__ == "__main__":
vertighel's avatar
vertighel committed

    with_web = True
        arg = sys.argv[1]
        if arg.startswith("--noweb"):
            with_web = False
            port = 5533
        else:
            port = arg
    except IndexError as e:
Davide Ricci's avatar
Davide Ricci committed

    hostname = "0.0.0.0"
Davide Ricci's avatar
Davide Ricci committed

    if with_web:
        socketio = instance.enable(app)
        socketio.run(app, host=hostname, port=port)
        app.run(host=hostname, port=port)