forked from pi-node/pi-node
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
68 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |