Browse code

Merge branch 'strava-upload' of ssh://jonget.fr:5522/volume1/web/gitlist.1.0.2/repos/bike_companion into strava-upload

louis.jonget authored on17/03/2023 15:54:23
Showing1 changed files
... ...
@@ -15,140 +15,140 @@ var client_id = "94880";
15 15
 var client_secret = "08dc170f0fe38f39dd327bea82a28db4400e6f00";
16 16
 
17 17
 var firstlocationOptions = {
18
-  'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
19
-  'timeout': 60000, //60s timeout to get a first good signal
20
-  'maximumAge': 0 // no cache
18
+    'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
19
+    'timeout': 60000, //60s timeout to get a first good signal
20
+    'maximumAge': 0 // no cache
21 21
 };
22 22
 var locationOptions = {
23
-  'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
24
-  'timeout': 5000, //5s timeout to get a good signal
25
-  'maximumAge': 0 // no cache
23
+    'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
24
+    'timeout': 5000, //5s timeout to get a good signal
25
+    'maximumAge': 0 // no cache
26 26
 };
27 27
 
28
-Pebble.addEventListener('showConfiguration', function (e) {
29
-  clay.config = clayConfig;
30
-  console.log("Clay config is showing...")
31
-  Pebble.openURL(clay.generateUrl());
28
+Pebble.addEventListener('showConfiguration', function(e) {
29
+    clay.config = clayConfig;
30
+    console.log("Clay config is showing...")
31
+    Pebble.openURL(clay.generateUrl());
32 32
 });
33 33
 
34
-Pebble.addEventListener('webviewclosed', function (t) {
35
-  if (!t || t.response) {
36
-    console.log("Clay config is submitted : " + t.response)
37
-    try {
38
-      if (data = JSON.parse(t.response), data.code && data.scope == "read,activity:write") {
39
-        if (data.state == "bike_companion" && data.scope == "read,activity:write") {
40
-          getTokens(data.code);
41
-        } else {
42
-          console.log("Error on response returned : scope is " + grantcode.scope + " and state is " + grantcode.state);
34
+Pebble.addEventListener('webviewclosed', function(t) {
35
+    if (!t || t.response) {
36
+        console.log("Clay config is submitted : " + t.response)
37
+        try {
38
+            if (data = JSON.parse(t.response), data.code && data.scope == "read,activity:write") {
39
+                if (data.state == "bike_companion" && data.scope == "read,activity:write") {
40
+                    getTokens(data.code);
41
+                } else {
42
+                    console.log("Error on response returned : scope is " + grantcode.scope + " and state is " + grantcode.state);
43
+                }
44
+            } else {
45
+                clay.getSettings(t.response);
46
+                console.log("Clay settings in Localstorage looks like " + localStorage.getItem("clay-settings"));
47
+            }
48
+        } catch (t) {
49
+            console.log("Oauth parsing error, continue on saving clay settings");
50
+            clay.getSettings(t.response);
51
+            var claysettings = JSON.parse(localStorage.getItem('clay-settings'))
52
+            claysettings.strava_enabled = false;
53
+            localStorage.setItem("clay-settings", JSON.stringify("claysettings"));
54
+            console.log("Clay settings in Localstorage looks like " + localStorage.getItem("clay-settings"));
43 55
         }
44
-      } else {
45
-        clay.getSettings(t.response);
46
-        console.log("Clay settings in Localstorage looks like " + localStorage.getItem("clay-settings"));
47
-      }
48
-    } catch (t) {
49
-      console.log("Oauth parsing error, continue on saving clay settings");
50
-      clay.getSettings(t.response);
51
-      var claysettings = JSON.parse(localStorage.getItem('clay-settings'))
52
-      claysettings.strava_enabled = false;
53
-      localStorage.setItem("clay-settings", JSON.stringify("claysettings"));
54
-      console.log("Clay settings in Localstorage looks like " + localStorage.getItem("clay-settings"));
55
-    }
56 56
 
57
-  }
57
+    }
58 58
 });
59 59
 
60 60
 // Calculate the distance from 2 geoloc in degrees.
61 61
 // IMPORTANT : this is a calculation from 2D projection, altitude is not involved
62 62
 //
63 63
 function distance_on_geoid(lat1, lon1, lat2, lon2) {
64
-  // Convert degrees to radians
65
-  lat1 = lat1 * Math.PI / 180.0;
66
-  lon1 = lon1 * Math.PI / 180.0;
67
-  lat2 = lat2 * Math.PI / 180.0;
68
-  lon2 = lon2 * Math.PI / 180.0;
69
-  // radius of earth in metres
70
-  r = 6378100;
71
-  // P
72
-  rho1 = r * Math.cos(lat1);
73
-  z1 = r * Math.sin(lat1);
74
-  x1 = rho1 * Math.cos(lon1);
75
-  y1 = rho1 * Math.sin(lon1);
76
-  // Q
77
-  rho2 = r * Math.cos(lat2);
78
-  z2 = r * Math.sin(lat2);
79
-  x2 = rho2 * Math.cos(lon2);
80
-  y2 = rho2 * Math.sin(lon2);
81
-  // Dot product
82
-  dot = (x1 * x2 + y1 * y2 + z1 * z2);
83
-  cos_theta = dot / (r * r);
84
-  theta = Math.acos(cos_theta);
85
-  // Distance in Metres
86
-  return r * theta;
64
+    // Convert degrees to radians
65
+    lat1 = lat1 * Math.PI / 180.0;
66
+    lon1 = lon1 * Math.PI / 180.0;
67
+    lat2 = lat2 * Math.PI / 180.0;
68
+    lon2 = lon2 * Math.PI / 180.0;
69
+    // radius of earth in metres
70
+    r = 6378100;
71
+    // P
72
+    rho1 = r * Math.cos(lat1);
73
+    z1 = r * Math.sin(lat1);
74
+    x1 = rho1 * Math.cos(lon1);
75
+    y1 = rho1 * Math.sin(lon1);
76
+    // Q
77
+    rho2 = r * Math.cos(lat2);
78
+    z2 = r * Math.sin(lat2);
79
+    x2 = rho2 * Math.cos(lon2);
80
+    y2 = rho2 * Math.sin(lon2);
81
+    // Dot product
82
+    dot = (x1 * x2 + y1 * y2 + z1 * z2);
83
+    cos_theta = dot / (r * r);
84
+    theta = Math.acos(cos_theta);
85
+    // Distance in Metres
86
+    return r * theta;
87 87
 }
88 88
 
89 89
 // Adding leading characters to string for nice displays
90 90
 //
91 91
 function padStart(string, max_length, padding) {
92
-  if (string.length > max_length) {
93
-    return string;
94
-  } else {
95
-    var new_str = string;
96
-    for (index = string.length; index < max_length; index++) {
97
-      new_str = padding + new_str;
92
+    if (string.length > max_length) {
93
+        return string;
94
+    } else {
95
+        var new_str = string;
96
+        for (index = string.length; index < max_length; index++) {
97
+            new_str = padding + new_str;
98
+        }
99
+        return new_str;
98 100
     }
99
-    return new_str;
100
-  }
101 101
 }
102 102
 
103 103
 
104 104
 // Store location in Pebble app local storage
105 105
 //
106 106
 function storeLocation(position, first) {
107
-  var latitude = position.coords.latitude;
108
-  var longitude = position.coords.longitude;
109
-  var timestamp = position.timestamp;
110
-  if (first == true) {
111
-    localStorage.setItem("firstlatitude", latitude);
112
-    localStorage.setItem("firstlongitude", longitude);
113
-    localStorage.setItem("firsttimestamp", Date.now());
114
-    //console.log("-- First timestamp: " + localStorage.getItem("firsttimestamp"));
115
-    localStorage.setItem("totalcoordinates", 0)
116
-  }
107
+    var latitude = position.coords.latitude;
108
+    var longitude = position.coords.longitude;
109
+    var timestamp = position.timestamp;
110
+    if (first == true) {
111
+        localStorage.setItem("firstlatitude", latitude);
112
+        localStorage.setItem("firstlongitude", longitude);
113
+        localStorage.setItem("firsttimestamp", Date.now());
114
+        //console.log("-- First timestamp: " + localStorage.getItem("firsttimestamp"));
115
+        localStorage.setItem("totalcoordinates", 0)
116
+    }
117 117
 
118
-  localStorage.setItem("lastlatitude", latitude);
119
-  localStorage.setItem("lastlongitude", longitude);
120
-  localStorage.setItem("lasttimestamp", timestamp);
121
-  localStorage.setItem("totalcoordinates", parseInt(localStorage.getItem("totalcoordinates")) + 1)
122
-  // console.log("Stored location " + position.coords.latitude + ',' + position.coords.longitude);
118
+    localStorage.setItem("lastlatitude", latitude);
119
+    localStorage.setItem("lastlongitude", longitude);
120
+    localStorage.setItem("lasttimestamp", timestamp);
121
+    localStorage.setItem("totalcoordinates", parseInt(localStorage.getItem("totalcoordinates")) + 1)
122
+        // console.log("Stored location " + position.coords.latitude + ',' + position.coords.longitude);
123 123
 }
124 124
 
125 125
 // Get location from Pebble app local storage
126 126
 //
127 127
 function getLocation(first) {
128 128
 
129
-  if (first == false) {
130
-    if (localStorage.getItem("lastlatitude") || localStorage.getItem("lastlongitude") || localStorage.getItem("lasttimestamp")) {
131
-      var la = localStorage.getItem("lastlatitude");
132
-      var lo = localStorage.getItem("lastlongitude");
133
-      var ti = localStorage.getItem("lasttimestamp");
134
-      var co = { "latitude": la, "longitude": lo };
135
-      var pos = { "coords": co, "timestamp": ti };
136
-      return pos;
137
-    } else {
138
-      return null;
139
-    }
140
-  } else {
141
-    if (localStorage.getItem("firstlatitude") || localStorage.getItem("firstlongitude") || localStorage.getItem("firsttimestamp")) {
142
-      var la = localStorage.getItem("firstlatitude");
143
-      var lo = localStorage.getItem("firstlongitude");
144
-      var ti = localStorage.getItem("firsttimestamp");
145
-      var co = { "latitude": la, "longitude": lo };
146
-      var pos = { "coords": co, "timestamp": ti };
147
-      return pos;
129
+    if (first == false) {
130
+        if (localStorage.getItem("lastlatitude") || localStorage.getItem("lastlongitude") || localStorage.getItem("lasttimestamp")) {
131
+            var la = localStorage.getItem("lastlatitude");
132
+            var lo = localStorage.getItem("lastlongitude");
133
+            var ti = localStorage.getItem("lasttimestamp");
134
+            var co = { "latitude": la, "longitude": lo };
135
+            var pos = { "coords": co, "timestamp": ti };
136
+            return pos;
137
+        } else {
138
+            return null;
139
+        }
148 140
     } else {
149
-      return null;
141
+        if (localStorage.getItem("firstlatitude") || localStorage.getItem("firstlongitude") || localStorage.getItem("firsttimestamp")) {
142
+            var la = localStorage.getItem("firstlatitude");
143
+            var lo = localStorage.getItem("firstlongitude");
144
+            var ti = localStorage.getItem("firsttimestamp");
145
+            var co = { "latitude": la, "longitude": lo };
146
+            var pos = { "coords": co, "timestamp": ti };
147
+            return pos;
148
+        } else {
149
+            return null;
150
+        }
150 151
     }
151
-  }
152 152
 
153 153
 
154 154
 }
... ...
@@ -156,25 +156,25 @@ function getLocation(first) {
156 156
 // Get max speed of the run
157 157
 //
158 158
 function getMaxSpeed(lastSpeed) {
159
-  oldmax = localStorage.getItem("maxSpeed") || -1;
160
-  if (oldmax < lastSpeed) {
161
-    maxSpeed = lastSpeed
162
-  } else if (oldmax > lastSpeed) {
163
-    maxSpeed = oldmax
164
-  } else {
165
-    maxSpeed = oldmax
166
-  }
167
-  localStorage.setItem("maxSpeed", maxSpeed);
168
-  return maxSpeed
159
+    oldmax = localStorage.getItem("maxSpeed") || -1;
160
+    if (oldmax < lastSpeed) {
161
+        maxSpeed = lastSpeed
162
+    } else if (oldmax > lastSpeed) {
163
+        maxSpeed = oldmax
164
+    } else {
165
+        maxSpeed = oldmax
166
+    }
167
+    localStorage.setItem("maxSpeed", maxSpeed);
168
+    return maxSpeed
169 169
 }
170 170
 
171 171
 // split float number into an array of int (null returned instead of 0 for decimal)
172 172
 //
173 173
 function splitFloatNumber(num) {
174
-  const intStr = num.toString().split('.')[0];
175
-  var decimalStr = num.toString().split('.')[1];
176
-  if (decimalStr === undefined) { decimalStr = 0 } else { decimalStr = decimalStr }
177
-  return [Number(intStr), Number(decimalStr)];
174
+    const intStr = num.toString().split('.')[0];
175
+    var decimalStr = num.toString().split('.')[1];
176
+    if (decimalStr === undefined) { decimalStr = 0 } else { decimalStr = decimalStr }
177
+    return [Number(intStr), Number(decimalStr)];
178 178
 
179 179
 }
180 180
 
... ...
@@ -189,10 +189,10 @@ function GPXHeadersBuilder(timestamp, name, type) {
189 189
 // Build GPX track point
190 190
 //
191 191
 function GPXtrkptBuilder(lat, lon, ele, timestamp) {
192
-  var GPX = localStorage.getItem("GPX");
193
-  var trkpt = '<trkpt lat="' + lat + '" lon="' + lon + '"><ele>' + ele + '</ele><time>' + timestamp + '</time></trkpt>';
194
-  localStorage.setItem("GPX", GPX + trkpt);
195
-  return true;
192
+    var GPX = localStorage.getItem("GPX");
193
+    var trkpt = '<trkpt lat="' + lat + '" lon="' + lon + '"><ele>' + ele + '</ele><time>' + timestamp + '</time></trkpt>';
194
+    localStorage.setItem("GPX", GPX + trkpt);
195
+    return true;
196 196
 }
197 197
 
198 198
 // Build GPX footer
... ...
@@ -210,73 +210,73 @@ function GPXfooterBuilder() {
210 210
 //------------------------------------------
211 211
 
212 212
 function getTokens(code) {
213
-  // call to strava api to get tokens in exchange of temp code
214
-  // need to use strava.jonget.fr to proxy request and hide secret
215
-  var url = "https://www.strava.com/oauth/token?client_id=" + client_id + "&client_secret=" + client_secret + "&code=" + code + "&grant_type=authorization_code";
216
-  var xhr = new XMLHttpRequest();
217
-  xhr.timeout = 10000; // time in milliseconds
218
-
219
-  xhr.open("POST", url, false);
220
-
221
-  xhr.send();
222
-
223
-  if (xhr.status === 200) {
224
-    console.log('------xhr request returned :', xhr.responseText);
225
-    response_json = JSON.parse(xhr.responseText);
226
-
227
-    var tokenjson = {
228
-      access_token: response_json.access_token,
229
-      refresh_token: response_json.refresh_token,
230
-      expiry: response_json.expires_at,
231
-      delay: response_json.expires_in
232
-    };
233
-    localStorage.setItem("strava_tokens", JSON.stringify(tokenjson));
234
-  }
213
+    // call to strava api to get tokens in exchange of temp code
214
+    // need to use strava.jonget.fr to proxy request and hide secret
215
+    var url = "https://www.strava.com/oauth/token?client_id=" + client_id + "&client_secret=" + client_secret + "&code=" + code + "&grant_type=authorization_code";
216
+    var xhr = new XMLHttpRequest();
217
+    xhr.timeout = 10000; // time in milliseconds
218
+
219
+    xhr.open("POST", url, false);
220
+
221
+    xhr.send();
222
+
223
+    if (xhr.status === 200) {
224
+        console.log('------xhr request returned :', xhr.responseText);
225
+        response_json = JSON.parse(xhr.responseText);
226
+
227
+        var tokenjson = {
228
+            access_token: response_json.access_token,
229
+            refresh_token: response_json.refresh_token,
230
+            expiry: response_json.expires_at,
231
+            delay: response_json.expires_in
232
+        };
233
+        localStorage.setItem("strava_tokens", JSON.stringify(tokenjson));
234
+    }
235 235
 }
236 236
 
237 237
 function refreshTokens(refresh_token) {
238
-  // call to strava api to get tokens in exchange of refresh code
239
-  // need to use strava.jonget.fr to proxy request and hide secret
240
-  var url = "https://www.strava.com/oauth/token?client_id=" + client_id + "&client_secret=" + client_secret + "&refresh_token=" + refresh_token + "&grant_type=refresh_token";
241
-  var xhr = new XMLHttpRequest();
242
-  xhr.timeout = 10000; // time in milliseconds
243
-
244
-  xhr.open("POST", url, false);
245
-
246
-  xhr.send();
247
-  //console.log('------Refresh token - xhr onloaded')
248
-  if (xhr.status === 200) {
249
-    console.log('------Refresh token - xhr request returned with ' + xhr.responseText);
250
-    response_json = JSON.parse(xhr.responseText);
251
-
252
-    var tokenjson = {
253
-      access_token: response_json.access_token,
254
-      refresh_token: response_json.refresh_token,
255
-      expiry: response_json.expires_at,
256
-      delay: response_json.expires_in
257
-    };
258
-    localStorage.setItem("strava_tokens", JSON.stringify(tokenjson));
238
+    // call to strava api to get tokens in exchange of refresh code
239
+    // need to use strava.jonget.fr to proxy request and hide secret
240
+    var url = "https://www.strava.com/oauth/token?client_id=" + client_id + "&client_secret=" + client_secret + "&refresh_token=" + refresh_token + "&grant_type=refresh_token";
241
+    var xhr = new XMLHttpRequest();
242
+    xhr.timeout = 10000; // time in milliseconds
243
+
244
+    xhr.open("POST", url, false);
245
+
246
+    xhr.send();
247
+    //console.log('------Refresh token - xhr onloaded')
248
+    if (xhr.status === 200) {
249
+        console.log('------Refresh token - xhr request returned with ' + xhr.responseText);
250
+        response_json = JSON.parse(xhr.responseText);
251
+
252
+        var tokenjson = {
253
+            access_token: response_json.access_token,
254
+            refresh_token: response_json.refresh_token,
255
+            expiry: response_json.expires_at,
256
+            delay: response_json.expires_in
257
+        };
258
+        localStorage.setItem("strava_tokens", JSON.stringify(tokenjson));
259 259
 
260
-  }
260
+    }
261 261
 
262 262
 }
263 263
 
264 264
 // Send GPX to Strava profile
265 265
 function SendToStrava() {
266
-  console.log('--- GPX upload to strava');
267
-  var gpxfile = localStorage.getItem("GPX");
266
+    console.log('--- GPX upload to strava');
267
+    var gpxfile = localStorage.getItem("GPX");
268 268
 
269
-  var tokens = localStorage.getItem("strava_tokens");
269
+    var tokens = localStorage.getItem("strava_tokens");
270 270
 
271
-  //checking token expiry
272
-  var date = (Date.now()) / 1000
271
+    //checking token expiry
272
+    var date = (Date.now()) / 1000
273 273
 
274
-  if (JSON.parse(tokens).expiry < date) {
275
-    console.log("Strava oAuth token expired, refreshing it")
276
-    refreshTokens(JSON.parse(tokens).refresh_token);
277
-  } else {
278
-    console.log("token (" + JSON.parse(tokens).access_token + ") valid, continuing")
279
-  }
274
+    if (JSON.parse(tokens).expiry < date) {
275
+        console.log("Strava oAuth token expired, refreshing it")
276
+        refreshTokens(JSON.parse(tokens).refresh_token);
277
+    } else {
278
+        console.log("token (" + JSON.parse(tokens).access_token + ") valid, continuing")
279
+    }
280 280
 
281 281
 
282 282
   var bearer = JSON.parse(tokens).access_token;
... ...
@@ -332,44 +332,44 @@ function SendToStrava() {
332 332
   for (var i in params.files) body += "--" + boundary + '\r\nContent-Disposition: form-data; name="' + i + '" ; filename=test.gpx\r\n\r\n' + params.files[i] + "\r\n";
333 333
   body += "--" + boundary + "--\r\n"
334 334
 
335
-  XHR.onreadystatechange = function () {
336
-    try {
337
-      4 == XHR.readyState && (n.status = XHR.status, n.txt = XHR.responseText, n.xml = XHR.responseXML, params.callback && params.callback(n))
338
-    } catch (e) {
339
-      console.error("Error2 loading, ", e)
335
+    XHR.onreadystatechange = function() {
336
+        try {
337
+            4 == XHR.readyState && (n.status = XHR.status, n.txt = XHR.responseText, n.xml = XHR.responseXML, params.callback && params.callback(n))
338
+        } catch (e) {
339
+            console.error("Error2 loading, ", e)
340
+        }
340 341
     }
341
-  }
342
-  XHR.send(body)
342
+    XHR.send(body)
343 343
 }
344 344
 
345 345
 
346 346
 // Send GPX to web server (need configuration on serverside)
347 347
 // TODO : secure it ?
348 348
 function PostToWeb() {
349
-  console.log('--- GPX upload to custom web server');
350
-  var GPX = localStorage.getItem("GPX");
351
-  var url = JSON.parse(localStorage.getItem('clay-settings')).gpx_web_url + "?name=pebblegpx&type=application/gpx+xml";
352
-  var xhr = new XMLHttpRequest();
353
-  xhr.timeout = 10000; // time in milliseconds
354
-
355
-  xhr.open("POST", url, false);
356
-
357
-  //console.log('------ CSV / xhr opened')
358
-  xhr.onload = function () {
359
-    //console.log('------xhr onloaded')
360
-    if (xhr.readyState === 4) {
361
-      //console.log('------xhr request returned with ' + xhr.status);
362
-      //console.log(this.responseText);
363
-      localStorage.setItem("custom_uploaded", true);
364
-      if (xhr.status == 200) {
365
-        //console.log('--> HTTP 200');
366
-        return true;
367
-      } else {
368
-        //console.log('--> HTTP ' + xhr.status);
369
-        return false;
370
-      }
371
-    }
372
-  };
349
+    console.log('--- GPX upload to custom web server');
350
+    var GPX = localStorage.getItem("GPX");
351
+    var url = JSON.parse(localStorage.getItem('clay-settings')).gpx_web_url + "?name=pebblegpx&type=application/gpx+xml";
352
+    var xhr = new XMLHttpRequest();
353
+    xhr.timeout = 10000; // time in milliseconds
354
+
355
+    xhr.open("POST", url, false);
356
+
357
+    //console.log('------ CSV / xhr opened')
358
+    xhr.onload = function() {
359
+        //console.log('------xhr onloaded')
360
+        if (xhr.readyState === 4) {
361
+            //console.log('------xhr request returned with ' + xhr.status);
362
+            //console.log(this.responseText);
363
+            localStorage.setItem("custom_uploaded", true);
364
+            if (xhr.status == 200) {
365
+                //console.log('--> HTTP 200');
366
+                return true;
367
+            } else {
368
+                //console.log('--> HTTP ' + xhr.status);
369
+                return false;
370
+            }
371
+        }
372
+    };
373 373
 
374 374
   //send GPX in body
375 375
   xhr.send(GPX);
... ...
@@ -379,125 +379,125 @@ function PostToWeb() {
379 379
 // Send location to web server for instant location (no live tracking)
380 380
 // TODO : secure it ?
381 381
 function instantLocationUpdate(pos) {
382
-  console.log('--- Instant location update');
383
-  // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
384
-
385
-  var url = JSON.parse(localStorage.getItem('clay-settings')).ping_location_url + "?lat=" + pos.coords.latitude + "&long=" + pos.coords.longitude + "&acc=" + pos.coords.accuracy + "&timestamp=" + pos.timestamp;
386
-  var xhr = new XMLHttpRequest();
387
-  xhr.timeout = 10000; // time in milliseconds
388
-
389
-  xhr.open("POST", url);
390
-
391
-  //console.log('------ instant / xhr opened')
392
-  xhr.onload = function () {
393
-    //console.log('------xhr onloaded')
394
-    if (xhr.readyState === 4) {
395
-      //console.log('------xhr request returned with ' + xhr.status);
396
-      //console.log(this.responseText);
397
-      if (xhr.status == 200) {
398
-        //console.log('--> HTTP 200');
399
-        return true;
400
-      } else {
401
-        //console.log('--> HTTP ' + xhr.status);
402
-        return false;
403
-      }
404
-    }
405
-  };
382
+    console.log('--- Instant location update');
383
+    // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
384
+
385
+    var url = JSON.parse(localStorage.getItem('clay-settings')).ping_location_url + "?lat=" + pos.coords.latitude + "&long=" + pos.coords.longitude + "&acc=" + pos.coords.accuracy + "&timestamp=" + pos.timestamp;
386
+    var xhr = new XMLHttpRequest();
387
+    xhr.timeout = 10000; // time in milliseconds
388
+
389
+    xhr.open("POST", url);
390
+
391
+    //console.log('------ instant / xhr opened')
392
+    xhr.onload = function() {
393
+        //console.log('------xhr onloaded')
394
+        if (xhr.readyState === 4) {
395
+            //console.log('------xhr request returned with ' + xhr.status);
396
+            //console.log(this.responseText);
397
+            if (xhr.status == 200) {
398
+                //console.log('--> HTTP 200');
399
+                return true;
400
+            } else {
401
+                //console.log('--> HTTP ' + xhr.status);
402
+                return false;
403
+            }
404
+        }
405
+    };
406 406
 
407
-  //send without body
408
-  xhr.send();
407
+    //send without body
408
+    xhr.send();
409 409
 
410 410
 }
411 411
 
412 412
 // called in case of successful geoloc gathering and sends the coordinate to watch
413 413
 //
414 414
 function locationSuccess(new_pos) {
415
-  console.log('--- locationSuccess');
416
-  // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
417
-
418
-  var prev_pos = getLocation(false);
419
-  var first_pos = getLocation(true);
420
-  if (prev_pos === null) {
421
-    console.log('--- start building gpx');
422
-    storeLocation(new_pos, true);
423
-    localStorage.setItem("strava_uploaded", false);
424
-    localStorage.setItem("custom_uploaded", false);
425
-
426
-    // Start the GPX file
427
-    GPXHeadersBuilder(new Date(new_pos.timestamp).toISOString(), "test", "18");
428
-
429
-  } else {
430
-    storeLocation(new_pos, false);
431
-
432
-    // Prepare display on watch
433
-    // now it's only raw data
434
-    // init strings
435
-    var latitudeString = "";
436
-    var longitudeString = "";
437
-    var accuracyString = "";
438
-    var altitudeString = "";
439
-    var speedString = "";
440
-    var distanceString = "";
441
-
442
-    // get speed from geoloc API isntead of calculate it
443
-    // speed is initially in m/s, get it at km/h
444
-    if (new_pos.coords.speed === null) {
445
-      var speed = 0;
446
-    } else {
447
-      var speed = new_pos.coords.speed * 3.6;
448
-      localStorage.setItem("speedsum", parseInt(localStorage.getItem("speedsum")) + speed);
449
-    }
415
+    console.log('--- locationSuccess');
416
+    // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
417
+
418
+    var prev_pos = getLocation(false);
419
+    var first_pos = getLocation(true);
420
+    if (prev_pos === null) {
421
+        console.log('--- start building gpx');
422
+        storeLocation(new_pos, true);
423
+        localStorage.setItem("strava_uploaded", false);
424
+        localStorage.setItem("custom_uploaded", false);
425
+
426
+        // Start the GPX file
427
+        GPXHeadersBuilder(new Date(new_pos.timestamp).toISOString(), "test", "18");
450 428
 
451
-    // distance since beginning in m
452
-    var dist = distance_on_geoid(prev_pos.coords.latitude, prev_pos.coords.longitude, new_pos.coords.latitude, new_pos.coords.longitude);
453
-    var totaldist = parseInt(localStorage.getItem("dist"));
454
-    if (!isNaN(dist)) {
455
-      totaldist = totaldist + parseInt(dist);
456
-      localStorage.setItem("dist", totaldist);
457
-    }
458
-    distanceString = splitFloatNumber(totaldist / 1000)[0].toString() + "." + splitFloatNumber(totaldist / 1000)[1].toString().substring(0, 3);
459
-    //console.log("total dist is now " + totaldist);
460
-
461
-    // avg speed (also when not moving) since beginning
462
-    var avgspeed = parseInt(localStorage.getItem("speedsum")) / parseInt(localStorage.getItem("totalcoordinates"));
463
-    var avgSpeedString = splitFloatNumber(avgspeed)[0].toString() + "." + splitFloatNumber(avgspeed)[1].toString().substring(0, 1);
464
-    console.log("speedsum=" + parseInt(localStorage.getItem("speedsum")) + " / totalcoordinates=" + parseInt(localStorage.getItem("totalcoordinates")));
465
-    console.log("--avgspeed=" + avgspeed + " / avgSpeedString=" + avgSpeedString)
466
-    if (avgSpeedString == "0.N") {
467
-      avgSpeedString = "0.0";
468
-    }
469
-    //console.log("avg speed is : " + avgSpeedString);
470
-
471
-    // Duration
472
-
473
-    var duration = new_pos.timestamp - first_pos.timestamp;
474
-    const date = new Date(duration);
475
-    durationString = padStart(date.getUTCHours().toString(), 2, "0") + ":" + padStart(date.getMinutes().toString(), 2, "0") + ":" + padStart(date.getSeconds().toString(), 2, "0");
476
-    console.log("durationString is : " + durationString);
477
-
478
-    //formating for precision and max size
479
-    latitudeString = new_pos.coords.latitude.toString().substring(0, 12);
480
-    longitudeString = new_pos.coords.longitude.toString().substring(0, 12);
481
-    accuracyString = new_pos.coords.accuracy.toString().substring(0, 4);
482
-    //console.log("split num : " + new_pos.coords.altitude);
483
-    altitudeString = splitFloatNumber(new_pos.coords.altitude)[0].toString().substring(0, 5);
484
-    timestampISO = new Date(new_pos.timestamp).toISOString();
485
-
486
-    //console.log("split num : " + speed);
487
-    if (isNaN(speed)) {
488
-      speedString = "---";
489 429
     } else {
490
-      speedString = splitFloatNumber(speed)[0].toString().substring(0, 3) + "." + splitFloatNumber(speed)[1].toString().substring(0, 1);
491
-      if (speedString == "0.N") {
492
-        speedString = "0.0";
493
-      }
430
+        storeLocation(new_pos, false);
431
+
432
+        // Prepare display on watch
433
+        // now it's only raw data
434
+        // init strings
435
+        var latitudeString = "";
436
+        var longitudeString = "";
437
+        var accuracyString = "";
438
+        var altitudeString = "";
439
+        var speedString = "";
440
+        var distanceString = "";
441
+
442
+        // get speed from geoloc API isntead of calculate it
443
+        // speed is initially in m/s, get it at km/h
444
+        if (new_pos.coords.speed === null) {
445
+            var speed = 0;
446
+        } else {
447
+            var speed = new_pos.coords.speed * 3.6;
448
+            localStorage.setItem("speedsum", parseInt(localStorage.getItem("speedsum")) + speed);
449
+        }
494 450
 
495
-      //console.log("split num : " + getMaxSpeed(speed));
496
-      maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 3);
497
-    }
451
+        // distance since beginning in m
452
+        var dist = distance_on_geoid(prev_pos.coords.latitude, prev_pos.coords.longitude, new_pos.coords.latitude, new_pos.coords.longitude);
453
+        var totaldist = parseInt(localStorage.getItem("dist"));
454
+        if (!isNaN(dist)) {
455
+            totaldist = totaldist + parseInt(dist);
456
+            localStorage.setItem("dist", totaldist);
457
+        }
458
+        distanceString = splitFloatNumber(totaldist / 1000)[0].toString() + "." + splitFloatNumber(totaldist / 1000)[1].toString().substring(0, 3);
459
+        //console.log("total dist is now " + totaldist);
460
+
461
+        // avg speed (also when not moving) since beginning
462
+        var avgspeed = parseInt(localStorage.getItem("speedsum")) / parseInt(localStorage.getItem("totalcoordinates"));
463
+        var avgSpeedString = splitFloatNumber(avgspeed)[0].toString() + "." + splitFloatNumber(avgspeed)[1].toString().substring(0, 1);
464
+        console.log("speedsum=" + parseInt(localStorage.getItem("speedsum")) + " / totalcoordinates=" + parseInt(localStorage.getItem("totalcoordinates")));
465
+        console.log("--avgspeed=" + avgspeed + " / avgSpeedString=" + avgSpeedString)
466
+        if (avgSpeedString == "0.N") {
467
+            avgSpeedString = "0.0";
468
+        }
469
+        //console.log("avg speed is : " + avgSpeedString);
470
+
471
+        // Duration
472
+
473
+        var duration = new_pos.timestamp - first_pos.timestamp;
474
+        const date = new Date(duration);
475
+        durationString = padStart(date.getUTCHours().toString(), 2, "0") + ":" + padStart(date.getMinutes().toString(), 2, "0") + ":" + padStart(date.getSeconds().toString(), 2, "0");
476
+        console.log("durationString is : " + durationString);
477
+
478
+        //formating for precision and max size
479
+        latitudeString = new_pos.coords.latitude.toString().substring(0, 12);
480
+        longitudeString = new_pos.coords.longitude.toString().substring(0, 12);
481
+        accuracyString = new_pos.coords.accuracy.toString().substring(0, 4);
482
+        //console.log("split num : " + new_pos.coords.altitude);
483
+        altitudeString = splitFloatNumber(new_pos.coords.altitude)[0].toString().substring(0, 5);
484
+        timestampISO = new Date(new_pos.timestamp).toISOString();
485
+
486
+        //console.log("split num : " + speed);
487
+        if (isNaN(speed)) {
488
+            speedString = "---";
489
+        } else {
490
+            speedString = splitFloatNumber(speed)[0].toString().substring(0, 3) + "." + splitFloatNumber(speed)[1].toString().substring(0, 1);
491
+            if (speedString == "0.N") {
492
+                speedString = "0.0";
493
+            }
494
+
495
+            //console.log("split num : " + getMaxSpeed(speed));
496
+            maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 3);
497
+        }
498 498
 
499
-    //add a new datapoint to GPX file
500
-    GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
499
+        //add a new datapoint to GPX file
500
+        GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
501 501
 
502 502
 
503 503
 
... ...
@@ -514,63 +514,63 @@ function locationSuccess(new_pos) {
514 514
       'status': message
515 515
     };
516 516
 
517
-    // Send the message
518
-    Pebble.sendAppMessage(dict, function () {
519
-      console.log('Message sent successfully: ' + JSON.stringify(dict));
520
-    }, function (e) {
521
-      console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
522
-    });
523
-  }
517
+        // Send the message
518
+        Pebble.sendAppMessage(dict, function() {
519
+            console.log('Message sent successfully: ' + JSON.stringify(dict));
520
+        }, function(e) {
521
+            console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
522
+        });
523
+    }
524 524
 
525 525
 
526 526
 }
527 527
 
528 528
 function locationError(err) {
529 529
 
530
-  console.warn('location error (' + err.code + '): ' + err.message);
530
+    console.warn('location error (' + err.code + '): ' + err.message);
531 531
 
532 532
 }
533 533
 
534 534
 
535 535
 function start_get_coordinate() {
536
-  clearInterval(firstlocationInterval);
537
-  firstlocationInterval = false;
538
-  locationInterval = setInterval(function () {
539
-    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
540
-  }, 1000);
541
-
542
-  if (locate_me) {
543
-    instantLocationInterval = setInterval(function () {
544
-      navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, locationOptions);
545
-    }, 60000);
546
-  }
536
+    clearInterval(firstlocationInterval);
537
+    firstlocationInterval = false;
538
+    locationInterval = setInterval(function() {
539
+        navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
540
+    }, 1000);
541
+
542
+    if (locate_me) {
543
+        instantLocationInterval = setInterval(function() {
544
+            navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, locationOptions);
545
+        }, 60000);
546
+    }
547 547
 
548 548
 }
549 549
 
550 550
 function init() {
551 551
 
552
-  clearInterval(locationInterval);
553
-  locationInterval = false;
554
-  clearInterval(instantLocationInterval);
555
-  instantLocationInterval = false;
556
-  firstlocationInterval = setInterval(function () {
557
-    navigator.geolocation.getCurrentPosition(null, locationError, firstlocationOptions);
558
-  }, 1000);
552
+    clearInterval(locationInterval);
553
+    locationInterval = false;
554
+    clearInterval(instantLocationInterval);
555
+    instantLocationInterval = false;
556
+    firstlocationInterval = setInterval(function() {
557
+        navigator.geolocation.getCurrentPosition(null, locationError, firstlocationOptions);
558
+    }, 1000);
559 559
 
560
-  //console.log("Clay settings = " + localStorage.getItem('clay-settings'));
561
-  var se = JSON.parse(localStorage.getItem('clay-settings')).strava_enabled;
562
-  var su = ("true" === localStorage.getItem("strava_uploaded"));
563
-  var ce = JSON.parse(localStorage.getItem('clay-settings')).gpx_web_enabled;
564
-  var cu = ("true" === localStorage.getItem("custom_uploaded"));
560
+    //console.log("Clay settings = " + localStorage.getItem('clay-settings'));
561
+    var se = JSON.parse(localStorage.getItem('clay-settings')).strava_enabled;
562
+    var su = ("true" === localStorage.getItem("strava_uploaded"));
563
+    var ce = JSON.parse(localStorage.getItem('clay-settings')).gpx_web_enabled;
564
+    var cu = ("true" === localStorage.getItem("custom_uploaded"));
565 565
 
566
-  locate_me = JSON.parse(localStorage.getItem('clay-settings')).ping_location_enabled;
566
+    locate_me = JSON.parse(localStorage.getItem('clay-settings')).ping_location_enabled;
567 567
 
568 568
 
569
-  console.log("Locate_me = " + locate_me);
570
-  console.log("Strava = " + se + " (" + typeof se + ")/ uploaded = " + su + " (" + typeof su + ")");
571
-  console.log("Custom web = " + ce + " (" + typeof ce + ")/ uploaded = " + cu + " (" + typeof cu + ")");
569
+    console.log("Locate_me = " + locate_me);
570
+    console.log("Strava = " + se + " (" + typeof se + ")/ uploaded = " + su + " (" + typeof su + ")");
571
+    console.log("Custom web = " + ce + " (" + typeof ce + ")/ uploaded = " + cu + " (" + typeof cu + ")");
572 572
 
573
-  if ((se && !su) || (ce && !cu)) {
573
+    if ((se && !su) || (ce && !cu)) {
574 574
 
575 575
     var GPX = localStorage.getItem("GPX");
576 576
     console.log("last 6 char of GPX are " + GPX.substring(GPX.length - 6, GPX.length))
... ...
@@ -583,37 +583,37 @@ function init() {
583 583
         console.log("GPX FOOTER is now : " + GPX.substring(GPX.length - 6, GPX.length))
584 584
     }
585 585
 
586
-    if (se) {
587
-      console.log("GPX upload needed to Strava")
588
-      SendToStrava();
589
-    }
586
+        if (se) {
587
+            console.log("GPX upload needed to Strava")
588
+            SendToStrava();
589
+        }
590 590
 
591
-    if (ce) {
592
-      console.log("GPX upload needed to custom server")
593
-      PostToWeb();
591
+        if (ce) {
592
+            console.log("GPX upload needed to custom server")
593
+            PostToWeb();
594
+        }
595
+    } else {
596
+        console.log("clearing var")
597
+        localStorage.setItem("maxSpeed", 0);
598
+        localStorage.setItem("firstlatitude", "");
599
+        localStorage.setItem("firstlongitude", "");
600
+        localStorage.setItem("firsttimestamp", "");
601
+        localStorage.setItem("lastlatitude", "");
602
+        localStorage.setItem("lastlongitude", "");
603
+        localStorage.setItem("lasttimestamp", "");
604
+        localStorage.setItem("dist", 0)
605
+        localStorage.setItem("speedsum", 0)
594 606
     }
595
-  } else {
596
-    console.log("clearing var")
597
-    localStorage.setItem("maxSpeed", 0);
598
-    localStorage.setItem("firstlatitude", "");
599
-    localStorage.setItem("firstlongitude", "");
600
-    localStorage.setItem("firsttimestamp", "");
601
-    localStorage.setItem("lastlatitude", "");
602
-    localStorage.setItem("lastlongitude", "");
603
-    localStorage.setItem("lasttimestamp", "");
604
-    localStorage.setItem("dist", 0)
605
-    localStorage.setItem("speedsum", 0)
606
-  }
607 607
 
608 608
 }
609 609
 
610 610
 // Get JS readiness events
611
-Pebble.addEventListener('ready', function (e) {
612
-  console.log('PebbleKit JS is ready');
613
-  // Update Watch on this
614
-  Pebble.sendAppMessage({ 'JSReady': 1 });
611
+Pebble.addEventListener('ready', function(e) {
612
+    console.log('PebbleKit JS is ready');
613
+    // Update Watch on this
614
+    Pebble.sendAppMessage({ 'JSReady': 1 });
615 615
 
616
-  init();
616
+    init();
617 617
 });
618 618
 
619 619
 // Get AppMessage events