Weiterarbeit engine, main

This commit is contained in:
2024-05-27 16:24:43 +02:00
parent 5687acbf66
commit bf266a007f
4 changed files with 59 additions and 81 deletions

File diff suppressed because one or more lines are too long

View File

@@ -54,7 +54,7 @@ while True:
for user in users:
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)
try:

View File

@@ -1,49 +1,61 @@
from flask import Flask, request, jsonify
import influxdb_client
import os
import json
from datetime import datetime
from pytz import timezone
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
@app.route('/getconfig', methods=['POST'])
def get_config():
try:
#try:
token_id = request.headers.get('ID')
if not token_id:
return jsonify({'error': 'Token ID is missing'}), 400
config_file = os.path.join('config', f'{token_id}.json')
data_file = os.path.join('data', f'{token_id}.json') # angenommen, die Daten befinden sich im Ordner 'data'
if not os.path.exists(config_file):
return jsonify({'error': 'Config not found for the specified token'}), 404
with open(config_file, 'r') as file:
config = json.load(file)
# 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
# Query to get the latest timestamp from InfluxDB
query = f'from(bucket: "{INFLUXDB_BUCKET}") |> range(start: -1d) |> filter(fn: (r) => r._measurement == "{token_id}") |> last()'
result = influx_client.query_api().query(query)
records = list(result)
if records:
last_timestamp = records[0].records[0].get_time()
last_timestamp = last_timestamp.strftime('%Y-%m-%d %H:%M')
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
except Exception as e:
return jsonify({'error': str(e)}), 500
#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
@@ -56,67 +68,33 @@ def set_data():
# 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.'
# Wenn das JSON nicht korrekt formatiert ist, schreibe das neue JSON in die Datenbank und beende die Funktion
write_to_influx(token_id, new_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
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:
# 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)
# Daten in die InfluxDB schreiben
write_to_influx(token_id, new_data)
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
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(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
json_body = [
{
"measurement": token_id, # Verwende die Token-ID als Messungsnamen
"fields": {
"data": json.dumps(json_data) # Das gesamte JSON als Text speichern
}
}
]
# Datenpunkt in die InfluxDB einfügen
influx_client.write_api().write(bucket=INFLUXDB_BUCKET, org=INFLUXDB_ORG, record=json_body)
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)