Browse code

switch post to web with gpx instead of CSV

Louis authored on12/10/2022 08:00:32
Showing1 changed files
... ...
@@ -6,48 +6,48 @@ var messageKeys = require('message_keys');
6 6
 
7 7
 var message;
8 8
 var gpx_to_strava = false;
9
-var csv_to_web = true;
9
+var gpx_to_web = true;
10 10
 
11 11
 var locationInterval;
12 12
 
13 13
 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
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
17 17
 };
18 18
 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
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
22 22
 };
23 23
 var geoloc_id;
24 24
 
25 25
 // Store location in Pebble app local storage
26 26
 //
27 27
 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);
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);
35 35
 }
36 36
 
37 37
 // Get location from Pebble app local storage
38 38
 //
39 39
 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
-  }
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
+    }
51 51
 }
52 52
 
53 53
 
... ...
@@ -55,214 +55,214 @@ function getLocation() {
55 55
 // IMPORTANT : this is a calculation from 2D projection, altitude is not involved
56 56
 //
57 57
 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;
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;
81 81
 }
82 82
 
83 83
 // Calculate speed from 2 geoloc point arrays (with lat,long,timestamp)
84 84
 //
85 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;
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 92
 }
93 93
 
94 94
 // Get max speed of the run
95 95
 //
96 96
 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
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
107 107
 }
108 108
 
109 109
 // split float number into an array of int (null returned instead of 0 for decimal)
110 110
 //
111 111
 function splitFloatNumber(num) {
112
-  const intStr = num.toString().split('.')[0];
113
-  const decimalStr = num.toString().split('.')[1];
114
-  return [Number(intStr), Number(decimalStr)];
112
+    const intStr = num.toString().split('.')[0];
113
+    const decimalStr = num.toString().split('.')[1];
114
+    return [Number(intStr), Number(decimalStr)];
115 115
 
116 116
 }
117 117
 
118 118
 // Build GPX headers
119 119
 //
120 120
 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;
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;
124 124
 }
125 125
 
126 126
 // Build GPX footer
127 127
 //
128 128
 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;
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;
133 133
 }
134 134
 
135 135
 // Build GPX footer
136 136
 //
137 137
 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;
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;
143 143
 }
144 144
 
145 145
 // Send GPX to Strava profile
146 146
 // TODO : get authentication creds from settings
147 147
 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
-  };
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
+    };
187 187
 
188
-  // send with data in body
189
-  xhr.send(data);
190
-  /* -------------------- */
188
+    // send with data in body
189
+    xhr.send(data);
190
+    /* -------------------- */
191 191
 
192 192
 }
193 193
 
194 194
 
195 195
 // Build CSV
196 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";
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 199
 
200
-  localStorage.setItem("CSV", CSV + datapoint);
200
+    localStorage.setItem("CSV", CSV + datapoint);
201 201
 
202 202
 }
203 203
 // Send CSV to web server (need configuration on serverside)
204 204
 // TODO : secure it ?
205 205
 function PostToWeb() {
206
-  console.log('--- CSV upload to web');
207
-  var CSV = localStorage.getItem("CSV");
208
-
209
-  var url = "https://jonget.fr/strava/upload.php?name=pebblecsv&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
-  };
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
+    };
230 230
 
231
-  //send CSV in body
232
-  xhr.send(CSV);
231
+    //send CSV in body
232
+    xhr.send(GPX);
233 233
 
234 234
 }
235 235
 
236 236
 // Send location to web server for instant location (no tracking)
237 237
 // TODO : secure it ?
238 238
 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
-  };
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
+    };
263 263
 
264
-  //send without body
265
-  xhr.send();
264
+    //send without body
265
+    xhr.send();
266 266
 
267 267
 }
268 268
 
... ...
@@ -270,179 +270,173 @@ function instantLocationUpdate(pos) {
270 270
 // Adding leading characters to string for nice displays
271 271
 //
272 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;
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;
279 281
     }
280
-    return new_str;
281
-  }
282 282
 }
283 283
 
284 284
 // called in case of successful geoloc gathering and sends the coordinate to watch
285 285
 //
286 286
 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);
289
-
290
-  var prev_pos = getLocation();
291
-  storeLocation(new_pos);
292
-  if (prev_pos === null) {
293
-    console.log('--- start building gpx');
294
-
295
-    if (gpx_to_strava) {
296
-      // Start the GPX file
297
-      GPXHeadersBuilder(new Date(new_pos.timestamp).toISOString(), "test", "18");
298
-    }
299
-    if (csv_to_web) {
300
-      // Start the csv file
301
-      CSV(new_pos);
302
-    }
303
-  } else {
304
-    //clear watch of new position to avoid overlap
305
-    //navigator.geolocation.clearWatch(geoloc_id);
306
-    //console.log('--- watch geoloc cleared');
307
-    //var speed = speed_from_distance_and_time(prev_pos, new_pos);
308
-
309
-    //get speed from geoloc API isntead of calculate it
310
-    // speed is initially in m/s, get it at km/h
311
-    if (new_pos.coords.speed === null) {
312
-      var speed = 0;
287
+    console.log('--- locationSuccess');
288
+    // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
289
+
290
+    var prev_pos = getLocation();
291
+    storeLocation(new_pos);
292
+    if (prev_pos === null) {
293
+        console.log('--- start building gpx');
294
+
295
+        if (gpx_to_strava || gpx_to_web) {
296
+            // Start the GPX file
297
+            GPXHeadersBuilder(new Date(new_pos.timestamp).toISOString(), "test", "18");
298
+        }
313 299
     } else {
314
-      var speed = new_pos.coords.speed * 3.6;
315
-    }
316
-
317
-    // Prepare display on watch
318
-    // now it's only raw data
319
-    // init strings
320
-    var latitudeString = "";
321
-    var longitudeString = "";
322
-    var accuracyString = "";
323
-    var altitudeString = "";
324
-    var speedString = "";
325
-
326
-    //formating for precision and max size
327
-    latitudeString = new_pos.coords.latitude.toString().substring(0, 12);
328
-    longitudeString = new_pos.coords.longitude.toString().substring(0, 12);
329
-    accuracyString = new_pos.coords.accuracy.toString().substring(0, 4);
330
-    //console.log("split num : " + new_pos.coords.altitude);
331
-    altitudeString = splitFloatNumber(new_pos.coords.altitude)[0].toString().substring(0, 5);
332
-    timestampISO = new Date(new_pos.timestamp).toISOString();
333
-    //console.log("split num : " + speed);
334
-    speedString = splitFloatNumber(speed)[0].toString().substring(0, 3); //+ "." + splitFloatNumber(speed)[1].toString().substring(0, 1);
335
-
336
-    //console.log("split num : " + getMaxSpeed(speed));
337
-    maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 4);
338
-
339
-    if (speedString == "NaN") {
340
-      speedString = "---";
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
+        speedString = splitFloatNumber(speed)[0].toString().substring(0, 3); //+ "." + splitFloatNumber(speed)[1].toString().substring(0, 1);
331
+
332
+        //console.log("split num : " + getMaxSpeed(speed));
333
+        maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 4);
334
+
335
+        if (speedString == "NaN") {
336
+            speedString = "---";
337
+        }
338
+
339
+        if (gpx_to_strava || gpx_to_web) {
340
+            //add a new datapoint to GPX file
341
+            GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
342
+
343
+        }
344
+
345
+        // Build message
346
+        message = "OK";
347
+        var dict = {
348
+            'accuracy': accuracyString,
349
+            'altitude': altitudeString,
350
+            'speed': speedString,
351
+            'max_speed': maxSpeedString,
352
+            'status': message
353
+        };
354
+
355
+        // Send the message
356
+        Pebble.sendAppMessage(dict, function() {
357
+            console.log('Message sent successfully: ' + JSON.stringify(dict));
358
+        }, function(e) {
359
+            console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
360
+        });
341 361
     }
342 362
 
343
-    if (gpx_to_strava) {
344
-      //add a new datapoint to GPX file
345
-      GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
346
-      //console.log('GPX: ' + localStorage.getItem("GPX"));
347
-    }
348
-    if (csv_to_web) {
349
-      // Start the csv file
350
-      CSV(new_pos);
351
-      //console.log('CSV: ' + localStorage.getItem("CSV"));
352
-    }
353
-
354
-
355
-    // Build message
356
-    message = "OK";
357
-    var dict = {
358
-      'accuracy': accuracyString,
359
-      'altitude': altitudeString,
360
-      'speed': speedString,
361
-      'max_speed': maxSpeedString,
362
-      'status': message
363
-    };
364
-
365
-    // Send the message
366
-    Pebble.sendAppMessage(dict, function () {
367
-      console.log('Message sent successfully: ' + JSON.stringify(dict));
368
-    }, function (e) {
369
-      console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
370
-    });
371
-  }
372
-
373 363
 }
374 364
 
375 365
 function locationError(err) {
376 366
 
377
-  console.warn('location error (' + err.code + '): ' + err.message);
378
-  if (csv_to_web) {
367
+    console.warn('location error (' + err.code + '): ' + err.message);
368
+    /*
369
+    if (gpx_to_web) {
379 370
 
380
-    var CSV = localStorage.getItem("CSV");
381
-    var datapoint = Date.now() + ",location error," + err.code + "," + err.message + ",,,,";
371
+        var CSV = localStorage.getItem("CSV");
372
+        var datapoint = Date.now() + ",location error," + err.code + "," + err.message + ",,,,";
382 373
 
383
-    localStorage.setItem("CSV", CSV + datapoint);
384
-  }
374
+        localStorage.setItem("CSV", CSV + datapoint);
375
+    }*/
385 376
 
386 377
 }
387 378
 
388 379
 
389 380
 function get_coordinate() {
390
-  console.log('--- Starting regular getCurrentPosition loop using setInterval at 5 sec');
381
+    console.log('--- Starting regular getCurrentPosition loop using setInterval at 5 sec');
391 382
 
392
-  navigator.geolocation.getCurrentPosition(locationSuccess, locationError, firstlocationOptions);
383
+    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, firstlocationOptions);
393 384
 
394
-  locationInterval = setInterval(function () {
395
-    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
396
-  }, 1000);
385
+    locationInterval = setInterval(function() {
386
+        navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
387
+    }, 1000);
397 388
 
398
-  instantLocationInterval = setInterval(function () {
399
-    navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, locationOptions);
400
-  }, 60000);
389
+    instantLocationInterval = setInterval(function() {
390
+        navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, locationOptions);
391
+    }, 60000);
401 392
 
402 393
 }
403 394
 
404 395
 function init() {
405
-  // local storage init,
406
-  // todo : clear only temporary values, not clay config (and do it on exit ?)
407
-  localStorage.clear();
408
-  localStorage.setItem("CSV", "");
409
-  // clear any other var to do
410
-  clearInterval(locationInterval);
396
+    // local storage init,
397
+    // todo : clear only temporary values, not clay config (and do it on exit ?)
398
+    localStorage.clear();
399
+    localStorage.setItem("CSV", "");
400
+    // clear any other var to do
401
+    clearInterval(locationInterval);
411 402
 
412 403
 }
413 404
 
414 405
 // Get JS readiness events
415
-Pebble.addEventListener('ready', function (e) {
416
-  console.log('PebbleKit JS is ready');
417
-  // Update Watch on this
418
-  Pebble.sendAppMessage({ 'JSReady': 1 });
406
+Pebble.addEventListener('ready', function(e) {
407
+    console.log('PebbleKit JS is ready');
408
+    // Update Watch on this
409
+    Pebble.sendAppMessage({ 'JSReady': 1 });
419 410
 
420
-  init();
411
+    init();
421 412
 });
422 413
 
423 414
 // Get AppMessage events
424
-Pebble.addEventListener('appmessage', function (e) {
425
-  // Get the dictionary from the message
426
-  var dict = e.payload;
427
-  //console.log(dict[0].toString());
428
-  switch (dict[0]) {
429
-    case 'get':
430
-      get_coordinate();
431
-      break;
432
-    case 'exit':
433
-      if (gpx_to_strava) {
434
-        //End GPX file
435
-        GPXfooterBuilder();
436
-        //send to strava through API
437
-        SendToStrava();
438
-      }
439
-      if (csv_to_web) {
440
-        // send CSV to web server through API
441
-        PostToWeb();
442
-      }
443
-      break;
444
-    default:
445
-      console.log('Sorry. I don\'t understand your request :' + dict[0]);
446
-  }
415
+Pebble.addEventListener('appmessage', function(e) {
416
+    // Get the dictionary from the message
417
+    var dict = e.payload;
418
+    //console.log(dict[0].toString());
419
+    switch (dict[0]) {
420
+        case 'get':
421
+            get_coordinate();
422
+            break;
423
+        case 'exit':
424
+            if (gpx_to_strava || gpx_to_web) {
425
+                //End GPX file
426
+                GPXfooterBuilder();
427
+                if (gpx_to_strava) {
428
+                    //send to strava through API
429
+                    SendToStrava();
430
+                }
431
+                if (gpx_to_web) {
432
+                    // send CSV to web server through API
433
+                    PostToWeb();
434
+                }
435
+            }
436
+
437
+            break;
438
+        default:
439
+            console.log('Sorry. I don\'t understand your request :' + dict[0]);
440
+    }
447 441
 
448
-});
442
+});
449 443
\ No newline at end of file