From de596db4e0dec64890282d86185b064128d4a88b Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Sat, 19 Oct 2024 16:23:11 +0700 Subject: [PATCH] Update main.py --- edge_gateway/advanced_edge_gateway/main.py | 91 ++++++++++++++++------ 1 file changed, 68 insertions(+), 23 deletions(-) diff --git a/edge_gateway/advanced_edge_gateway/main.py b/edge_gateway/advanced_edge_gateway/main.py index bad8dce..8bf53ea 100644 --- a/edge_gateway/advanced_edge_gateway/main.py +++ b/edge_gateway/advanced_edge_gateway/main.py @@ -1,33 +1,78 @@ -# edge_gateway/main.py +import logging import os import json -from kafka import KafkaDataProcessor -from anomaly_detection import AnomalyDetector -from secure_communication import MutualTLS +from flask import Flask, jsonify +from temperature_sensor import TemperatureSensor # Assuming this is a custom module for temperature readings +from node_registry import NodeRegistry +from node_monitor import NodeMonitor -class EdgeGateway: +# Configure logging +logging.basicConfig(filename='main.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +app = Flask(__name__) + +class Supernode: def __init__(self, config_file='config.json'): - self.config = EdgeGatewayConfig(config_file) - self.kafka_processor = KafkaDataProcessor(**self.config.get_kafka_config()) - self.anomaly_detector = AnomalyDetector(**self.config.get_anomaly_detection_config()) - self.mutual_tls = MutualTLS(**self.config.get_mutual_tls_config()) + self.config_file = config_file + self.config = self.load_config() + self.temperature_sensor = TemperatureSensor(self.config.get('sensor_device_path', '/sys/bus/w1/devices/28-000005f8b8ff/w1_slave')) + self.node_registry = NodeRegistry(uri=self.config.get('registry_uri', 'ws://localhost:8765')) + self.node_monitor = NodeMonitor(uri=self.config.get('monitor_uri', 'ws://localhost:8765')) + + def load_config(self): + """Load configuration from a JSON file.""" + if os.path.exists(self.config_file): + with open(self.config_file, 'r') as file: + config = json.load(file) + logging.info("Configuration loaded successfully.") + return config + else: + logging.error(f"Configuration file {self.config_file} not found. Using default settings.") + return {} + + def get_temperature(self): + """Get the current temperature from the sensor.""" + try: + temperature = self.temperature_sensor.read_temperature() + logging.info(f"Current temperature: {temperature}°C") + return temperature + except Exception as e: + logging.error(f"Error reading temperature: {e}") + return None - def start(self): - # Start consuming from Kafka topic - self.kafka_processor.startConsuming() + @app.route('/status', methods=['GET']) + def status(): + """Endpoint to get the current status of the Raspberry Pi.""" + uptime = self.get_uptime() + temperature = self.get_temperature() + response = { + 'temperature': temperature, + 'uptime': uptime + } + return jsonify(response) - # Start anomaly detection - self.anomaly_detector.train_model([]) # Train the model with some data + def get_uptime(self): + """Get the uptime of the Raspberry Pi.""" + with open('/proc/uptime', 'r') as f: + uptime_seconds = float(f.readline().split()[0]) + uptime = self.format_uptime(uptime_seconds) + return uptime - # Establish secure connection using mutual TLS - self.mutual_tls.connect("example.com", 443) + def format_uptime(self, seconds): + """Format uptime from seconds to a readable string.""" + days = int(seconds // (24 * 3600)) + hours = int((seconds % (24 * 3600)) // 3600) + minutes = int((seconds % 3600) // 60) + return f"{days} days, {hours} hours, {minutes} minutes" - # Send and receive data over the secure connection - self.mutual_tls.send_data("Hello, server!") - buffer = bytearray(1024) - self.mutual_tls.receive_data(buffer, 1024) - print(buffer.decode()) + def run(self): + """Run the Flask application.""" + try: + logging.info("Starting the Supernode application...") + app.run(host='0.0.0.0', port=3000) + except Exception as e: + logging.error(f"Error while running the application: {e}") if __name__ == "__main__": - edge_gateway = EdgeGateway() - edge_gateway.start() + supernode = Supernode() + supernode.run()