Browse code

adding var init under condition

louis.jonget authored on14/10/2022 15:46:53
Showing1 changed files
... ...
@@ -5,49 +5,46 @@ var clay = new Clay(clayConfig);
5 5
 var messageKeys = require('message_keys');
6 6
 
7 7
 var message;
8
-var gpx_to_strava = false;
9
-var gpx_to_web = true;
10 8
 
11 9
 var locationInterval;
12 10
 
13 11
 var firstlocationOptions = {
14
-    'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
15
-    'timeout': 60000, //60s timeout to get a good signal
16
-    'maximumAge': 5 // no cache
12
+  'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
13
+  'timeout': 60000, //60s timeout to get a good signal
14
+  'maximumAge': 5 // no cache
17 15
 };
18 16
 var locationOptions = {
19
-    'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
20
-    'timeout': 5000, //5s timeout to get a good signal
21
-    'maximumAge': 5 // no cache
17
+  'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
18
+  'timeout': 5000, //5s timeout to get a good signal
19
+  'maximumAge': 5 // no cache
22 20
 };
23
-var geoloc_id;
24 21
 
25 22
 // Store location in Pebble app local storage
26 23
 //
27 24
 function storeLocation(position) {
28
-    var latitude = position.coords.latitude;
29
-    var longitude = position.coords.longitude;
30
-    var timestamp = position.timestamp;
31
-    localStorage.setItem("latitude", latitude);
32
-    localStorage.setItem("longitude", longitude);
33
-    localStorage.setItem("timestamp", timestamp);
34
-    // console.log("Stored location " + position.coords.latitude + ',' + position.coords.longitude);
25
+  var latitude = position.coords.latitude;
26
+  var longitude = position.coords.longitude;
27
+  var timestamp = position.timestamp;
28
+  localStorage.setItem("latitude", latitude);
29
+  localStorage.setItem("longitude", longitude);
30
+  localStorage.setItem("timestamp", timestamp);
31
+  // console.log("Stored location " + position.coords.latitude + ',' + position.coords.longitude);
35 32
 }
36 33
 
37 34
 // Get location from Pebble app local storage
38 35
 //
39 36
 function getLocation() {
40
-    if (localStorage.getItem("latitude") || localStorage.getItem("longitude") || localStorage.getItem("timestamp")) {
41
-        var la = localStorage.getItem("latitude");
42
-        var lo = localStorage.getItem("longitude");
43
-        var ti = localStorage.getItem("timestamp");
44
-        var co = { "latitude": la, "longitude": lo };
45
-        var pos = { "coords": co, "timestamp": ti };
46
-        // console.log("Stored location " + pos.co.la + ',' + pos.co.lo);
47
-        return pos;
48
-    } else {
49
-        return null;
50
-    }
37
+  if (localStorage.getItem("latitude") || localStorage.getItem("longitude") || localStorage.getItem("timestamp")) {
38
+    var la = localStorage.getItem("latitude");
39
+    var lo = localStorage.getItem("longitude");
40
+    var ti = localStorage.getItem("timestamp");
41
+    var co = { "latitude": la, "longitude": lo };
42
+    var pos = { "coords": co, "timestamp": ti };
43
+    // console.log("Stored location " + pos.co.la + ',' + pos.co.lo);
44
+    return pos;
45
+  } else {
46
+    return null;
47
+  }
51 48
 }
52 49
 
53 50
 
... ...
@@ -55,390 +52,375 @@ function getLocation() {
55 52
 // IMPORTANT : this is a calculation from 2D projection, altitude is not involved
56 53
 //
57 54
 function distance_on_geoid(lat1, lon1, lat2, lon2) {
58
-    // Convert degrees to radians
59
-    lat1 = lat1 * Math.PI / 180.0;
60
-    lon1 = lon1 * Math.PI / 180.0;
61
-    lat2 = lat2 * Math.PI / 180.0;
62
-    lon2 = lon2 * Math.PI / 180.0;
63
-    // radius of earth in metres
64
-    r = 6378100;
65
-    // P
66
-    rho1 = r * Math.cos(lat1);
67
-    z1 = r * Math.sin(lat1);
68
-    x1 = rho1 * Math.cos(lon1);
69
-    y1 = rho1 * Math.sin(lon1);
70
-    // Q
71
-    rho2 = r * Math.cos(lat2);
72
-    z2 = r * Math.sin(lat2);
73
-    x2 = rho2 * Math.cos(lon2);
74
-    y2 = rho2 * Math.sin(lon2);
75
-    // Dot product
76
-    dot = (x1 * x2 + y1 * y2 + z1 * z2);
77
-    cos_theta = dot / (r * r);
78
-    theta = Math.acos(cos_theta);
79
-    // Distance in Metres
80
-    return r * theta;
55
+  // Convert degrees to radians
56
+  lat1 = lat1 * Math.PI / 180.0;
57
+  lon1 = lon1 * Math.PI / 180.0;
58
+  lat2 = lat2 * Math.PI / 180.0;
59
+  lon2 = lon2 * Math.PI / 180.0;
60
+  // radius of earth in metres
61
+  r = 6378100;
62
+  // P
63
+  rho1 = r * Math.cos(lat1);
64
+  z1 = r * Math.sin(lat1);
65
+  x1 = rho1 * Math.cos(lon1);
66
+  y1 = rho1 * Math.sin(lon1);
67
+  // Q
68
+  rho2 = r * Math.cos(lat2);
69
+  z2 = r * Math.sin(lat2);
70
+  x2 = rho2 * Math.cos(lon2);
71
+  y2 = rho2 * Math.sin(lon2);
72
+  // Dot product
73
+  dot = (x1 * x2 + y1 * y2 + z1 * z2);
74
+  cos_theta = dot / (r * r);
75
+  theta = Math.acos(cos_theta);
76
+  // Distance in Metres
77
+  return r * theta;
81 78
 }
82 79
 
83
-// Calculate speed from 2 geoloc point arrays (with lat,long,timestamp)
84
-//
85
-function speed_from_distance_and_time(p1, p2) {
86
-    dist = distance_on_geoid(p1.coords.latitude, p1.coords.longitude, p2.coords.latitude, p2.coords.longitude);
87
-    // timestamp is in milliseconds
88
-    time_s = (p2.timestamp - p1.timestamp) / 1000.0;
89
-    speed_mps = dist / time_s;
90
-    speed_kph = (speed_mps * 3600.0) / 1000.0;
91
-    return speed_kph;
92
-}
93 80
 
94 81
 // Get max speed of the run
95 82
 //
96 83
 function getMaxSpeed(lastSpeed) {
97
-    oldmax = localStorage.getItem("maxSpeed") || -1;
98
-    if (oldmax < lastSpeed) {
99
-        maxSpeed = lastSpeed
100
-    } else if (oldmax > lastSpeed) {
101
-        maxSpeed = oldmax
102
-    } else {
103
-        maxSpeed = oldmax
104
-    }
105
-    localStorage.setItem("maxSpeed", maxSpeed);
106
-    return maxSpeed
84
+  oldmax = localStorage.getItem("maxSpeed") || -1;
85
+  if (oldmax < lastSpeed) {
86
+    maxSpeed = lastSpeed
87
+  } else if (oldmax > lastSpeed) {
88
+    maxSpeed = oldmax
89
+  } else {
90
+    maxSpeed = oldmax
91
+  }
92
+  localStorage.setItem("maxSpeed", maxSpeed);
93
+  return maxSpeed
107 94
 }
108 95
 
109 96
 // split float number into an array of int (null returned instead of 0 for decimal)
110 97
 //
111 98
 function splitFloatNumber(num) {
112
-    const intStr = num.toString().split('.')[0];
113
-    const decimalStr = num.toString().split('.')[1];
114
-    return [Number(intStr), Number(decimalStr)];
99
+  const intStr = num.toString().split('.')[0];
100
+  const decimalStr = num.toString().split('.')[1];
101
+  return [Number(intStr), Number(decimalStr)];
115 102
 
116 103
 }
117 104
 
118 105
 // Build GPX headers
119 106
 //
120 107
 function GPXHeadersBuilder(timestamp, name, type) {
121
-    var headers = '<?xml version="1.0" encoding="UTF-8"?><gpx creator="Pebble with barometer" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" xmlns="http://www.topografix.com/GPX/1/1"><metadata><time>' + timestamp + '</time></metadata><trk><name>' + name + '</name><type>' + type + '</type><trkseg>';
122
-    var ret = localStorage.setItem("GPX", headers);
123
-    return true;
108
+  var headers = '<?xml version="1.0" encoding="UTF-8"?><gpx creator="Pebble with barometer" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" xmlns="http://www.topografix.com/GPX/1/1"><metadata><time>' + timestamp + '</time></metadata><trk><name>' + name + '</name><type>' + type + '</type><trkseg>';
109
+  var ret = localStorage.setItem("GPX", headers);
110
+  return true;
124 111
 }
125 112
 
126 113
 // Build GPX footer
127 114
 //
128 115
 function GPXtrkptBuilder(lat, lon, ele, timestamp) {
129
-    var GPX = localStorage.getItem("GPX");
130
-    var trkpt = '<trkpt lat="' + lat + '" lon="' + lon + '"><ele>' + ele + '</ele><time>' + timestamp + '</time></trkpt>';
131
-    localStorage.setItem("GPX", GPX + trkpt);
132
-    return true;
116
+  var GPX = localStorage.getItem("GPX");
117
+  var trkpt = '<trkpt lat="' + lat + '" lon="' + lon + '"><ele>' + ele + '</ele><time>' + timestamp + '</time></trkpt>';
118
+  localStorage.setItem("GPX", GPX + trkpt);
119
+  return true;
133 120
 }
134 121
 
135 122
 // Build GPX footer
136 123
 //
137 124
 function GPXfooterBuilder() {
138
-    var GPX = localStorage.getItem("GPX");
139
-    var footer = '</trkseg></trk></gpx>';
140
-    var ret = localStorage.setItem("GPX", GPX + footer);
141
-    //console.log("GPX closed : " + GPX + footer);
142
-    return ret;
125
+  var GPX = localStorage.getItem("GPX");
126
+  var footer = '</trkseg></trk></gpx>';
127
+  var ret = localStorage.setItem("GPX", GPX + footer);
128
+  //console.log("GPX closed : " + GPX + footer);
129
+  return ret;
143 130
 }
144 131
 
145 132
 // Send GPX to Strava profile
146 133
 // TODO : get authentication creds from settings
147 134
 function SendToStrava() {
148
-    console.log('--- GPX upload to strava');
149
-    var GPX = localStorage.getItem("GPX");
150
-
151
-
152
-    /* -------------------- */
153
-    var array = [GPX]; // an array consisting of a single string
154
-    var blob = new Blob(array, { type: "application/gpx+xml" }); // the blob
155
-
156
-    // creating multipart/form-data to be sent
157
-    var data = new FormData();
158
-    data.append("file", blob, "blob.gpx");
159
-    data.append("name", "test");
160
-    data.append("description", "testdesc");
161
-    data.append("data_type", "gpx");
162
-
163
-    var url = "https://www.strava.com/api/v3/uploads";
164
-    var xhr = new XMLHttpRequest();
165
-    xhr.withCredentials = true;
166
-    xhr.timeout = 10000; // time in milliseconds
167
-
168
-    xhr.open("POST", url, false);
169
-    xhr.setRequestHeader("Authorization", "Bearer d8927033b3996efe1e5a4e62425bc2aff8f635b0");
170
-
171
-    console.log('------GPX / xhr opened with authorization')
172
-    console.log('------array for blob: ' + array)
173
-    xhr.onload = function() {
174
-        console.log('------xhr onload')
175
-        if (xhr.readyState === 4) {
176
-            console.log('------xhr request returned with ' + xhr.status);
177
-            console.log(this.responseText);
178
-            if (xhr.status == 200) {
179
-                //console.log('--> HTTP 200');
180
-                return true;
181
-            } else {
182
-                //console.log('--> HTTP ' + xhr.status);
183
-                return false;
184
-            }
185
-        }
186
-    };
135
+  console.log('--- GPX upload to strava');
136
+  var GPX = localStorage.getItem("GPX");
137
+
138
+
139
+  /* -------------------- */
140
+  var array = [GPX]; // an array consisting of a single string
141
+  var blob = new Blob(array, { type: "application/gpx+xml" }); // the blob
142
+
143
+  // creating multipart/form-data to be sent
144
+  var data = new FormData();
145
+  data.append("file", blob, "blob.gpx");
146
+  data.append("name", "test");
147
+  data.append("description", "testdesc");
148
+  data.append("data_type", "gpx");
149
+
150
+  var url = "https://www.strava.com/api/v3/uploads";
151
+  var xhr = new XMLHttpRequest();
152
+  xhr.withCredentials = true;
153
+  xhr.timeout = 10000; // time in milliseconds
154
+
155
+  xhr.open("POST", url, false);
156
+  xhr.setRequestHeader("Authorization", "Bearer d8927033b3996efe1e5a4e62425bc2aff8f635b0");
157
+
158
+  console.log('------GPX / xhr opened with authorization')
159
+  console.log('------array for blob: ' + array)
160
+  xhr.onload = function () {
161
+    console.log('------xhr onload')
162
+    if (xhr.readyState === 4) {
163
+      console.log('------xhr request returned with ' + xhr.status);
164
+      console.log(this.responseText);
165
+      if (xhr.status == 200) {
166
+        localStorage.setItem("strava_uploaded", true);
167
+        //console.log('--> HTTP 200');
168
+        return true;
169
+      } else {
170
+        //console.log('--> HTTP ' + xhr.status);
171
+        return false;
172
+      }
173
+    }
174
+  };
187 175
 
188
-    // send with data in body
189
-    xhr.send(data);
190
-    /* -------------------- */
176
+  // send with data in body
177
+  xhr.send(data);
178
+  /* -------------------- */
191 179
 
192 180
 }
193 181
 
194 182
 
195
-// Build CSV
196
-function CSV(pos) {
197
-    var CSV = localStorage.getItem("CSV");
198
-    var datapoint = pos.timestamp + "," + pos.coords.latitude + "," + pos.coords.longitude + "," + pos.coords.altitude + "," + pos.coords.accuracy + "," + pos.coords.altitudeAccuracy + "," + pos.coords.heading + "," + pos.coords.speed + "\n";
199
-
200
-    localStorage.setItem("CSV", CSV + datapoint);
201
-
202
-}
203
-// Send CSV to web server (need configuration on serverside)
183
+// Send GPX to web server (need configuration on serverside)
204 184
 // TODO : secure it ?
205 185
 function PostToWeb() {
206
-    console.log('--- GPX upload to custom web server');
207
-    var GPX = localStorage.getItem("GPX");
208
-
209
-    var url = "https://jonget.fr/strava/upload.php?name=pebblegpx&type=application/gpx+xml";
210
-    var xhr = new XMLHttpRequest();
211
-    xhr.timeout = 10000; // time in milliseconds
212
-
213
-    xhr.open("POST", url, false);
214
-
215
-    //console.log('------ CSV / xhr opened')
216
-    xhr.onload = function() {
217
-        //console.log('------xhr onload')
218
-        if (xhr.readyState === 4) {
219
-            //console.log('------xhr request returned with ' + xhr.status);
220
-            //console.log(this.responseText);
221
-            if (xhr.status == 200) {
222
-                //console.log('--> HTTP 200');
223
-                return true;
224
-            } else {
225
-                //console.log('--> HTTP ' + xhr.status);
226
-                return false;
227
-            }
228
-        }
229
-    };
186
+  console.log('--- GPX upload to custom web server');
187
+  var GPX = localStorage.getItem("GPX");
188
+
189
+  var url = "https://jonget.fr/strava/upload.php?name=pebblegpx&type=application/gpx+xml";
190
+  var xhr = new XMLHttpRequest();
191
+  xhr.timeout = 10000; // time in milliseconds
192
+
193
+  xhr.open("POST", url, false);
194
+
195
+  //console.log('------ GPX / xhr opened')
196
+  xhr.onload = function () {
197
+    //console.log('------xhr onload')
198
+    if (xhr.readyState === 4) {
199
+      //console.log('------xhr request returned with ' + xhr.status);
200
+      //console.log(this.responseText);
201
+      if (xhr.status == 200) {
202
+        localStorage.setItem("custom_uploaded", true);
203
+        //console.log('--> HTTP 200');
204
+        return true;
205
+      } else {
206
+        //console.log('--> HTTP ' + xhr.status);
207
+        return false;
208
+      }
209
+    }
210
+  };
230 211
 
231
-    //send CSV in body
232
-    xhr.send(GPX);
212
+  //send GPX in body
213
+  xhr.send(GPX);
233 214
 
234 215
 }
235 216
 
236 217
 // Send location to web server for instant location (no tracking)
237 218
 // TODO : secure it ?
238 219
 function instantLocationUpdate(pos) {
239
-    console.log('--- Instant location update');
240
-    // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
241
-
242
-    var url = "https://jonget.fr/find_me/update.php?lat=" + pos.coords.latitude + "&long=" + pos.coords.longitude + "&acc=" + pos.coords.accuracy + "&timestamp=" + pos.timestamp;
243
-    var xhr = new XMLHttpRequest();
244
-    xhr.timeout = 10000; // time in milliseconds
245
-
246
-    xhr.open("POST", url);
247
-
248
-    //console.log('------ instant / xhr opened')
249
-    xhr.onload = function() {
250
-        //console.log('------xhr onload')
251
-        if (xhr.readyState === 4) {
252
-            //console.log('------xhr request returned with ' + xhr.status);
253
-            //console.log(this.responseText);
254
-            if (xhr.status == 200) {
255
-                //console.log('--> HTTP 200');
256
-                return true;
257
-            } else {
258
-                //console.log('--> HTTP ' + xhr.status);
259
-                return false;
260
-            }
261
-        }
262
-    };
220
+  console.log('--- Instant location update');
221
+  // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
222
+
223
+  var url = "https://jonget.fr/find_me/update.php?lat=" + pos.coords.latitude + "&long=" + pos.coords.longitude + "&acc=" + pos.coords.accuracy + "&timestamp=" + pos.timestamp;
224
+  var xhr = new XMLHttpRequest();
225
+  xhr.timeout = 10000; // time in milliseconds
226
+
227
+  xhr.open("POST", url, false);
228
+
229
+  //console.log('------ instant / xhr opened')
230
+  xhr.onload = function () {
231
+    //console.log('------xhr onload')
232
+    if (xhr.readyState === 4) {
233
+      //console.log('------xhr request returned with ' + xhr.status);
234
+      //console.log(this.responseText);
235
+      if (xhr.status == 200) {
236
+        //console.log('--> HTTP 200');
237
+        return true;
238
+      } else {
239
+        //console.log('--> HTTP ' + xhr.status);
240
+        return false;
241
+      }
242
+    }
243
+  };
263 244
 
264
-    //send without body
265
-    xhr.send();
245
+  //send without body
246
+  xhr.send();
266 247
 
267 248
 }
268 249
 
269 250
 
270
-// Adding leading characters to string for nice displays
271
-//
272
-function padStart(string, max_length, padding) {
273
-    if (string.length > max_length) {
274
-        return string;
275
-    } else {
276
-        var new_str = string;
277
-        for (index = string.length; index < max_length; index++) {
278
-            new_str = "0" + new_str;
279
-        }
280
-        return new_str;
281
-    }
282
-}
283
-
284 251
 // called in case of successful geoloc gathering and sends the coordinate to watch
285 252
 //
286 253
 function locationSuccess(new_pos) {
287
-    console.log('--- locationSuccess');
288
-    // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
254
+  console.log('--- locationSuccess');
255
+  // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
289 256
 
290
-    var prev_pos = getLocation();
291
-    storeLocation(new_pos);
292
-    if (prev_pos === null) {
293
-      console.log('--- start building gpx');
257
+  var prev_pos = getLocation();
258
+  storeLocation(new_pos);
259
+  if (prev_pos === null) {
260
+    console.log('--- start building gpx');
294 261
 
295
-      if (gpx_to_strava || gpx_to_web) {
296
-        // Start the GPX file
297
-        GPXHeadersBuilder(new Date(new_pos.timestamp).toISOString(), "test", "18");
298
-      }
262
+    if (localStorage.getItem("strava_enabled") || localStorage.getItem("custom_enabled")) {
263
+      // Start the GPX file
264
+      GPXHeadersBuilder(new Date(new_pos.timestamp).toISOString(), "test", "18");
265
+    }
266
+  } else {
267
+    //clear watch of new position to avoid overlap
268
+    //navigator.geolocation.clearWatch(geoloc_id);
269
+    //console.log('--- watch geoloc cleared');
270
+    //var speed = speed_from_distance_and_time(prev_pos, new_pos);
271
+
272
+    //get speed from geoloc API isntead of calculate it
273
+    // speed is initially in m/s, get it at km/h
274
+    if (new_pos.coords.speed === null) {
275
+      var speed = 0;
299 276
     } else {
300
-      //clear watch of new position to avoid overlap
301
-      //navigator.geolocation.clearWatch(geoloc_id);
302
-      //console.log('--- watch geoloc cleared');
303
-      //var speed = speed_from_distance_and_time(prev_pos, new_pos);
304
-
305
-      //get speed from geoloc API isntead of calculate it
306
-      // speed is initially in m/s, get it at km/h
307
-      if (new_pos.coords.speed === null) {
308
-        var speed = 0;
309
-      } else {
310
-        var speed = new_pos.coords.speed * 3.6;
311
-      }
312
-
313
-      // Prepare display on watch
314
-      // now it's only raw data
315
-      // init strings
316
-      var latitudeString = "";
317
-      var longitudeString = "";
318
-      var accuracyString = "";
319
-      var altitudeString = "";
320
-      var speedString = "";
321
-
322
-      //formating for precision and max size
323
-      latitudeString = new_pos.coords.latitude.toString().substring(0, 12);
324
-      longitudeString = new_pos.coords.longitude.toString().substring(0, 12);
325
-      accuracyString = new_pos.coords.accuracy.toString().substring(0, 4);
326
-      //console.log("split num : " + new_pos.coords.altitude);
327
-      altitudeString = splitFloatNumber(new_pos.coords.altitude)[0].toString().substring(0, 5);
328
-      timestampISO = new Date(new_pos.timestamp).toISOString();
329
-      //console.log("split num : " + speed);
330
-      if (isNaN(speed)) {
331
-        speedString = "---";
332
-      } else {
333
-        speedString = splitFloatNumber(speed)[0].toString().substring(0, 3) + "." + splitFloatNumber(speed)[1].toString().substring(0, 1);
334
-        if (speedString == "0.N") {
335
-          speedString = "0.0";
336
-        }
277
+      var speed = new_pos.coords.speed * 3.6;
278
+    }
337 279
 
338
-        //console.log("split num : " + getMaxSpeed(speed));
339
-        maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 3);
280
+    // Prepare display on watch
281
+    // now it's only raw data
282
+    // init strings
283
+    var latitudeString = "";
284
+    var longitudeString = "";
285
+    var accuracyString = "";
286
+    var altitudeString = "";
287
+    var speedString = "";
288
+
289
+    //formating for precision and max size
290
+    latitudeString = new_pos.coords.latitude.toString().substring(0, 12);
291
+    longitudeString = new_pos.coords.longitude.toString().substring(0, 12);
292
+    accuracyString = new_pos.coords.accuracy.toString().substring(0, 4);
293
+    //console.log("split num : " + new_pos.coords.altitude);
294
+    altitudeString = splitFloatNumber(new_pos.coords.altitude)[0].toString().substring(0, 5);
295
+    timestampISO = new Date(new_pos.timestamp).toISOString();
296
+    //console.log("split num : " + speed);
297
+    if (isNaN(speed)) {
298
+      speedString = "---";
299
+    } else {
300
+      speedString = splitFloatNumber(speed)[0].toString().substring(0, 3) + "." + splitFloatNumber(speed)[1].toString().substring(0, 1);
301
+      if (speedString == "0.N") {
302
+        speedString = "0.0";
340 303
       }
341
-      if (gpx_to_strava || gpx_to_web) {
342
-        //add a new datapoint to GPX file
343
-        GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
344 304
 
345
-      }
305
+      //console.log("split num : " + getMaxSpeed(speed));
306
+      maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 3);
307
+    }
308
+    if (localStorage.getItem("strava_enabled") || localStorage.getItem("custom_enabled")) {
309
+      //add a new datapoint to GPX file
310
+      GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
346 311
 
347
-      // Build message
348
-      message = "OK";
349
-      var dict = {
350
-        'accuracy': accuracyString,
351
-        'altitude': altitudeString,
352
-        'speed': speedString,
353
-        'max_speed': maxSpeedString,
354
-        'status': message
355
-      };
356
-
357
-      // Send the message
358
-      Pebble.sendAppMessage(dict, function () {
359
-        console.log('Message sent successfully: ' + JSON.stringify(dict));
360
-      }, function (e) {
361
-        console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
362
-      });
363 312
     }
364 313
 
365
-}
314
+    // Build message
315
+    message = "OK";
316
+    var dict = {
317
+      'accuracy': accuracyString,
318
+      'altitude': altitudeString,
319
+      'speed': speedString,
320
+      'max_speed': maxSpeedString,
321
+      'status': message
322
+    };
366 323
 
367
-function locationError(err) {
324
+    // Send the message
325
+    Pebble.sendAppMessage(dict, function () {
326
+      console.log('Message sent successfully: ' + JSON.stringify(dict));
327
+    }, function (e) {
328
+      console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
329
+    });
330
+  }
368 331
 
369
-    console.warn('location error (' + err.code + '): ' + err.message);
370
-    /*
371
-    if (gpx_to_web) {
332
+}
372 333
 
373
-        var CSV = localStorage.getItem("CSV");
374
-        var datapoint = Date.now() + ",location error," + err.code + "," + err.message + ",,,,";
334
+function locationError(err) {
375 335
 
376
-        localStorage.setItem("CSV", CSV + datapoint);
377
-    }*/
336
+  console.warn('location error (' + err.code + '): ' + err.message);
378 337
 
379 338
 }
380 339
 
381 340
 
382 341
 function get_coordinate() {
383
-    console.log('--- Starting regular getCurrentPosition loop using setInterval at 5 sec');
342
+  console.log('--- Starting regular getCurrentPosition loop using setInterval at 5 sec');
384 343
 
385
-    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, firstlocationOptions);
344
+  navigator.geolocation.getCurrentPosition(locationSuccess, locationError, firstlocationOptions);
386 345
 
387
-    locationInterval = setInterval(function() {
388
-        navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
389
-    }, 1000);
346
+  locationInterval = setInterval(function () {
347
+    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
348
+  }, 1000);
390 349
 
391
-    instantLocationInterval = setInterval(function() {
392
-        navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, locationOptions);
393
-    }, 60000);
350
+  instantLocationInterval = setInterval(function () {
351
+    navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, locationOptions);
352
+  }, 60000);
394 353
 
395 354
 }
396 355
 
397 356
 function init() {
398
-    // local storage init,
399
-    // todo : clear only temporary values, not clay config (and do it on exit ?)
400
-    localStorage.clear();
401
-    localStorage.setItem("CSV", "");
402
-    // clear any other var to do
403
-    clearInterval(locationInterval);
357
+  // local storage init,
358
+
359
+  //to be replaced by Clay settings :
360
+  localStorage.setItem("custom_enabled", true);
361
+  localStorage.setItem("strava_enabled", false);
362
+
363
+  var ce = localStorage.getItem("custom_uploaded");
364
+  var cu = localStorage.getItem("custom_enabled");
365
+  var se = localStorage.getItem("strava_uploaded");
366
+  var su = localStorage.getItem("strava_enabled");
367
+
368
+  if ((se && !su) || (ce && !cu)) {
369
+    if (ce) {
370
+      PostToWeb();
371
+    }
372
+    if (se) {
373
+      SendToStrava();
374
+    }
375
+  } else {
376
+    localStorage.setItem("GPX", "");
377
+    localStorage.setItem("maxSpeed", "");
378
+    localStorage.setItem("latitude", "");
379
+    localStorage.setItem("longitude", "");
380
+    localStorage.setItem("timestamp", "");
381
+    localStorage.setItem("custom_uploaded", false);
382
+    localStorage.setItem("strava_uploaded", false);
383
+  }
384
+  // clear any other var to do
385
+  clearInterval(locationInterval);
404 386
 
405 387
 }
406 388
 
407 389
 // Get JS readiness events
408
-Pebble.addEventListener('ready', function(e) {
409
-    console.log('PebbleKit JS is ready');
410
-    // Update Watch on this
411
-    Pebble.sendAppMessage({ 'JSReady': 1 });
390
+Pebble.addEventListener('ready', function (e) {
391
+  console.log('PebbleKit JS is ready');
392
+  // Update Watch on this
393
+  Pebble.sendAppMessage({ 'JSReady': 1 });
412 394
 
413
-    init();
395
+  init();
414 396
 });
415 397
 
416 398
 // Get AppMessage events
417
-Pebble.addEventListener('appmessage', function(e) {
418
-    // Get the dictionary from the message
419
-    var dict = e.payload;
420
-    //console.log(dict[0].toString());
421
-    switch (dict[0]) {
422
-        case 'get':
423
-            get_coordinate();
424
-            break;
425
-        case 'exit':
426
-            if (gpx_to_strava || gpx_to_web) {
427
-                //End GPX file
428
-                GPXfooterBuilder();
429
-                if (gpx_to_strava) {
430
-                    //send to strava through API
431
-                    SendToStrava();
432
-                }
433
-                if (gpx_to_web) {
434
-                    // send CSV to web server through API
435
-                    PostToWeb();
436
-                }
437
-            }
438
-
439
-            break;
440
-        default:
441
-            console.log('Sorry. I don\'t understand your request :' + dict[0]);
442
-    }
399
+Pebble.addEventListener('appmessage', function (e) {
400
+  // Get the dictionary from the message
401
+  var dict = e.payload;
402
+  //console.log(dict[0].toString());
403
+  switch (dict[0]) {
404
+    case 'get':
405
+      get_coordinate();
406
+      break;
407
+    case 'exit':
408
+      if (localStorage.getItem("strava_enabled") || localStorage.getItem("custom_enabled")) {
409
+        //End GPX file
410
+        GPXfooterBuilder();
411
+        if (localStorage.getItem("strava_enabled")) {
412
+          //send to strava through API
413
+          SendToStrava();
414
+        }
415
+        if (localStorage.getItem("custom_enabled")) {
416
+          // send GPX to web server through API
417
+          PostToWeb();
418
+        }
419
+      }
420
+
421
+      break;
422
+    default:
423
+      console.log('Sorry. I don\'t understand your request :' + dict[0]);
424
+  }
443 425
 
444 426
 });
445 427
\ No newline at end of file