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
|
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { FadeLoader } from "react-spinners";
import { io } from "socket.io-client";
import CityMap from "../components/CityMap";
import Header from "../components/Header";
import Sidebar from "../components/Sidebar";
import API_URL from "../config";
import "../styles/dashboard.css";
import type { ErrorResponse } from "../types/error";
import type { AuthorizedUser } from "../types/login";
import type { Robot, RobotsResponse } from "../types/robot";
function Dashboard() {
const [errorMessage, setErrorMessage] = useState<string>("");
const [isLoading, setIsLoading] = useState<boolean>(true);
const [isSimulationActive, setIsSimulationActive] = useState(false);
const [robots, setRobots] = useState<Robot[]>([]);
const navigate = useNavigate();
const userString = localStorage.getItem("user");
const user: AuthorizedUser = userString ? JSON.parse(userString) : null;
const token = localStorage.getItem("token-robot-tracker");
async function handleLogout() {
localStorage.removeItem("token-robot-tracker");
localStorage.removeItem("user");
navigate("/login", { replace: true });
}
async function handleStartAllRobots() {
setIsSimulationActive(true);
try {
const response = await fetch(`${API_URL}/robots/move`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
});
if (!response.ok) {
const errorData: ErrorResponse = await response.json();
throw new Error(
errorData.message || "Failed to set all robots moving."
);
}
console.log("All robots set moving.");
} catch (error) {
console.error("Error starting robots:", error);
if (error instanceof Error) {
setErrorMessage(error.message);
} else {
setErrorMessage("An unexpected error occurred.");
}
setIsSimulationActive(false);
}
}
async function handleStopAllRobots() {
setIsSimulationActive(false);
try {
const response = await fetch(`${API_URL}/robots/stop`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
});
if (!response.ok) {
const errorData: ErrorResponse = await response.json();
throw new Error(
errorData.message || "Failed to set all robots idle."
);
}
console.log("All robots set idle.");
} catch (error) {
console.error("Error stopping robots:", error);
if (error instanceof Error) {
setErrorMessage(error.message);
} else {
setErrorMessage("An unexpected error occurred.");
}
setIsSimulationActive(true);
}
}
// Request robot data from backend on component mount
useEffect(() => {
// Additional safety check to protect this page from unauthorized access
if (!token || token === "undefined" || token === "null") {
navigate("/login");
return;
}
async function fetchRobots() {
try {
setIsLoading(true);
const response = await fetch(`${API_URL}/robots`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
});
if (!response.ok) {
const errorData: ErrorResponse = await response.json();
throw new Error(
errorData.message ||
`Failed to load the robots: ${response.status}`
);
}
const data: RobotsResponse = await response.json();
setRobots(data.data);
} catch (error) {
console.error("Failed to load the robots:", error);
if (error instanceof Error) {
setErrorMessage(error.message);
} else {
setErrorMessage("An unexpected error occurred.");
}
} finally {
setIsLoading(false);
}
}
fetchRobots();
// Establish WebSocket connection to backend
const socket = io(API_URL);
// Listen for real-time robot updates
socket.on("robots_update", (updatedRobots) => {
setRobots(updatedRobots);
});
// Cleanup when component unmounts
return () => {
socket.disconnect();
};
}, [token, navigate]);
return isLoading ? (
<FadeLoader />
) : (
<div className="dashboard-page">
<Header user={user} logout={handleLogout} />
<CityMap robots={robots} />
<Sidebar
activeSimulation={isSimulationActive}
errorMessage={errorMessage}
setErrorMessage={setErrorMessage}
token={token}
robots={robots}
onStartAllRobots={handleStartAllRobots}
onStopAllRobots={handleStopAllRobots}
/>
</div>
);
}
export default Dashboard;
|