From 731b8b721ec70eeaa20bfa21d5a5b47c6f3511ca Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Tue, 29 Oct 2024 19:04:12 +0700 Subject: [PATCH] Create websocket_api.py --- src/api/websocket_api.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/api/websocket_api.py diff --git a/src/api/websocket_api.py b/src/api/websocket_api.py new file mode 100644 index 0000000..8b93906 --- /dev/null +++ b/src/api/websocket_api.py @@ -0,0 +1,31 @@ +# api/websocket_api.py + +from flask import Flask +from flask_socketio import SocketIO, emit +from src.iot.sensor_integration import SensorData + +app = Flask(__name__) +socketio = SocketIO(app) + +# Initialize sensor data +sensor_data = SensorData() + +@socketio.on('connect') +def handle_connect(): + """Handle new WebSocket connections.""" + print('Client connected') + emit('response', {'message': 'Connected to WebSocket API'}) + +@socketio.on('request_latest_data') +def handle_request_latest_data(): + """Send the latest climate data to the client.""" + data = sensor_data.get_latest_data() + emit('latest_data', data) + +@socketio.on('disconnect') +def handle_disconnect(): + """Handle WebSocket disconnections.""" + print('Client disconnected') + +if __name__ == '__main__': + socketio.run(app, debug=True, host='0.0.0.0', port=5001)