-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
399 lines (339 loc) · 17.8 KB
/
script.js
File metadata and controls
399 lines (339 loc) · 17.8 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
const daylightSound = new Audio('audio/Luffy_Theme.mp3');
const nightfallSound = new Audio('audio/Zoro_Theme.mp3');
let hasPlayedDaySound = false;
let hasPlayedNightSound = false;
/*========================================================== Clock Function ==========================================================*/
function updateClock(){
const now = new Date(); // Creates a Date object called 'now' to access the date and time
const hours = String((now.getHours()) % 12 || 12).padStart(2, '0'); // .padStart() function adds whatever character is specified at the beginning of the string if it doesn't have the required number of characters: in this case 2. Converting the hours to str
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const ampm = hours >= 12 ? 'PM' : 'AM';
document.getElementById('time').innerHTML = `
<span>${hours}:${minutes}:${seconds}</span><span style="font-size: 6rem">${ampm}</span>
`; // sets the hours, minutes and seconds by updating HTML
const options = { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric' }; // specifies the actual format for the date
document.getElementById('date').textContent = now.toLocaleDateString('en-US', options); // using the 'now' object, it sets the date with the specified format and updtaes HTML
}
/*========================================================== Weather Function ==========================================================*/
async function getWeather(){ // async is a keyword that is used when we don't really want a function to activate instantly and is waiting for another condition
try{
const response = await fetch('http://localhost:3001/weather');
if(!response.ok){
throw new Error('Network response was not ok'); // If the response is not okay, then through an error out
}
const dataRecieved = await response.json(); // parsing the string that we got to an actual javascript object
const currentWeather = dataRecieved.current; // Current Weather
const humidity = dataRecieved.current ? dataRecieved.current.relative_humidity_2m : "N/A"; // Humidity level
const dailyWeather = dataRecieved.daily; // For Forecast
const weatherCodes = { // Translating weather codes that Open-Meteo sends
0: "Clear sky",
1: "Mainly clear",
2: "Partly cloudy",
3: "Overcast",
45: "Fog",
48: "Depositing rime fog",
51: "Light drizzle: Take Umbrella",
53: "Moderate drizzle: Take Umbrella",
55: "Dense drizzle: Take Umbrella",
61: "Slight rain: Take Umbrella",
63: "Moderate rain: Take Umbrella",
65: "Heavy rain: Take Umbrella",
80: "Slight rain showers: Take Umbrella",
95: "Thunderstorm: Take Umbrella"
}
const description = weatherCodes[currentWeather.weather_code] || "Unknown condition"; // Description, If unknown pops up, go into URL and see what the current weather code is
const currentRainChance = dataRecieved.hourly.precipitation_probability[0];
// Injecting HTML for the weather widget
document.getElementById('weather-widget').innerHTML = `
<div class="weather-header">
<p>Current Conditions</p>
</div>
<div class="weather-main">
<div class="main-temp">${Math.round(currentWeather.temperature_2m)}°</div>
<div class="main-desc">
<span class="condition-text">${description}</span>
<span class="high-low">High: ${Math.round(dailyWeather.temperature_2m_max[0])}° • Low: ${Math.round(dailyWeather.temperature_2m_min[0])}°</span>
<span class="last-updated" id="last-updated-weather">Last Updated: ${lastUpdatedTime()}</span>
</div>
</div>
<div class="weather-grid">
<div class="stat-item">
<span class="stat-label">Wind</span>
<span class="stat-value">${currentWeather.wind_speed_10m} <small>m/h</small></span>
</div>
<div class="stat-item">
<span class="stat-label">Humidity</span>
<span class="stat-value">${humidity}%</span>
</div>
<div class="stat-item rain-prob">
<span class="stat-label">Rain</span>
<span class="stat-value">${currentRainChance}%</span>
</div>
<div class="stat-item uv-index">
<span class="stat-label">UV Index</span>
<span class="stat-value">${currentWeather.uv_index}</span>
</div>
</div>
`;
updateSolarTracker(dataRecieved);
// Array of day names to map the dates
const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
let forecastHTML = ``;
// Loop through the next 6 days (starting at index 1 for tomorrow)
for(let i = 1; i <= 6; i++){
const date = new Date(dailyWeather.time[i] + 'T00:00');
const dayName = dayNames[date.getDay()];
const dayNumber = date.getDate();
const maxTemp = Math.round(dailyWeather.temperature_2m_max[i]);
const minTemp = Math.round(dailyWeather.temperature_2m_min[i]);
const rainChance = dailyWeather.precipitation_probability_max[i];
let dayIcon;
if(rainChance > 80) dayIcon = '🌦️';
else if(rainChance > 60) dayIcon = '🌥️';
else if(rainChance > 40) dayIcon = '⛅';
else if(rainChance > 20) dayIcon = '🌤️';
else dayIcon = `☀️`;
// Adding the HTML that will be injected into index.html
forecastHTML += `
<div class="forecast-day">
<div class="day-stats">
<span class="day-name">${dayName} ${dayNumber}</span>
<span class="day-temp">${maxTemp}° / ${minTemp}°F</span>
<span class="day-rain">${dayIcon} Chance of Rain: ${rainChance}%</span>
</div>
</div>
`;
}
// Injecting the HTML onto the forecast bar
document.getElementById('forecast-bar').innerHTML = forecastHTML;
}
catch(error){
console.error("Open-Meteo fetch failed:", error);
}
}
/*========================================================== Shuttle Function ==========================================================*/
async function getShuttleData(){
try{
const response = await fetch('http://localhost:3001/shuttle'); // send a request to the proxxy server for information
const data = await response.json(); // Wait for the json file and store it in 'data'
const route2Data = data.find(item => item.RouteDescription === "Route 2"); // Out of all of the information, search specifically for the Route 2 info
// A valid entry must not be departed AND have a positive, reasonable arrival time (under 2 hours)
const isValidEntry = (t) => !t.IsDeparted && t.Seconds > 0 && t.Seconds < 7200;
if(route2Data && route2Data.Times && route2Data.Times.length > 0){ // if the data exists and shuttles are running, keep going!
const nextEntry = route2Data.Times.find(t => isValidEntry(t));
if(nextEntry){ // If nextEntry exists
const allEntries = route2Data.Times.filter(t => isValidEntry(t));
const secondEntry = allEntries[1]; // second bus if it exists
const getDisplayTime = (entry) => {
const minutesAway = Math.floor(entry.Seconds / 60); // Convert seconds to minutes
if (entry.Seconds <= 120) return `Shuttle is Arriving!🚨`;
else if (entry.Seconds <= 300) return `Get Ready, Shuttle arrives in ${minutesAway} min`;
else return `Shuttle is ${minutesAway} min away...`;
};
// If the second entry exists, display it's information, else don't display anything
const secondBusHTML = secondEntry ? `
<div id="next-shuttle">
Next: ${getDisplayTime(secondEntry)}
</div>
` : '';
// Injecting the HTML into the shuttle-routes-widget
document.getElementById('shuttle-routes-widget').innerHTML = `
<p id="shuttle-widget-title">Shuttle Route</p>
<p id="route-title">Route 2 @ Boardwalk Stop</p>
<div>
${getDisplayTime(nextEntry)}
</div>
${secondBusHTML}
<span class="last-updated" id="last-updated-shuttle">Last Updated: ${lastUpdatedTime()}</span>
`;
}
// If nextEntry doesn't exist
else{
document.getElementById('shuttle-routes-widget').innerHTML = `
<p id="shuttle-widget-title">Shuttle Route</p>
<p id="route-title">Route 2 @ Boardwalk Stop</p>
<p style="margin-top: 1rem;">Fetching...</p>
<span class="last-updated" id="last-updated-shuttle">Last Updated: ${lastUpdatedTime()}</span>
`;
}
}
// If there are no bus routes active
else{
document.getElementById('shuttle-routes-widget').innerHTML = `
<p id="shuttle-widget-title">Shuttle Route</p>
<p id="route-title">Route 2 @ Boardwalk Stop</p>
<p style="margin-top: 1rem;">No Active Shuttle Routes.</p>
<span class="last-updated" id="last-updated-shuttle">Last Updated: ${lastUpdatedTime()}</span>
`;
}
}
catch(error){
console.error("UCF Shuttle Fetch Error:", error);
}
}
/*========================================================== Parking Function ==========================================================*/
async function getParkingData() {
try {
const response = await fetch("http://localhost:3001/parking");
const data = await response.json();
// Wanted Parking garages
const targetGarages = ["Garage A", "Garage B", "Garage C", "Garage D", "Garage H", "Garage I"];
const renderGarage = (item) => {
if (!item || !item.location || !item.location.counts) return '';
const stats = item.location.counts;
const name = item.location.name;
const occupied = stats.occupied;
const total = stats.total;
const available = stats.available;
const percent = Math.round((occupied / total) * 100);
let statusColor = "";
let statusColorHeader = "";
if(percent >= 90){
statusColor = "rgb(212, 47, 47)";
statusColorHeader = "rgb(172, 40, 40)";
}
else if(percent >= 75){
statusColor = "#c78d3c";
statusColorHeader = "#9b6f32";
}
else{
statusColor = "#41c7a8";
statusColorHeader = "#2f917a";
}
return `
<div class="garage-info" style="text-align: center; background-color: ${statusColor}; box-shadow: 0 0 .3rem ${statusColor};">
<span class="garage-name" style="background-color: ${statusColorHeader};">${name}</span>
<span class="garage-percent">${percent}% Full</span>
<p class="spots-left">${available} spots remaining</p>
</div>
`;
};
// Using .map() to find each specific garage from the list
const mostGaragesHTML = targetGarages.map(garageName => {
// Find the object in the API data where the location name matches our list
const garageData = data.find(item => item.location.name === garageName);
return renderGarage(garageData);
}).join(''); // Combine the array of HTML strings into one long string
document.getElementById('ucf-parking-widget').innerHTML = `
<p id="parking-title">Main Campus Parking</p>
<span class="last-updated" id="last-updated-parking">Last Updated: ${lastUpdatedTime()}</span>
<div id="parking-list">
${mostGaragesHTML}
</div>
`;
} catch (error) {
console.error("Parking Fetch Error:", error);
document.getElementById('ucf-parking-widget').innerHTML = "Failed to load parking data.";
}
}
/*========================================================== Solar Tracker ==========================================================*/
function updateSolarTracker(data){
const existingSolar = document.querySelector('.solar-container');
if(existingSolar){
existingSolar.remove();
}
const now = new Date();
const sunrise = new Date(data.daily.sunrise[0]);
const sunset = new Date(data.daily.sunset[0]);
// Calculate total daylight minutes and minutes passed since sunrise
const totalDaylight = (sunset - sunrise) / (1000 * 60);
const minutesPassed = (now - sunrise) / (1000 * 60);
// Calculate percentage (clamped between 0 and 100)
let percent = Math.min(Math.max((minutesPassed / totalDaylight) * 100, 0), 100);
// If it's night time, we'll show a "Night" state
const isNight = now < sunrise || now > sunset;
const sunIcon = isNight ? '🌕' : '☀️';
const statusText = isNight ? "Moonlight" : "Daylight";
// Logic for Night Time theme
const root = document.documentElement;
if(isNight){
root.style.setProperty('--bg', '#0D0D0B');
root.style.setProperty('--text-primary', '#E0DFD5');
root.style.setProperty('--text-secondary', '#63635E');
root.style.setProperty('--widget-bg', '#1A1A18');
root.style.setProperty('--widget-border', 'rgba(255, 255, 255, 0.05)');
root.style.setProperty('--accent', '#5a2b6a');
// Play sound ONLY when entering Night mode for the first time
if(!hasPlayedNightSound){
nightfallSound.play().catch(e => console.log("Audio blocked: Needs user interaction"));
hasPlayedNightSound = true;
hasPlayedDaySound = false; // load the Day sound for tomorrow morning
}
}
else{
root.style.setProperty('--bg', '#F5F2EC');
root.style.setProperty('--text-primary', '#1A1A18');
root.style.setProperty('--text-secondary', '#8A8880');
root.style.setProperty('--widget-bg', '#FFFFFF');
root.style.setProperty('--widget-border', 'rgba(0, 0, 0, 0.07)');
root.style.setProperty('--accent', '#d7fffe');
// Play sound ONLY when entering Day mode for the first time
if(!hasPlayedDaySound){
// Check if it's NOT the very first second of the script loading
daylightSound.play().catch(e => console.log("Audio blocked: Needs user interaction"));
hasPlayedDaySound = true;
hasPlayedNightSound = false; // load the Night sound for tonight
}
}
document.getElementById('weather-widget').innerHTML += `
<div class="solar-container">
<div class="solar-labels">
<span>${sunrise.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: true})}</span>
<span class="solar-status">${statusText}</span>
<span>${sunset.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: true})}</span>
</div>
<div class="solar-track">
<div class="sun-marker" style="left: ${percent}%">${sunIcon}</div>
</div>
</div>
`;
}
/*========================================================== Auxiliary Functions ==========================================================*/
function lastUpdatedTime(){
const lastUpdated = new Date(); // To see when we last updated the weather
let hours = lastUpdated.getHours(); // .padStart() function adds whatever character is specified at the beginning of the string if it doesn't have the required number of characters: in this case 2
const minutes = lastUpdated.getMinutes().toString().padStart(2, '0');
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12 || 12;
return `${hours}:${minutes} ${ampm}`;
}
function toggleMenu(){
const menu = document.getElementById('side-menu');
const button = document.getElementById('menu-toggle');
menu.classList.toggle('active');
button.classList.toggle('active');
}
// Close menu if user clicks outside of it
document.addEventListener('click', (e) => {
const menu = document.getElementById('side-menu');
const button = document.getElementById('menu-toggle');
if(!menu.contains(e.target) && !button.contains(e.target) && menu.classList.contains('active')){
toggleMenu();
}
});
// Run the functions!
updateClock();
getWeather();
getShuttleData();
getParkingData();
// Updating Function
setInterval(updateClock, 1000); // Refresh clock every second
setInterval(getWeather, 600000); // Refresh weather every 10 minutes
setInterval(getShuttleData, 20000); // Refresh Route 2 every 20 seconds
setInterval(getParkingData, 300000); // Refresh Parking every 5 minutes
// Auto-retry when internet comes back
let isOnline = true;
window.addEventListener('online', () => {
if (!isOnline) {
isOnline = true;
console.log('Internet restored, refreshing data...');
getWeather();
getShuttleData();
getParkingData();
}
});
window.addEventListener('offline', () => {
isOnline = false;
console.log('Internet lost...');
});