Weiterarbeit Users, Server implementier für Config-Data austausch, Data funktioniert noch nicht korrekt
This commit is contained in:
20
server/config/BasToken.json
Normal file
20
server/config/BasToken.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"metadata":{"config_has_changed" : "1"},
|
||||
"users": [
|
||||
{"type": "User1", "config": {"ID":"Umod1","user_prio":1,"lock_prio":2}},
|
||||
{"type": "User1", "config": {"ID":"Umod3","user_prio":3,"lock_prio":4}},
|
||||
{"type": "User1", "config": {"ID":"Umod2.0","user_prio":2,"lock_prio":3}},
|
||||
{"type": "User1", "config": {"ID":"Umod2.1","user_prio":2,"lock_prio":3}},
|
||||
{"type": "User1", "config": {"ID":"Umod2.2","user_prio":2,"lock_prio":3}},
|
||||
{"type": "User1", "config": {"ID":"Umod2.3","user_prio":2,"lock_prio":3}},
|
||||
{"type": "User2", "config": {"ID":"Usta2.0","user_prio":2,"lock_prio":6}},
|
||||
{"type": "Boiler_1Stufig_Shelly", "config": {"ID":"shelly_Boiler","user_prio":2,"lock_prio":6, "shelly_ip" : "192.168.20.233", "boilerpower": 5000, "temperatur": 38}}
|
||||
],
|
||||
"producers": [
|
||||
{"type": "Fronius", "config": {"ID":"Fronius_15kW","IP":"192.168.20.51","Adr":1}},
|
||||
{"type": "Fronius", "config": {"ID":"Fronius_20kW","IP":"192.168.20.51","Adr":2}}
|
||||
],
|
||||
"meters": [
|
||||
{"type": "Fronius", "config": {"ID":"Meter_Fronius","IP":"192.168.20.51","Adr":1}}
|
||||
]
|
||||
}
|
||||
1
server/data/BasToken.json
Normal file
1
server/data/BasToken.json
Normal file
File diff suppressed because one or more lines are too long
42
server/json_merger.py
Normal file
42
server/json_merger.py
Normal file
@@ -0,0 +1,42 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Thu Apr 18 17:13:06 2024
|
||||
|
||||
@author: dh
|
||||
"""
|
||||
def merge_json(old_json, new_json):
|
||||
if not isinstance(old_json, dict) or not isinstance(new_json, dict):
|
||||
return old_json
|
||||
|
||||
for key, value in new_json.items():
|
||||
if key not in old_json:
|
||||
old_json[key] = value
|
||||
elif isinstance(value, list):
|
||||
if key not in old_json:
|
||||
old_json[key] = []
|
||||
if key == "timestamps":
|
||||
for item in value:
|
||||
if item not in old_json[key]:
|
||||
old_json[key].append(item)
|
||||
else:
|
||||
old_json[key].extend(value)
|
||||
elif isinstance(value, dict):
|
||||
old_json[key] = merge_json(old_json.get(key, {}), value)
|
||||
else:
|
||||
old_json[key] = value
|
||||
|
||||
return old_json
|
||||
|
||||
# Beispielaufruf
|
||||
old_json = {
|
||||
"timestamps": ["s", "e", "r"],
|
||||
"data": {"foo": [1, 2, 4], "bar": [3, 4, 6]}
|
||||
}
|
||||
|
||||
new_json = {
|
||||
"timestamps": ["r", "p"],
|
||||
"data": {"foo": [4,5], "bar": [6,7]}
|
||||
}
|
||||
|
||||
merged_json = merge_json(old_json, new_json)
|
||||
print(merged_json)
|
||||
154
server/main.py
154
server/main.py
@@ -1,56 +1,124 @@
|
||||
from flask import Flask, request, jsonify, abort
|
||||
from flask import Flask, request, jsonify
|
||||
import os
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
TOKENS_FILE = "tokens.txt"
|
||||
CONFIG_DIR = "configs"
|
||||
|
||||
# Route to get configuration
|
||||
@app.route('/getconfig', methods=['POST'])
|
||||
def get_config():
|
||||
# Überprüfe, ob die erforderlichen Daten im Request vorhanden sind
|
||||
if not request.json or 'token' not in request.json or 'data' not in request.json:
|
||||
abort(400, 'Bad request. JSON data with "token" and "data" is required.')
|
||||
try:
|
||||
token_id = request.headers.get('ID')
|
||||
|
||||
if not token_id:
|
||||
return jsonify({'error': 'Token ID is missing'}), 400
|
||||
|
||||
token = request.json['token']
|
||||
data = request.json['data']
|
||||
config_file = os.path.join('config', f'{token_id}.json')
|
||||
|
||||
# Überprüfe, ob der Token gültig ist
|
||||
if not is_valid_token(token):
|
||||
abort(401, 'Unauthorized. Invalid token.')
|
||||
if not os.path.exists(config_file):
|
||||
return jsonify({'error': 'Config not found for the specified token'}), 404
|
||||
|
||||
# Speichere die Daten in einem Datei für das entsprechende Token
|
||||
save_data(token, data)
|
||||
|
||||
# Lade die Konfigurationsdatei für das Token
|
||||
config = load_config(token)
|
||||
|
||||
return jsonify(config)
|
||||
|
||||
def is_valid_token(token):
|
||||
# Überprüfe, ob der Token in der tokens.txt Datei vorhanden ist
|
||||
with open(TOKENS_FILE, 'r') as file:
|
||||
tokens = file.read().splitlines()
|
||||
return token in tokens
|
||||
|
||||
def save_data(token, data):
|
||||
# Erstelle das Verzeichnis für die Konfigurationsdateien, falls es nicht existiert
|
||||
if not os.path.exists(CONFIG_DIR):
|
||||
os.makedirs(CONFIG_DIR)
|
||||
|
||||
# Speichere die Daten in einer Datei für das entsprechende Token
|
||||
with open(os.path.join(CONFIG_DIR, f'{token}.json'), 'w') as file:
|
||||
file.write(jsonify(data))
|
||||
|
||||
def load_config(token):
|
||||
config_file = os.path.join(CONFIG_DIR, f'{token}.json')
|
||||
|
||||
# Lade die Konfigurationsdatei für das Token
|
||||
if os.path.exists(config_file):
|
||||
with open(config_file, 'r') as file:
|
||||
return json.load(file)
|
||||
config = json.load(file)
|
||||
|
||||
|
||||
data_file = os.path.join('config', f'{token_id}.json')
|
||||
|
||||
with open(data_file, 'r') as file:
|
||||
data = json.load(file)
|
||||
# Extract and include last timestamp in the response
|
||||
try:
|
||||
config['last_timestamp'] = data['timestamps'][len(data['timestamps'])-1]
|
||||
except:
|
||||
config['last_timestamp']=0
|
||||
return jsonify(config), 200
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
# Route to set new data
|
||||
|
||||
|
||||
|
||||
@app.route('/setdata', methods=['POST'])
|
||||
def set_data():
|
||||
# Token-ID aus den Request-Headern extrahieren
|
||||
token_id = request.headers.get('ID')
|
||||
|
||||
# Neue Daten aus den Request-Headern laden
|
||||
new_data = request.headers.get('JSON')
|
||||
|
||||
try:
|
||||
# Versuche, das JSON zu laden
|
||||
new_data = json.loads(new_data)
|
||||
except json.JSONDecodeError:
|
||||
# Wenn das JSON nicht korrekt formatiert ist, schreibe das neue JSON in die Datei und beende die Funktion
|
||||
write_json_file(token_id, new_data)
|
||||
return 'Invalid JSON format. New JSON data has been written to the file and overwritten existing data.'
|
||||
|
||||
# Pfad zum Datenordner und Datei für die Token-ID erstellen
|
||||
data_folder = 'data'
|
||||
file_path = os.path.join(data_folder, f'{token_id}.json')
|
||||
|
||||
# Überprüfen, ob die Datei existiert und Daten enthält
|
||||
if os.path.exists(file_path) and os.path.getsize(file_path) > 0:
|
||||
# Bestehende Daten aus der Datei laden
|
||||
with open(file_path, 'r') as file:
|
||||
existing_data = json.load(file)
|
||||
|
||||
# Merge der beiden JSON-Objekte
|
||||
merged_data = merge_json(existing_data, new_data)
|
||||
else:
|
||||
return {}
|
||||
# Wenn die Datei nicht existiert oder leer ist, neue Daten verwenden
|
||||
merged_data = new_data
|
||||
|
||||
# Daten in die Datei schreiben
|
||||
with open(file_path, 'w') as file:
|
||||
json.dump(merged_data, file)
|
||||
|
||||
return 'Data successfully set!'
|
||||
|
||||
def write_json_file(token_id, new_data):
|
||||
"""
|
||||
Funktion zum Schreiben von JSON-Daten in eine Datei.
|
||||
"""
|
||||
# Pfad zum Datenordner und Datei für die Token-ID erstellen
|
||||
data_folder = 'data'
|
||||
file_path = os.path.join(data_folder, f'{token_id}.json')
|
||||
|
||||
# Neue Daten in die Datei schreiben
|
||||
with open(file_path, 'w') as file:
|
||||
json.dump(new_data, file)
|
||||
|
||||
def merge_json(old_json, new_json):
|
||||
if not isinstance(old_json, dict) or not isinstance(new_json, dict):
|
||||
return old_json
|
||||
|
||||
for key, value in new_json.items():
|
||||
if key not in old_json:
|
||||
old_json[key] = value
|
||||
elif isinstance(value, list):
|
||||
if key not in old_json:
|
||||
old_json[key] = []
|
||||
if key == "timestamps":
|
||||
for item in value:
|
||||
if item not in old_json[key]:
|
||||
old_json[key].append(item)
|
||||
else:
|
||||
old_json[key].extend(value)
|
||||
elif isinstance(value, dict):
|
||||
old_json[key] = merge_json(old_json.get(key, {}), value)
|
||||
else:
|
||||
old_json[key] = value
|
||||
|
||||
return old_json
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
app.run(debug=False)
|
||||
|
||||
Reference in New Issue
Block a user