Untitled

mail@pastecode.io avatar
unknown
python
6 months ago
4.5 kB
4
Indexable
Never
import datetime
import socket
import json

import requests


class MiddleMan:
    def __init__(self):
        self.data = {
            "timestamp": None,
            "vin": None,
            "last_timestamp_check": None,
            "acceleration": None,
            "speed": None,
            "license_plates": [],
            "coordinates": None,
            "violations": [
                {
                    "type": None,
                    "coordinates": None,
                    "timestamp": None
                }
            ],
            "driver": {
                "seatbelt": None,
                "drowsiness": None,
                "heart_rate": []
            },
            "passenger": {
                "seatbelt": None,
                "heart_rate": []
            },
            "passengers_num": None
        }

    def update_data(self, new_data):
        for key, value in new_data.items():
            if key in self.data:
                if isinstance(self.data[key], dict):
                    self.data[key].update(value)
                elif isinstance(self.data[key], list) and isinstance(value, list):
                    self.data[key] = [v if v is not None else self.data[key][i] for i, v in enumerate(value)]
                else:
                    self.data[key] = value

    def listen_and_update(self, port):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind(('localhost', port))
            s.listen()
            conn, addr = s.accept()
            with conn:
                received_data = json.loads(conn.recv(1024).decode())
                self.update_data(received_data)

    def handle_before_accident_scenario(self, script1_port, script2_address, script2_port):
        # Listen for data from Script 1
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s1:
            s1.bind(('localhost', script1_port))
            s1.listen()
            conn1, addr1 = s1.accept()
            with conn1:
                received_data = json.loads(conn1.recv(1024).decode())
                self.update_data(received_data)

        # Request data from Script 2
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s2:
            s2.connect((script2_address, script2_port))
            s2.sendall(json.dumps({"accident_status": "occurred"}).encode())
            data_from_script2 = json.loads(s2.recv(1024).decode())
            self.update_data(data_from_script2)

        self.send_data_to_api('server_host', 8080)

    def handle_post_accident_scenario(self, script1_port, script2_address, script2_port):
        # Wait for accident signal from Script 1
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s1:
            s1.bind(('localhost', script1_port))
            s1.listen()
            conn1, addr1 = s1.accept()
            with conn1:
                accident_signal = json.loads(conn1.recv(1024).decode())
                if accident_signal.get("accident_status") == "car_stopped":
                    # Notify Script 2 about the accident
                    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s2:
                        s2.connect((script2_address, script2_port))
                        s2.sendall(json.dumps({"accident_status": "car_stopped"}).encode())

                        # Continuously receive data from Script 2 until accident is over
                        while True:
                            data_from_script2 = json.loads(s2.recv(1024).decode())
                            self.update_data(data_from_script2)

                            self.send_data_to_api('server_host', 8080, data_from_script2)

                            if data_from_script2.get("accident_status") == "over":
                                break

    def send_data_to_api(self, api_url, data):
        try:
            response = requests.post(api_url, json=data)
            response.raise_for_status()  # This will raise an error for HTTP error responses
            return response.json()  # or just return True if you don't need the response
        except requests.RequestException as e:
            print(f"An error occurred: {e}")
            return None

middleman = MiddleMan()
middleman.handle_before_accident_scenario(12345, 'https://diploma-thesis-backend.onrender.com/accident/accident-data', 54321)  # Replace with the actual port
middleman.handle_post_accident_scenario(12345, 'https://diploma-thesis-backend.onrender.com/accident/accident-data', 54321)
Leave a Comment