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: token_id = request.headers.get('ID') if not token_id: return jsonify({'error': 'Token ID is missing'}), 400 # 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: # 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 # 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 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.' # Daten in die InfluxDB schreiben write_to_influx(token_id, new_data) return 'Data successfully set!' def write_to_influx(token_id, json_data): """ Funktion zum Schreiben von Daten in InfluxDB. """ 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, host="127.0.0.1")#, port=5000) #app.run(host="0.0.0.0", port=5000)