-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpopup-fix-simple.js
More file actions
631 lines (545 loc) · 22.1 KB
/
popup-fix-simple.js
File metadata and controls
631 lines (545 loc) · 22.1 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
/**
* Safecast Popup Display Fix - Simplified Version
* This script focuses on correctly calculating and displaying the average radiation value
*/
(function() {
// Global variable to track if radiation sensors are enabled
window.radiationSensorsEnabled = true;
// Wait for the page to fully load and for RTMKS to be defined
window.addEventListener('load', function() {
console.log('Page loaded, checking for RTMKS...');
function checkAndApplyFix() {
if (typeof RTMKS === 'undefined') {
console.log('Waiting for RTMKS to be defined...');
setTimeout(checkAndApplyFix, 500);
return;
}
console.log('Safecast Popup Fix loaded - RTMKS found');
applyFixes();
}
checkAndApplyFix();
});
function applyFixes() {
// Store the original GetInfoWindowHtmlForParams function
const originalGetInfoWindowHtmlForParams = RTMKS.GetInfoWindowHtmlForParams;
// Override the GetInfoWindowHtmlForParams function
RTMKS.GetInfoWindowHtmlForParams = function(
locations, lats, lons, device_urns, device_classes,
cpms, values, tubeTypes, unixSSs, imgs, loc,
mini, tblw, fontCssClass, showGraph, showID
) {
console.log('Patched GetInfoWindowHtmlForParams called with:', {
locations, device_urns, device_classes, cpms, tubeTypes, values
});
// Extract device info from imgs if available
let deviceInfo = null;
if (imgs && imgs.length > 0) {
try {
deviceInfo = JSON.parse(imgs[0]);
console.log('Parsed device info:', deviceInfo);
} catch (error) {
console.log('Could not parse imgs as JSON:', error);
}
}
// Get the device URN
let deviceUrn = '';
if (device_urns && device_urns.length > 0) {
deviceUrn = device_urns[0];
} else if (deviceInfo && deviceInfo.device_urn) {
deviceUrn = deviceInfo.device_urn;
}
// Get the device class
let deviceClass = '';
if (device_classes && device_classes.length > 0) {
deviceClass = device_classes[0];
} else if (deviceInfo && deviceInfo.device_class) {
deviceClass = deviceInfo.device_class;
}
// Get the location name
let displayLocation = '';
if (locations && locations.length > 0) {
displayLocation = locations[0];
} else if (deviceInfo && deviceInfo.location) {
displayLocation = deviceInfo.location;
} else if (deviceClass && deviceUrn) {
const parts = deviceUrn.split(':');
if (parts.length > 1) {
displayLocation = deviceClass + ' ' + parts[1];
} else {
displayLocation = deviceClass + ' ' + deviceUrn;
}
} else {
displayLocation = 'Unknown Device';
}
// Get the measurement time
let measurementTime = '';
if (deviceInfo && deviceInfo.when_captured) {
try {
const date = new Date(deviceInfo.when_captured);
measurementTime = date.toLocaleString();
} catch (error) {
console.log('Error parsing date:', error);
}
} else if (unixSSs && unixSSs.length > 0) {
try {
const date = new Date(unixSSs[0] * 1000);
measurementTime = date.toLocaleString();
} catch (error) {
console.log('Error formatting date:', error);
}
}
// Process tube data
let hasTubeData = false;
let tubeData = {};
let activeTubes = [];
// Check if cpms is an array of arrays (nested array)
let flatCpms = cpms;
if (cpms && cpms.length > 0 && Array.isArray(cpms[0])) {
flatCpms = cpms[0];
}
// Check if tubeTypes is an array of arrays (nested array)
let flatTubeTypes = tubeTypes;
if (tubeTypes && tubeTypes.length > 0 && Array.isArray(tubeTypes[0])) {
flatTubeTypes = tubeTypes[0];
}
// Process tube data if available
if (flatTubeTypes && flatTubeTypes.length > 0 && flatCpms && flatCpms.length > 0) {
hasTubeData = true;
// Create tubeData object
for (let i = 0; i < flatTubeTypes.length; i++) {
if (i < flatCpms.length) {
const tubeType = flatTubeTypes[i];
const cpmValue = flatCpms[i];
// Skip invalid values
if (!cpmValue || isNaN(parseFloat(cpmValue))) {
continue;
}
// Determine conversion factor
let conversionFactor = 0.0057; // Default
if (tubeType === 'lnd_7318u') {
conversionFactor = 0.0024; // LND-7318u
} else if (tubeType === 'lnd_7128ec') {
conversionFactor = 0.0063; // LND-7128ec
} else if (tubeType === 'lnd_712u') {
conversionFactor = 0.0081; // LND-712u
} else if (tubeType === 'lnd_7318c') {
conversionFactor = 0.0059; // LND-7318c
}
// Calculate µSv/h value
const usvhValue = cpmValue * conversionFactor;
// Store tube data
tubeData[tubeType] = cpmValue;
// Add to active tubes
activeTubes.push({
type: tubeType,
cpm: cpmValue,
factor: conversionFactor,
usvh: usvhValue
});
console.log('Tube:', tubeType, 'CPM:', cpmValue, 'Factor:', conversionFactor, 'µSv/h:', usvhValue.toFixed(3));
}
}
}
// Calculate average radiation value
let totalValue = 0;
let tubeCount = 0;
let averageValue = 0;
activeTubes.forEach(tube => {
totalValue += tube.usvh;
tubeCount++;
});
if (tubeCount > 0) {
averageValue = totalValue / tubeCount;
}
console.log('Device:', deviceUrn, 'Total:', totalValue.toFixed(3), 'Count:', tubeCount, 'Average:', averageValue.toFixed(3));
// Build custom popup HTML
let html = "<div style='font-family: Arial, sans-serif; padding: 10px; width: 100%;'>";
// Title: Bold device name
html += "<div style='font-size:16px; font-weight:bold; margin-bottom:10px;'>" + displayLocation + "</div>";
// Device section
html += "<div style='font-size:14px; font-weight:bold; margin-top:10px;'>Device</div>";
html += "<div style='font-size:13px; margin-top:5px;'>Device URN: " + deviceUrn + "</div>";
html += "<div style='font-size:13px;'>Device Class: " + deviceClass + "</div>";
// Radiation section
html += "<div style='font-size:14px; font-weight:bold; margin-top:15px;'>Radiation</div>";
// Show calculated average value
html += "<div style='font-size:16px; margin-top:5px;'>" + averageValue.toFixed(3) + " \u00b5Sv/h</div>";
// Show CPM values if available
if (hasTubeData) {
html += "<div style='font-size:13px; margin-top:5px;'>CPM</div>";
// Display each tube's data
activeTubes.forEach(tube => {
html += "<div style='font-size:13px; margin-top:3px;'>" + tube.type + ": " + tube.cpm +
" CPM (" + tube.usvh.toFixed(3) + " \u00b5Sv/h)</div>";
});
}
// Measurement time
if (measurementTime) {
html += "<div style='font-size:13px; margin-top:15px;'>Measured at: " + measurementTime + "</div>";
}
// More info link
html += "<div style='font-size:13px; margin-top:15px;'><a href='#' onclick='return false;'>More info</a></div>";
html += "</div>";
return html;
};
// Add the radiation toggle button
setTimeout(function() {
addRadiationToggleButton();
fetchRealSensorData();
}, 3000);
}
// Function to add the toggle button to the UI
function addRadiationToggleButton() {
// Check if the air quality toggle button exists to position our button next to it
var airQualityBtn = document.querySelector('.air-quality-toggle');
var parentElement = airQualityBtn ? airQualityBtn.parentElement : document.body;
// Create the radiation toggle button
var radiationBtn = document.createElement('button');
radiationBtn.id = 'toggle-radiation-btn';
radiationBtn.textContent = 'Hide Radiation Sensors';
radiationBtn.className = 'radiation-toggle';
radiationBtn.style.cssText = 'position: absolute; top: 70px; right: 10px; z-index: 1000; background-color: white; border: 1px solid #ccc; padding: 5px 10px; border-radius: 4px; cursor: pointer;';
radiationBtn.onclick = window.toggleRadiationSensors;
// Add the button to the page
parentElement.appendChild(radiationBtn);
}
// Function to toggle radiation sensors visibility
window.toggleRadiationSensors = function() {
window.radiationSensorsEnabled = !window.radiationSensorsEnabled;
console.log('Radiation sensors ' + (window.radiationSensorsEnabled ? 'enabled' : 'disabled'));
// Clear existing markers
if (window.allMarkers && window.allMarkers.length > 0) {
for (var i = 0; i < window.allMarkers.length; i++) {
if (window.allMarkers[i].marker) {
window.allMarkers[i].marker.setMap(null);
}
if (window.allMarkers[i].recentCircle) {
window.allMarkers[i].recentCircle.setMap(null);
}
}
window.allMarkers = [];
}
// Reload markers if enabled
if (window.radiationSensorsEnabled) {
fetchRealSensorData();
}
// Update button state
var button = document.getElementById('toggle-radiation-btn');
if (button) {
button.textContent = window.radiationSensorsEnabled ? 'Hide Radiation Sensors' : 'Show Radiation Sensors';
}
};
// Function to fetch real sensor data from the API
function fetchRealSensorData() {
// Skip if radiation sensors are disabled
if (!window.radiationSensorsEnabled) {
console.log('Radiation sensors are disabled, skipping fetch');
return;
}
console.log('Fetching real sensor data from API...');
// Clear any existing markers first
if (window.allMarkers && window.allMarkers.length > 0) {
console.log('Clearing', window.allMarkers.length, 'existing markers');
for (var i = 0; i < window.allMarkers.length; i++) {
if (window.allMarkers[i].marker) {
window.allMarkers[i].marker.setMap(null);
}
if (window.allMarkers[i].recentCircle) {
window.allMarkers[i].recentCircle.setMap(null);
}
}
window.allMarkers = [];
}
// Add cache-busting parameter to prevent caching
var timestamp = new Date().getTime();
var url = '/tt-api/devices?t=' + timestamp;
// Fetch data from API
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.status);
}
return response.text();
})
.then(text => {
console.log('Received response from API, length:', text.length);
// Try to parse the response as JSON
try {
// Clean the text if needed
let cleanedText = text;
// Try to find where the JSON actually starts and ends
let jsonStart = cleanedText.indexOf('[');
let jsonEnd = cleanedText.lastIndexOf(']') + 1;
if (jsonStart >= 0 && jsonEnd > jsonStart) {
cleanedText = cleanedText.substring(jsonStart, jsonEnd);
} else {
throw new Error('Could not find JSON array in response');
}
// Additional cleaning for problematic characters
cleanedText = cleanedText
.replace(/[^\x20-\x7E]/g, '') // Remove non-printable ASCII
.replace(/\u0000/g, '') // Remove null bytes
.replace(/[\r\n]+/g, '') // Remove newlines
.replace(/,\s*}/g, '}') // Fix trailing commas in objects
.replace(/,\s*\]/g, ']'); // Fix trailing commas in arrays
// Parse the JSON
const devices = JSON.parse(cleanedText);
console.log('Successfully parsed device data, count:', devices.length);
// Filter out devices without location data
const validDevices = devices.filter(device =>
device &&
device.loc_lat &&
device.loc_lon &&
!isNaN(parseFloat(device.loc_lat)) &&
!isNaN(parseFloat(device.loc_lon))
);
console.log('Valid devices with location data:', validDevices.length);
if (validDevices.length > 0) {
// Create markers for these devices
createMarkersFromDevices(validDevices);
return;
} else {
throw new Error('No valid devices with location data found');
}
} catch (error) {
console.error('Error processing device data:', error);
// Only use mock data if we couldn't get real data
useMockData();
}
})
.catch(error => {
console.error('Error fetching device data:', error);
useMockData();
});
}
// Function to use mock data as a fallback
function useMockData() {
console.log('Using mock device data');
const mockDevices = [
{
"device_urn": "safecast:4007513236",
"device_class": "safecast",
"device": 4007513236,
"when_captured": "2021-06-13T10:32:46Z",
"loc_lat": 35.6695,
"loc_lon": 139.7117,
"lnd_7318u": 28,
"lnd_7128ec": 9,
"service_uploaded": "2021-06-13T10:32:46Z"
},
{
"device_urn": "safecast:2651380949",
"device_class": "safecast",
"device": 2651380949,
"when_captured": "2024-04-15T22:49:45Z",
"loc_lat": 35.6595,
"loc_lon": 139.7217,
"lnd_7318u": 696,
"lnd_7128ec": 249,
"service_uploaded": "2024-04-15T22:49:45Z"
}
];
// Create markers for the mock devices
createMarkersFromDevices(mockDevices);
}
// Function to create markers from device data
function createMarkersFromDevices(devices) {
// Skip if radiation sensors are disabled
if (!window.radiationSensorsEnabled) {
console.log('Radiation sensors are disabled, skipping marker creation');
return;
}
console.log('Creating markers for', devices.length, 'devices');
// Initialize global marker array if it doesn't exist
if (!window.allMarkers) {
window.allMarkers = [];
}
// Process each device
for (var i = 0; i < devices.length; i++) {
var device = devices[i];
// Skip devices without valid location
if (!device.loc_lat || !device.loc_lon ||
isNaN(parseFloat(device.loc_lat)) ||
isNaN(parseFloat(device.loc_lon))) {
continue;
}
// Create position
var position = new google.maps.LatLng(
parseFloat(device.loc_lat),
parseFloat(device.loc_lon)
);
// Extract tube data
var tubeData = {};
var tubeTypes = [];
var cpmValues = [];
var activeTubes = [];
// Process all available tube types
if (device.lnd_7318u) {
tubeData['lnd_7318u'] = device.lnd_7318u;
tubeTypes.push('lnd_7318u');
cpmValues.push(device.lnd_7318u);
activeTubes.push({
type: 'lnd_7318u',
cpm: device.lnd_7318u,
factor: 0.0024, // LND-7318u conversion factor
usvh: device.lnd_7318u * 0.0024
});
}
if (device.lnd_7128ec) {
tubeData['lnd_7128ec'] = device.lnd_7128ec;
tubeTypes.push('lnd_7128ec');
cpmValues.push(device.lnd_7128ec);
activeTubes.push({
type: 'lnd_7128ec',
cpm: device.lnd_7128ec,
factor: 0.0063, // LND-7128ec conversion factor
usvh: device.lnd_7128ec * 0.0063
});
}
if (device.lnd_712u) {
tubeData['lnd_712u'] = device.lnd_712u;
tubeTypes.push('lnd_712u');
cpmValues.push(device.lnd_712u);
activeTubes.push({
type: 'lnd_712u',
cpm: device.lnd_712u,
factor: 0.0081, // LND-712u conversion factor
usvh: device.lnd_712u * 0.0081
});
}
if (device.lnd_7318c) {
tubeData['lnd_7318c'] = device.lnd_7318c;
tubeTypes.push('lnd_7318c');
cpmValues.push(device.lnd_7318c);
activeTubes.push({
type: 'lnd_7318c',
cpm: device.lnd_7318c,
factor: 0.0059, // LND-7318c conversion factor
usvh: device.lnd_7318c * 0.0059
});
}
// Check if the measurement is recent (within 4 hours)
var isRecent = false;
if (device.when_captured) {
var capturedTime = new Date(device.when_captured).getTime();
var currentTime = new Date().getTime();
var fourHoursInMs = 4 * 60 * 60 * 1000;
isRecent = (currentTime - capturedTime) <= fourHoursInMs;
}
// Create SVG icons that match the legend exactly
function createSvgIcon(isOnline) {
// Based on the legend image, create exact replicas
var outerCircleColor, innerCircleColor, dotColor;
if (isOnline) {
// Online icon: Green outer circle, white inner circle, blue dot
outerCircleColor = '#00AA00'; // Darker green for outer circle
innerCircleColor = '#FFFFFF'; // White inner circle
dotColor = '#0000FF'; // Blue dot
} else {
// Offline icon: Dashed gray circles, white inner circle, blue dot
outerCircleColor = '#666666'; // Darker gray for outer circle
innerCircleColor = '#FFFFFF'; // White inner circle
dotColor = '#0000FF'; // Blue dot
}
// Create SVG icon matching the legend exactly
var svg;
if (isOnline) {
// Online icon: Solid green outer circle, white inner circle, blue dot
svg = `
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="11" fill="${outerCircleColor}" stroke="#000000" stroke-width="1"/>
<circle cx="12" cy="12" r="8" fill="${innerCircleColor}" stroke="#000000" stroke-width="1"/>
<circle cx="12" cy="12" r="3" fill="${dotColor}" stroke="#000000" stroke-width="0.5"/>
</svg>
`;
} else {
// Offline icon: Dashed/broken gray circles, white inner circle, blue dot
svg = `
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="11" fill="transparent" stroke="${outerCircleColor}" stroke-width="2" stroke-dasharray="3,3"/>
<circle cx="12" cy="12" r="8" fill="${innerCircleColor}" stroke="${outerCircleColor}" stroke-width="1.5" stroke-dasharray="3,3"/>
<circle cx="12" cy="12" r="3" fill="${dotColor}" stroke="#000000" stroke-width="0.5"/>
</svg>
`;
}
return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
}
// Generate icon URL
var iconUrl = createSvgIcon(isRecent);
// Create marker with custom icon
var marker = new google.maps.Marker({
position: position,
map: window.map,
title: device.device_class + ' ' + (device.device_urn ? device.device_urn.split(':')[1] : device.device),
icon: {
url: iconUrl,
scaledSize: new google.maps.Size(24, 24),
anchor: new google.maps.Point(12, 12)
}
});
// Store device data with the marker
marker.deviceData = device;
marker.tubeData = tubeData;
marker.tubeTypes = tubeTypes;
marker.cpmValues = cpmValues;
marker.activeTubes = activeTubes;
// Add click event to show info window
marker.addListener('click', function() {
// Close any existing info window
if (window.currentInfoWindow) {
window.currentInfoWindow.close();
}
// Get the device data from the marker
var device = this.deviceData;
var tubeTypes = this.tubeTypes;
var cpmValues = this.cpmValues;
var activeTubes = this.activeTubes;
if (device) {
// Format the location/title
var title = '';
if (device.device_class && device.device_urn) {
const deviceNumber = typeof device.device_urn === 'string' ?
device.device_urn.split(':')[1] || '' :
String(device.device_urn).split(':')[1] || '';
title = device.device_class + ' ' + deviceNumber;
} else {
title = 'Unknown Device';
}
// Create info window content
var content = RTMKS.GetInfoWindowHtmlForParams(
[title], // locations
[device.loc_lat || ''], // lats
[device.loc_lon || ''], // lons
[device.device_urn || ''], // device_urns
[device.device_class || ''], // device_classes
cpmValues, // cpms (array of CPM values)
['0.000'], // values (this will be calculated in the GetInfoWindowHtmlForParams function)
tubeTypes, // tube types
[new Date(device.when_captured).getTime() / 1000], // unixSSs
[JSON.stringify(device)], // locations_info
0, // i
false, // mini
400, // tblw
'', // fontCssClass
false, // showGraph
false // showID
);
// Create info window
var infoWindow = new google.maps.InfoWindow({
content: content,
maxWidth: 400
});
// Store the current info window
window.currentInfoWindow = infoWindow;
// Open the info window
infoWindow.open(window.map, this);
}
});
// Store marker in global array for later cleanup
window.allMarkers.push({
marker: marker
});
}
console.log('Created', window.allMarkers.length, 'markers');
}
})();