File size: 4,483 Bytes
c575e18
 
19b663b
 
 
 
 
 
ce6d450
19b663b
 
 
 
 
c59c4c4
 
9c4ee1e
 
c59c4c4
 
 
 
 
 
 
9c4ee1e
 
c59c4c4
 
 
 
 
9c4ee1e
 
c59c4c4
 
 
 
 
 
 
 
9c4ee1e
 
 
c59c4c4
 
 
 
 
 
 
 
 
9c4ee1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59c4c4
 
19b663b
f70fe7a
 
 
 
 
 
9c4ee1e
f70fe7a
 
 
 
 
 
 
 
 
19b663b
 
c59c4c4
19b663b
 
 
 
f70fe7a
 
 
 
 
 
 
19b663b
 
 
c59c4c4
19b663b
 
 
 
f70fe7a
 
19b663b
 
 
 
 
9c4ee1e
 
 
 
 
 
 
 
19b663b
 
c575e18
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simulator</title>
</head>
<body>
    <canvas id="displayCanvas" width="256" height="256"></canvas>

    <script>
        const canvas = document.getElementById('displayCanvas');
        const ctx = canvas.getContext('2d');
        
        let socket;
        let isConnected = false;
        let reconnectAttempts = 0;
        const MAX_RECONNECT_DELAY = 30000; // Maximum delay between reconnection attempts (30 seconds)

        function connect() {
            socket = new WebSocket(`wss://${window.location.host}/ws`);

            socket.onopen = function(event) {
                console.log("WebSocket connection established");
                isConnected = true;
                reconnectAttempts = 0;
                startHeartbeat();
            };

            socket.onclose = function(event) {
                console.log("WebSocket connection closed. Attempting to reconnect...");
                isConnected = false;
                clearInterval(heartbeatInterval);
                scheduleReconnection();
            };

            socket.onerror = function(error) {
                console.error("WebSocket error:", error);
            };

            socket.onmessage = function (event) {
                const data = JSON.parse(event.data);
                if (data.type === "heartbeat_response") {
                    console.log("Heartbeat response received");
                } else if (data.image) {
                    const img = new Image();
                    img.onload = function() {
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                    };
                    img.src = 'data:image/png;base64,' + data.image;
                }
            };
        }

        function scheduleReconnection() {
            const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), MAX_RECONNECT_DELAY);
            console.log(`Scheduling reconnection in ${delay}ms`);
            setTimeout(connect, delay);
            reconnectAttempts++;
        }

        let heartbeatInterval;
        function startHeartbeat() {
            heartbeatInterval = setInterval(() => {
                if (isConnected) {
                    socket.send(JSON.stringify({ type: "heartbeat" }));
                }
            }, 15000); // Send heartbeat every 15 seconds
        }

        // Initial connection
        connect();

        let lastSentPosition = null;
        let lastSentTime = 0;
        const SEND_INTERVAL = 50; // Send updates every 50ms

        function sendMousePosition(x, y, forceUpdate = false) {
            const currentTime = Date.now();
            if (isConnected && (forceUpdate || !lastSentPosition || currentTime - lastSentTime >= SEND_INTERVAL)) {
                socket.send(JSON.stringify({
                    "action_type": "move",
                    "mouse_position": [x, y]
                }));
                lastSentPosition = { x, y };
                lastSentTime = currentTime;
            }
        }

        // Capture mouse movements and clicks
        canvas.addEventListener("mousemove", function (event) {
            if (!isConnected) return;
            let rect = canvas.getBoundingClientRect();
            let x = event.clientX - rect.left;
            let y = event.clientY - rect.top;
            
            // Client-side prediction
            ctx.beginPath();
            ctx.moveTo(lastSentPosition ? lastSentPosition.x : x, lastSentPosition ? lastSentPosition.y : y);
            ctx.lineTo(x, y);
            ctx.stroke();

            sendMousePosition(x, y);
        });

        canvas.addEventListener("click", function (event) {
            if (!isConnected) return;
            let rect = canvas.getBoundingClientRect();
            let x = event.clientX - rect.left;
            let y = event.clientY - rect.top;

            sendMousePosition(x, y, true);

            socket.send(JSON.stringify({
                "action_type": "left_click",
                "mouse_position": [x, y]
            }));
        });

        // Graceful disconnection
        window.addEventListener('beforeunload', function (e) {
            if (isConnected) {
                socket.send(JSON.stringify({ type: "disconnect" }));
                socket.close();
            }
        });
    </script>
</body>
</html>