-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
321 lines (285 loc) · 10.3 KB
/
index.html
File metadata and controls
321 lines (285 loc) · 10.3 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
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css"
integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
crossorigin=""/>
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js"
integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
crossorigin=""></script>
<style>
html, body {
height: 100%;
padding: 0;
margin: 0;
}
#map {
/* configure the size of the map */
width: 100vw;
height: 50%;
}
button {
border-radius: 5px;
background-color: rgb(104, 156, 246);
border-width: 1px;
padding: 5px;
margin-left: 3px;
}
button:hover {
transform: scale(1.1);
}
input {
width: 100%;
}
#errorDiv {
position: fixed;
width: 100%;
background-color: red;
bottom: 0px;
}
#downloadDiv {
position: fixed;
width: 100%;
bottom: 0px;
background-color: rgb(114, 170, 158);
padding: 5px;
}
</style>
<title>Experiment Tool</title>
</head>
<body>
<div id="map"> </div>
<div id="inputArea">
<h4> Coordinates <a id="highAccuracy">(High accuracy)</a></h4>
<a id="geoPosition"> </a>
<button onclick="setWatcher()"> Reload Position </button>
<table>
<tr>
<td><label for="input-soc">State of Charge (%):</label></td>
<td><input type="number" id="input-soc" name="input-soc" min="0" max="100" step="0.1" placeholder="SoC"></td>
<td>
<button onclick="changeInputValue('input-soc', -10)">-10</button>
<button onclick="changeInputValue('input-soc', -1)">-1</button>
<button onclick="changeInputValue('input-soc', +1)">+1</button>
<button onclick="changeInputValue('input-soc', +10)">+10</button>
</td>
</tr>
</table>
<button onclick="resetTripTime()">Reset trip start</button>
<div id="details"></div>
<button onclick="getScreenLock()"> Request screenlock <a id="screenlock-status"></a></button>
<div id="downloadDiv">
<button onclick="downloadCurrentData()"> Download data </button>
<button onclick="downloadLocalStorage()"> Download local storage</button>
<button id="resetLocalStorage" onclick="resetLocalStorage()"> Reset local storage </button>
</div>
<div id="errorDiv"></div>
</div>
</body>
<script>
// Setup Map:
var map = L.map("map", { zoomControl: false }).setView([51.163361, 10.447683], 7);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '',
maxZoom: 18,
tileSize: 512,
zoomOffset: -1
}).addTo(map);
function removeLeafletAttribution() { //to avoid accidental clicking
try {
const attribution = document.getElementsByClassName("leaflet-control-attribution leaflet-control");
attribution[0].parentNode.removeChild(attribution[0]);
}
finally {}
}
removeLeafletAttribution();
// Get Query Parameters:
var enableHighAccuracy = true;
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
if (urlParams.get('disableHighAccuracy') == "true")
{
console.log("Disabling high accuracy");
enableHighAccuracy = false;
document.getElementById("highAccuracy").innerHTML = "";
}
// Geolocation:
var marker, circle, lat, long, accuracy, watcher, posObject;
var timestamp = 0;
var updateCount = 0;
function displayPosition(position) {
if (position.timestamp - timestamp < 5000)
return;
updateCount += 1;
posObject = geolocationToObject(position);
lat = position.coords.latitude;
long = position.coords.longitude;
accuracy = position.coords.accuracy;
timestamp = new Date(position.timestamp);
updateData();
const el = document.getElementById("geoPosition");
// const options = { hour: "numeric" };
el.innerHTML = `${lat.toFixed(5)}, ${long.toFixed(5)} (updated: ${timestamp.toLocaleTimeString('de-DE')}, count: ${updateCount})`;
if (marker) {
map.removeLayer(marker);
}
if (circle) {
map.removeLayer(circle);
}
marker = L.marker([lat, long]);
circle = L.circle([lat, long], { radius: accuracy });
var featureGroup = L.featureGroup([marker, circle]).addTo(map);
fillinFields(posObject);
map.fitBounds(featureGroup.getBounds());
}
function geolocationToObject(position) {
const timestring = new Date(position.timestamp);
return {
timestamp: position.timestamp,
timestring: timestring.toLocaleTimeString("de-DE"),
tripTime: Math.round((timestring - sessionTimestamp) / 1000),
accuracy: Math.round(position.coords.accuracy * 100) / 100,
altitude: Math.round(position.coords.altitude * 100) / 100,
heading: position.coords.heading,
latitude: position.coords.latitude,
longitude: position.coords.longitude,
speed: position.coords.speed ? Math.round(position.coords.speed * 3.6 * 100)/100. : null
};
}
function fillinFields(coords) {
const target = document.getElementById("details");
target.innerHTML = "";
target.innerHTML += `Trip time: ${coords.tripTime} <br>`;
target.innerHTML += `Accuracy: ${coords.accuracy} <br>`;
target.innerHTML += `Altitude: ${coords.altitude} <br>`;
target.innerHTML += `Heading: ${coords.heading} <br>`;
target.innerHTML += `Speed: ${coords.speed} <br>`;
}
function setWatcher() {
if (watcher)
navigator.geolocation.clearWatch(watcher);
watcher = navigator.geolocation.watchPosition(displayPosition,
(e) => {window.alert(e.message); error(e.message);},
{maximumAge: 5000, timeout: 5000, enableHighAccuracy});
}
if (!navigator.geolocation) {
error("Your browser doesn't support geolocation feature!");
} else {
setWatcher();
}
// Datacollection:
const sessionTimestamp = new Date();
function resetTripTime() {
sessionTimestamp = new Date();
}
const sessionTime = (new Date()).toLocaleString();
var data = [];
var autosave = false; // CHANGE THIS IF NECESSARY
function updateData(automatic = true) {
const obj = JSON.parse(JSON.stringify(posObject));
obj["automatic"] = automatic;
obj["SoCInput"] = parseFloat(document.getElementById("input-soc").value);
data.push(obj);
updateLocalStorage();
}
function downloadCurrentData() {
downloadData(data, `exp_${sessionTime}`);
}
function downloadData(dataObject, filename) {
downloadCsv(dataObject, filename);
downloadDataString(JSON.stringify(dataObject, null, 4), "json", filename);
}
function downloadDataString(dataString, dataFormat, filename) {
var dataStr = `data:text/${dataFormat};charset=utf-8,` + encodeURIComponent(dataString);
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", `${filename}.${dataFormat}`);
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
function downloadCsv(object, filename) {
let str = "";
str += "timestamp,timestring,tripTime,accuracy,altitude,heading,latitude,longitude,speed,automatic,SoC\n";
object.forEach((i) => {
const itemString = `${i.timestamp},${i.timestring},${i.tripTime},${i.accuracy},${i.altitude},${i.heading},${i.latitude},${i.longitude},${i.speed},${i.automatic},${i.SoCInput}\n`;
str += itemString;
});
downloadDataString(str, "csv", filename);
}
window.onbeforeunload = function(){
if (data.length > 0 && autosave)
downloadData();
}
function resetLocalStorage() {
localStorage.clear();
}
document.getElementById("resetLocalStorage").innerHTML = `Reset local storage (${localStorage.length} items)`
function downloadLocalStorage() {
console.log("Downloading local storage...");
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const d = localStorage.getItem(key);
try {
const parsed = JSON.parse(d);
downloadData(parsed, key);
} catch {
error(`Error with parsing data of key "${key}".`);
}
}
console.log("Done.");
}
function changeInputValue(id, change) {
const el = document.getElementById(id);
let currentValue = parseFloat(el.value);
if (isNaN(currentValue))
currentValue = 0.0;
let newValue = currentValue + change;
if (el.min)
newValue = Math.max(parseFloat(el.min), newValue);
if (el.max)
newValue = Math.min(parseFloat(el.max), newValue);
el.value = newValue;
}
function updateLocalStorage() {
try {
localStorage.setItem(`data_${sessionTime}`, JSON.stringify(data));
} catch {
error("Error when setting local storage.");
}
}
function error(message) {
console.error(message);
window.navigator.vibrate(500);
document.getElementById("errorDiv").innerHTML = message;
setInterval(() => {
document.getElementById("errorDiv").innerHTML = "";
}, 20000);
}
function isScreenLockSupported() {
return ('wakeLock' in navigator);
}
var screenLock;
async function getScreenLock() {
if(isScreenLockSupported()){
try {
navigator.wakeLock.request('screen')
.then(lock => {
screenLock = lock;
console.log("Screenlock granted:", lock);
document.getElementById("screenlock-status").innerHTML = "(on)";
screenLock.onrelease = () => {
error("Screenlock was released.");
document.getElementById("screenlock-status").innerHTML = "(off)";
};
});
} catch(err) {
error(err.message);
}
} else {
error("Screenlock is not supported on this device.");
}
}
getScreenLock();
</script>