summaryrefslogtreecommitdiff
path: root/backend/src/simulation/robotMovementSimulator.ts
blob: 2299f43f783940b650e4bb9880635517fd4310b6 (plain)
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { QueryResult } from "pg";
import { Server } from "socket.io";
import db from "../database/postgres.js";
import {
    Robot,
    RobotPosition,
    RobotsUpdateBroadcast,
    SimulationResponse,
} from "../types/robot.js";

// Coordinates for the boundaries of the frontend map
const LEIPZIG_AREA = {
    WEST: 12.22,
    SOUTH: 51.26,
    EAST: 12.54,
    NORTH: 51.44,
} as const;

const LEIPZIG_CENTER = {
    LAT: 51.340863,
    LON: 12.375919,
} as const;

const SIMULATION_INTERVAL_MS = 2000;

// IDs of moving robots
const movingRobots = new Set<number>();

// Global simulation timer
let simulationTimer: NodeJS.Timeout | null = null;

/*
    MOVEMENT FUNCTION
    generate random position within Leipzig based on current position
*/

function generateRandomPosition(currentLat: string, currentLon: string) {
    // 0.0005 degrees ca. 50-70 meters
    const deltaLat = (Math.random() - 0.5) * 0.0005;
    const deltaLon = (Math.random() - 0.5) * 0.0005;

    let newLat = parseFloat(currentLat) + deltaLat;
    let newLon = parseFloat(currentLon) + deltaLon;

    // Check if robot's new position would be outside of Leipzig, if yes set back to center
    const outsideLatBoundary =
        newLat < LEIPZIG_AREA.SOUTH || newLat > LEIPZIG_AREA.NORTH;
    const outsideLonBoundary =
        newLon < LEIPZIG_AREA.WEST || newLon > LEIPZIG_AREA.EAST;

    if (outsideLatBoundary || outsideLonBoundary) {
        newLat = LEIPZIG_CENTER.LAT;
        newLon = LEIPZIG_CENTER.LON;
    }

    return {
        lat: newLat.toFixed(7),
        lon: newLon.toFixed(7),
    };
}

/*
    MAIN FUNCTION:
    move a robot, update database, websocket broadcast
*/

async function updateRobotPositions(io: Server) {
    let client;

    try {
        client = await db.connect();

        const allRobotsQuery: QueryResult<Robot> = await client.query(
            "SELECT * FROM robots ORDER BY id;"
        );
        const allRobots = allRobotsQuery.rows;

        // Update database
        await client.query("BEGIN");

        const updatedRobots: Robot[] = [];

        for (const robot of allRobots) {
            // If not moving, keep position & set idle
            if (!movingRobots?.has(robot.id)) {
                if (robot.status === "moving") {
                    const idleQuery: QueryResult<Robot> = await client.query(
                        `
                        UPDATE robots
                        SET status = 'idle',
                            updated_at = CURRENT_TIMESTAMP
                        WHERE id = $1
                        RETURNING *;
                        `,
                        [robot.id]
                    );
                    updatedRobots.push(idleQuery.rows[0]);
                } else {
                    updatedRobots.push(robot);
                }
                continue;
            }

            // If moving, assign new position and add previous to log
            const newPos: RobotPosition = generateRandomPosition(
                robot.lat,
                robot.lon
            );

            const previousPositionsLog: RobotPosition[] =
                robot.robot_positions || [];

            previousPositionsLog.push({ lat: robot.lat, lon: robot.lon });

            // Limit log to 10 entries, remove oldest when more
            if (previousPositionsLog.length > 10) {
                previousPositionsLog.shift();
            }

            const updateQuery: QueryResult<Robot> = await client.query(
                `
                UPDATE robots
                SET 
                    lat = $1,
                    lon = $2,
                    status = 'moving',
                    robot_positions = $3::jsonb,
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = $4
                RETURNING *;
                `,
                [
                    newPos.lat,
                    newPos.lon,
                    JSON.stringify(previousPositionsLog),
                    robot.id,
                ]
            );

            updatedRobots.push(updateQuery.rows[0]);
        }

        await client.query("COMMIT");

        // Websocket broadcast, make sure robots stay in correct order
        updatedRobots.sort((a, b) => a.id - b.id);

        const broadcastPayload: RobotsUpdateBroadcast = { updatedRobots };

        io.emit("robots_update", broadcastPayload);

        // Check if this was the final update, setting all to idle with no more robots moving
        if (movingRobots.size === 0) {
            if (simulationTimer) {
                clearInterval(simulationTimer);
                simulationTimer = null;
            }
        }
    } catch (error) {
        console.error("Error in the global simulation timer: ", error);
        if (client) await client.query("ROLLBACK");

        // Stop simulation on error
        if (simulationTimer) {
            clearInterval(simulationTimer);
            simulationTimer = null;
        }
    } finally {
        if (client) client.release();
    }
}

/*
    SIMULATION FUNCTION
    Runs the simulation by repeating the main function in intervals
*/

async function startSimulation(io: Server) {
    if (simulationTimer) return; // Already running

    // Immediate execution right away without delay
    await updateRobotPositions(io);

    // Then interval for subsequent updates
    simulationTimer = setInterval(async () => {
        await updateRobotPositions(io);
    }, SIMULATION_INTERVAL_MS);
}

/*
    PUBLIC CONTROLLER FUNCTIONS:
    start or stop movement of one or all robots
*/

export async function setRobotMoving(
    io: Server,
    robotId: number
): Promise<SimulationResponse> {
    movingRobots.add(Number(robotId));
    await startSimulation(io);

    return {
        message: `Robot ID ${robotId} set in motion.`,
        status: "moving",
    };
}

export async function setRobotIdle(
    robotId: number
): Promise<SimulationResponse> {
    movingRobots.delete(Number(robotId));

    return {
        message: `Robot ID ${robotId} stopped.`,
        status: "idle",
    };
}

export async function setAllRobotsMoving(
    io: Server
): Promise<SimulationResponse> {
    const allRobotIDsQuery: QueryResult<{ id: Robot["id"] }> = await db.query(
        "SELECT id FROM robots;"
    );
    allRobotIDsQuery.rows.forEach((queryObject) =>
        movingRobots.add(queryObject.id)
    );

    await startSimulation(io);

    return {
        message: "All robots set in motion.",
    };
}

export async function setAllRobotsIdle(): Promise<SimulationResponse> {
    movingRobots.clear();
    return {
        message: "All robots stopped.",
    };
}