APED_Device/app.py
2020-12-29 01:12:43 +01:00

61 lines
2.0 KiB
Python

#!/usr/bin/python3
from flask import request, send_from_directory
from flask_api import FlaskAPI
import RPi.GPIO as GPIO
import os
from xml_reader import Xml_reader
from interface_handler import Interface_handler
xml_reader = Xml_reader('XML/config.xml','XML/config.xsd')
interface_handler = Interface_handler(xml_reader)
device_names = xml_reader.get_device_names()
app = FlaskAPI(__name__)
@app.route('/', methods=["GET"])
def api_root():
return {
"device_url": request.url + "device/<device_name>",
"device_url_POST": {"output": "<value>"}
}
@app.route('/XML', methods=["GET","POST"])
def xml_transfer():
try:
#return the current config.xml
if request.method == "GET":
return send_from_directory('XML','config.xml')
# set a new config.xml
if request.method == "POST":
if 'config.xml' not in request.files:
raise ReferenceError("no file part")
file = request.files["config.xml"]
if file.filename != 'config.xml':
raise NameError("the file recieved does not have the filename config.xml")
file.save('/tmp/aped_device/config.xml')
#check config.xml against the XSD file
if xml_reader.validate('/tmp/aped_device/config.xml','XML/config.xsd'):
os.replace('XML/config.xml','XML/config_old.xml')
os.replace('/tmp/aped_device/config.xml','XML/config.xml')
else:
SyntaxError('the config.xml has invalid content')
except Exception as e:
return {'error' : str(e)}
@app.route('/device/<device_name>/', methods=["GET", "POST"])
def api_leds_control(device_name):
try:
if request.method == "POST":
response = interface_handler.write(device_name,request.data.get("output"))
return {'output': response}
return {'state': interface_handler.read(device_name)}
except Exception as e:
return {'error': str(e)}
if __name__ == "__main__":
app.run(port=8080,host="0.0.0.0")