-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_dashboard.py
More file actions
109 lines (92 loc) · 4.27 KB
/
client_dashboard.py
File metadata and controls
109 lines (92 loc) · 4.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python3
"""
SonicWave Client Dashboard - Flask Edition
Web-based interface for sending and receiving emergency communications.
"""
import logging
import threading
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit
from sonicwave.ggwave_transport import GGWaveTransport
from sonicwave.packet import EmergencyPacket, PacketManager
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Flask & SocketIO App
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode='threading')
# SonicWave Components
packet_manager = PacketManager()
ggwave_transport = None
# --- Packet Handling ---
def on_packet_received(packet):
"""Callback function for when a packet is received."""
logger.info(f"Packet received via GGWave: {packet.to_json()}")
# Broadcast the received packet to all connected web clients
socketio.emit('new_packet', packet.to_dict(), namespace='/dashboard')
# --- Transport Initialization ---
def initialize_ggwave():
"""Initializes and starts the GGWave transport."""
global ggwave_transport
try:
ggwave_transport = GGWaveTransport(on_packet_received=on_packet_received)
if ggwave_transport.initialize():
ggwave_transport.start_listening()
logger.info("GGWave transport initialized and listening.")
socketio.emit('status_update', {'transport': 'ggwave', 'status': 'active'}, namespace='/dashboard')
else:
logger.error("Failed to initialize GGWave transport.")
socketio.emit('status_update', {'transport': 'ggwave', 'status': 'error', 'message': 'Initialization failed'}, namespace='/dashboard')
except Exception as e:
logger.error(f"Error initializing GGWave: {e}")
socketio.emit('status_update', {'transport': 'ggwave', 'status': 'error', 'message': str(e)}, namespace='/dashboard')
# --- Flask Routes ---
@app.route('/')
def index():
"""Serve the main client dashboard page."""
return render_template('client_dashboard.html')
@app.route('/api/send', methods=['POST'])
def send_message():
"""API endpoint to send a message."""
data = request.json
if not data or 'message' not in data:
return jsonify({'status': 'error', 'message': 'Invalid data'}), 400
if not ggwave_transport or not ggwave_transport.is_listening():
return jsonify({'status': 'error', 'message': 'GGWave transport is not active'}), 500
try:
packet = EmergencyPacket(
emergency_type=data.get('emergency_type', 'GENERAL'),
priority=data.get('priority', 'MEDIUM'),
message=data['message'],
location=data.get('location', 'Web Dashboard')
)
# Send the packet in a separate thread to avoid blocking the request
threading.Thread(target=ggwave_transport.send_packet, args=(packet,)).start()
logger.info(f"Queued packet for sending via GGWave: {packet.to_json()}")
return jsonify({'status': 'success', 'message': 'Message queued for sending'})
except Exception as e:
logger.error(f"Error sending packet: {e}")
return jsonify({'status': 'error', 'message': str(e)}), 500
# --- SocketIO Events ---
@socketio.on('connect', namespace='/dashboard')
def on_connect():
"""Handle new client connections."""
logger.info("Web client connected.")
emit('status_update', {'message': 'Connected to SonicWave server.'})
# Report current ggwave status
if ggwave_transport and ggwave_transport.is_listening():
emit('status_update', {'transport': 'ggwave', 'status': 'active'})
else:
emit('status_update', {'transport': 'ggwave', 'status': 'inactive'})
@socketio.on('disconnect', namespace='/dashboard')
def on_disconnect():
"""Handle client disconnections."""
logger.info("Web client disconnected.")
if __name__ == '__main__':
# Initialize and start GGWave transport in a background thread
init_thread = threading.Thread(target=initialize_ggwave)
init_thread.daemon = True
init_thread.start()
logger.info("Starting Flask-SocketIO server on http://127.0.0.1:5000")
socketio.run(app, host='127.0.0.1', port=5000, allow_unsafe_werkzeug=True)