diff --git a/src/nightserver.py b/src/nightserver.py index fe1b8c2..4c4cf70 100644 --- a/src/nightserver.py +++ b/src/nightserver.py @@ -1,8 +1,17 @@ from flask import Flask, render_template, jsonify, request +from flask_apscheduler import APScheduler from copy import copy import uuid +import time +import requests + + app = Flask(__name__) +# UUID used for internal calls. +internalUUID = str(uuid.uuid4()) + + # Vitals vitalsHeartrate = None vitalsOxygen = None @@ -427,6 +436,10 @@ def setEnvironmentHumidity(): # allowed to set the requested endpoint. # This is ONLY used for PUSH requests currently. def authenticate(uuid, endpoint): + # Check for internal UUID + if uuid == internalUUID: + return True + for c in cyberware: # UUID Match if c['uuid'] == uuid: requestedHardware = c @@ -444,3 +457,72 @@ def authenticate(uuid, endpoint): @app.route('/') def uiindex(): return render_template('index.html') + + +# Maintenance functions +# The jank, my oh my +valuesToValidate = [ '/api/vitals/heartrate', '/api/vitals/oxygen', '/api/vitals/bodytemp', + '/api/fitness/steps', + '/api/environment/temperature', '/api/environment/humidity'] +baseURL = "http://localhost:5000" +# Value invalidation. A value is deemed invalid when there's no hardware attached +# that can set it. +# This has the potential to become very slow. A better solution is needed. +def valueInvalidation(): + print("Start value invalidation") + + # Search for invalid values + invalidated = copy(valuesToValidate) + for c in cyberware: + for value in valuesToInvalidate: + if value in c["canSet"]: + invalidated.remove(value) + + # Value invalidation begins + invalidStr = "" + for invalidValue in invalidated: + # Now this looks stupid, but since the key to post is always supposed to be the same + # as the last part of the path, this works. + # Does that make sense? I'm tired... + key = invalidValue.split('/')[-1] + + endpointToReset = baseURL + invalidValue + + requests.post(endpointToReset, json={ key: None, 'uuid': internalUUID }) + invalidStr = invalidStr + invalidValue + ", " + + print("Values invalidated: " + invalidStr) + +# Device invalidation. A device is deemed invalid after no contact for 15 seconds. +def deviceInvalidation(): + print("Device invalidation not implemented") + + +# APScheduler config +class Config: + JOBS = [ + { + "id": "valueInvalidation", + "func": "nightserver:valueInvalidation", + "trigger": "interval", + "seconds": 10, + }, + { + "id": "deviceInvalidation", + "func": "nightserver:deviceInvalidation", + "trigger": "interval", + "seconds": 15 + } + ] + + SCHEDULER_API_ENABLED = True + +# Config Flask and APScheduler +app.config.from_object(Config()) + +scheduler = APScheduler() + +scheduler.init_app(app) +scheduler.start() + +app.run()