Weiterarbeit engine, main
This commit is contained in:
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -54,7 +54,7 @@ while True:
|
|||||||
for user in users:
|
for user in users:
|
||||||
user.calc_used_power()
|
user.calc_used_power()
|
||||||
|
|
||||||
main.EnergyUserFactory.distribute_energy(users, -1*(meter_values["Meter_Sum"]["PowerReal_P_Sum"]))
|
main.EnergyUserFactory.distribute_energy(users, 1*(meter_values["Meter_Sum"]["PowerReal_P_Sum"]))
|
||||||
|
|
||||||
user_values = energyuser.EnergyUser.get_all_current_values(users)
|
user_values = energyuser.EnergyUser.get_all_current_values(users)
|
||||||
try:
|
try:
|
||||||
|
|||||||
136
server/main.py
136
server/main.py
@@ -1,49 +1,61 @@
|
|||||||
from flask import Flask, request, jsonify
|
from flask import Flask, request, jsonify
|
||||||
|
import influxdb_client
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from pytz import timezone
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
# InfluxDB-Verbindungsinformationen
|
||||||
|
INFLUXDB_HOST = 'http://192.168.20.21:8086'
|
||||||
|
INFLUXDB_PORT = 8086
|
||||||
|
INFLUXDB_TOKEN = 'yjgsLHr3Fxj6LwCRvJlPSMTkTg7CwEn2ajsAeaxLHIZ_17ZHyUUn7P9nCpkdioOexDlWq73zTatmZ_ajvTPozA=='
|
||||||
|
INFLUXDB_ORG = 'Belevo AG'
|
||||||
|
INFLUXDB_BUCKET = 'E-Manger_Demo'
|
||||||
|
|
||||||
|
|
||||||
|
# InfluxDB-Client initialisieren
|
||||||
|
influx_client = influxdb_client.InfluxDBClient(url=INFLUXDB_HOST, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG)
|
||||||
|
# Route to get configuration
|
||||||
# Route to get configuration
|
# Route to get configuration
|
||||||
@app.route('/getconfig', methods=['POST'])
|
@app.route('/getconfig', methods=['POST'])
|
||||||
def get_config():
|
def get_config():
|
||||||
try:
|
#try:
|
||||||
token_id = request.headers.get('ID')
|
token_id = request.headers.get('ID')
|
||||||
|
|
||||||
if not token_id:
|
if not token_id:
|
||||||
return jsonify({'error': 'Token ID is missing'}), 400
|
return jsonify({'error': 'Token ID is missing'}), 400
|
||||||
|
|
||||||
config_file = os.path.join('config', f'{token_id}.json')
|
# Query to get the latest timestamp from InfluxDB
|
||||||
data_file = os.path.join('data', f'{token_id}.json') # angenommen, die Daten befinden sich im Ordner 'data'
|
query = f'from(bucket: "{INFLUXDB_BUCKET}") |> range(start: -1d) |> filter(fn: (r) => r._measurement == "{token_id}") |> last()'
|
||||||
|
result = influx_client.query_api().query(query)
|
||||||
if not os.path.exists(config_file):
|
records = list(result)
|
||||||
return jsonify({'error': 'Config not found for the specified token'}), 404
|
|
||||||
|
if records:
|
||||||
with open(config_file, 'r') as file:
|
last_timestamp = records[0].records[0].get_time()
|
||||||
config = json.load(file)
|
last_timestamp = last_timestamp.strftime('%Y-%m-%d %H:%M')
|
||||||
|
|
||||||
# Extract and include last timestamp in the response
|
|
||||||
if os.path.exists(data_file):
|
|
||||||
with open(data_file, 'r') as file:
|
|
||||||
data = json.load(file)
|
|
||||||
try:
|
|
||||||
last_timestamp = max(data.keys()) # Den neuesten Zeitstempel aus den Schlüsseln der Daten extrahieren
|
|
||||||
print(last_timestamp)
|
|
||||||
config['last_timestamp'] = last_timestamp
|
|
||||||
except ValueError:
|
|
||||||
config['last_timestamp'] = 0
|
|
||||||
else:
|
else:
|
||||||
config['last_timestamp'] = 0
|
# Set last timestamp to epoch time if no records found
|
||||||
|
last_timestamp = datetime(1970, 1, 1).strftime('%Y-%m-%d %H:%M')
|
||||||
|
|
||||||
|
# Load config from JSON file
|
||||||
|
config_file = os.path.join('config', f'{token_id}.json')
|
||||||
|
if os.path.exists(config_file):
|
||||||
|
with open(config_file, 'r') as file:
|
||||||
|
config = json.load(file)
|
||||||
|
else:
|
||||||
|
config = {}
|
||||||
|
|
||||||
|
# Add last timestamp to config
|
||||||
|
config['last_timestamp'] = last_timestamp
|
||||||
|
|
||||||
return jsonify(config), 200
|
return jsonify(config), 200
|
||||||
|
|
||||||
except Exception as e:
|
#except Exception as e:
|
||||||
return jsonify({'error': str(e)}), 500
|
# return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
# Route to set new data
|
# Route to set new data
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/setdata', methods=['POST'])
|
@app.route('/setdata', methods=['POST'])
|
||||||
def set_data():
|
def set_data():
|
||||||
# Token-ID aus den Request-Headern extrahieren
|
# Token-ID aus den Request-Headern extrahieren
|
||||||
@@ -56,67 +68,33 @@ def set_data():
|
|||||||
# Versuche, das JSON zu laden
|
# Versuche, das JSON zu laden
|
||||||
new_data = json.loads(new_data)
|
new_data = json.loads(new_data)
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
# Wenn das JSON nicht korrekt formatiert ist, schreibe das neue JSON in die Datei und beende die Funktion
|
# Wenn das JSON nicht korrekt formatiert ist, schreibe das neue JSON in die Datenbank und beende die Funktion
|
||||||
write_json_file(token_id, new_data)
|
write_to_influx(token_id, new_data)
|
||||||
return 'Invalid JSON format. New JSON data has been written to the file and overwritten existing data.'
|
return 'Invalid JSON format. New JSON data has been written to InfluxDB and overwritten existing data.'
|
||||||
|
|
||||||
# Pfad zum Datenordner und Datei für die Token-ID erstellen
|
# Daten in die InfluxDB schreiben
|
||||||
data_folder = 'data'
|
write_to_influx(token_id, new_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:
|
|
||||||
# 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!'
|
return 'Data successfully set!'
|
||||||
|
|
||||||
def write_json_file(token_id, new_data):
|
def write_to_influx(token_id, json_data):
|
||||||
"""
|
"""
|
||||||
Funktion zum Schreiben von JSON-Daten in eine Datei.
|
Funktion zum Schreiben von Daten in InfluxDB.
|
||||||
"""
|
"""
|
||||||
# Pfad zum Datenordner und Datei für die Token-ID erstellen
|
json_body = [
|
||||||
data_folder = 'data'
|
{
|
||||||
file_path = os.path.join(data_folder, f'{token_id}.json')
|
"measurement": token_id, # Verwende die Token-ID als Messungsnamen
|
||||||
|
"fields": {
|
||||||
# Neue Daten in die Datei schreiben
|
"data": json.dumps(json_data) # Das gesamte JSON als Text speichern
|
||||||
with open(file_path, 'w') as file:
|
}
|
||||||
json.dump(new_data, file)
|
}
|
||||||
|
]
|
||||||
def merge_json(json1, json2):
|
|
||||||
# Wenn ein JSON leer ist, gib einfach das andere zurück
|
|
||||||
if not json1:
|
|
||||||
return json2
|
|
||||||
if not json2:
|
|
||||||
return json1
|
|
||||||
|
|
||||||
# Erstelle eine Kopie des ersten JSON
|
|
||||||
merged_data = json1.copy()
|
|
||||||
|
|
||||||
# Füge die Timestamps aus dem zweiten JSON ein, falls sie nicht bereits im ersten JSON vorhanden sind
|
|
||||||
for timestamp, values in json2.items():
|
|
||||||
if timestamp not in merged_data:
|
|
||||||
merged_data[timestamp] = values
|
|
||||||
|
|
||||||
return merged_data
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Datenpunkt in die InfluxDB einfügen
|
||||||
|
influx_client.write_api().write(bucket=INFLUXDB_BUCKET, org=INFLUXDB_ORG, record=json_body)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app.run(debug=False)
|
app.run(debug=False, host="127.0.0.1")#, port=5000)
|
||||||
|
#app.run(host="0.0.0.0", port=5000)
|
||||||
Reference in New Issue
Block a user