App.py
from flask import Flask, jsonify, request from flask_cors import CORS import json import socket
app = Flask(name) CORS(app)
# Define the path to the JSON configuration file CONFIG_FILE = 'config.json'
# Load settings from the JSON file def load_settings():
try: with open(CONFIG_FILE, 'r') as file: return json.load(file) except FileNotFoundError: # If the config file doesn't exist, return an empty default settings structure return { "use_dhcp": True, "manual_ip": "", "cloud_ip": "", "alert_email": "", "max_temperature": 30, "max_humidity": 50, "door_sensors": 1 }
# Save settings to the JSON file def save_settings(data):
with open(CONFIG_FILE, 'w') as file: json.dump(data, file, indent=4)
# Endpoint to get the sensor data @app.route('/sensor_data.json') def get_sensor_data():
with open('sensor_data.json', 'r') as f: data = json.load(f) return jsonify(data)
# Endpoint to get the current IP address of the Raspberry Pi @app.route('/get_current_ip', methods=['GET']) def get_current_ip():
try: # Get the current IP address of the Raspberry Pi hostname = socket.gethostname() current_ip = socket.gethostbyname(hostname) return jsonify({'current_ip': current_ip}) except Exception as e: return jsonify({'error': str(e)}), 500
# Endpoint to get the current configuration settings @app.route('/get_settings', methods=['GET']) def get_settings():
settings = load_settings() return jsonify(settings)
# Endpoint to save the configuration settings @app.route('/save_settings', methods=['POST']) def save_settings_endpoint():
try: settings = request.get_json() save_settings(settings) return jsonify({'message': 'Settings saved successfully.'}) except Exception as e: return jsonify({'error': str(e)}), 500
if name == 'main':
# Run the Flask server with debug mode enabled app.run(debug=True)