Browse code

clarifying variables in XHR for strava

louis.jonget authored on19/10/2022 18:02:20
Showing2 changed files
... ...
@@ -51,7 +51,7 @@ function upload(gpxfile) {
51 51
             method: "POST",
52 52
             data: { description: "desc", data_type: "gpx" },
53 53
             files: { file: gpxfile },
54
-            authorization: "Bearer " + c
54
+        authorization: "Bearer " + c,
55 55
             callback: function() {
56 56
                 var z = "";
57 57
                 if (r && console.log(e.status + " - " + e.txt), 201 == e.status) z = "Your activity has been created";
... ...
@@ -12,212 +12,239 @@ var gpx_to_web = true;
12 12
 var locationInterval;
13 13
 
14 14
 var firstlocationOptions = {
15
-    'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
16
-    'timeout': 60000, //60s timeout to get a good signal
17
-    'maximumAge': 5 // no cache
15
+  'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
16
+  'timeout': 60000, //60s timeout to get a good signal
17
+  'maximumAge': 5 // no cache
18 18
 };
19 19
 var locationOptions = {
20
-    'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
21
-    'timeout': 5000, //5s timeout to get a good signal
22
-    'maximumAge': 5 // no cache
20
+  'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
21
+  'timeout': 5000, //5s timeout to get a good signal
22
+  'maximumAge': 5 // no cache
23 23
 };
24 24
 var geoloc_id;
25 25
 
26 26
 // Store location in Pebble app local storage
27 27
 //
28 28
 function storeLocation(position) {
29
-    var latitude = position.coords.latitude;
30
-    var longitude = position.coords.longitude;
31
-    var timestamp = position.timestamp;
32
-    localStorage.setItem("latitude", latitude);
33
-    localStorage.setItem("longitude", longitude);
34
-    localStorage.setItem("timestamp", timestamp);
35
-    // console.log("Stored location " + position.coords.latitude + ',' + position.coords.longitude);
29
+  var latitude = position.coords.latitude;
30
+  var longitude = position.coords.longitude;
31
+  var timestamp = position.timestamp;
32
+  localStorage.setItem("latitude", latitude);
33
+  localStorage.setItem("longitude", longitude);
34
+  localStorage.setItem("timestamp", timestamp);
35
+  // console.log("Stored location " + position.coords.latitude + ',' + position.coords.longitude);
36 36
 }
37 37
 
38 38
 // Get location from Pebble app local storage
39 39
 //
40 40
 function getLocation() {
41
-    if (localStorage.getItem("latitude") || localStorage.getItem("longitude") || localStorage.getItem("timestamp")) {
42
-        var la = localStorage.getItem("latitude");
43
-        var lo = localStorage.getItem("longitude");
44
-        var ti = localStorage.getItem("timestamp");
45
-        var co = { "latitude": la, "longitude": lo };
46
-        var pos = { "coords": co, "timestamp": ti };
47
-        // console.log("Stored location " + pos.co.la + ',' + pos.co.lo);
48
-        return pos;
49
-    } else {
50
-        return null;
51
-    }
41
+  if (localStorage.getItem("latitude") || localStorage.getItem("longitude") || localStorage.getItem("timestamp")) {
42
+    var la = localStorage.getItem("latitude");
43
+    var lo = localStorage.getItem("longitude");
44
+    var ti = localStorage.getItem("timestamp");
45
+    var co = { "latitude": la, "longitude": lo };
46
+    var pos = { "coords": co, "timestamp": ti };
47
+    // console.log("Stored location " + pos.co.la + ',' + pos.co.lo);
48
+    return pos;
49
+  } else {
50
+    return null;
51
+  }
52 52
 }
53 53
 
54 54
 // Calculate the distance from 2 geoloc in degrees.
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
 
146 146
 // Send GPX to Strava profile
147 147
 // TODO : get authentication creds from settings
148 148
 function SendToStrava() {
149
-    console.log('--- GPX upload to strava');
150
-    var GPX = localStorage.getItem("GPX");
151
-    // need to automate oAUTH
152
-    var bearer = "8a68d5b79f2fb3e00ad3eaa5025253990fbd6a58"
153
-    params = {
154
-        url: s,
155
-        method: "POST",
156
-        data: { description: "desc", data_type: "gpx" },
157
-        files: { file: gpxfile },
158
-        authorization: "Bearer " + bearer,
159
-        callback: function() {
160
-            var message = "";
161
-            if (r && console.log(e.status + " - " + e.txt), 201 == e.status) {
162
-                message = "Your activity has been created";
163
-            } else if (400 == e.status) {
164
-                message = "An error has occurred. If you've already uploaded the current activity, please delete it in Strava.";
165
-            } else if (401 == e.status) {
166
-                message = "Error - Unauthorized. Please check your credentials in the settings.", o.setAccessToken("");
167
-            } else {
168
-                try {
169
-                    response_json = JSON.parse(e.txt), response_json.error ? (r && console.log("error:" + response_json.error), message = response_json.error, o.setAccessToken("")) : response_json.status && (r && console.log("status:" + response_json.status), z = response_json.status)
170
-                } catch (z) {
171
-                    console.log("Error log, " + z)
172
-                }
173
-            }
174
-            message && Pebble.showSimpleNotificationOnPebble("Ventoo SE - Strava", message)
149
+  console.log('--- GPX upload to strava');
150
+  var gpxfile = localStorage.getItem("GPX");
151
+  // need to automate oAUTH
152
+  var bearer = "8a68d5b79f2fb3e00ad3eaa5025253990fbd6a58"
153
+  params = {
154
+    url: "https://www.strava.com/api/v3/uploads",
155
+    method: "POST",
156
+    data: { description: "desc", data_type: "gpx" },
157
+    files: { file: gpxfile },
158
+    authorization: "Bearer " + bearer,
159
+    callback: function () {
160
+      var message = "";
161
+      // what is 'r'
162
+      // what is 'e'
163
+      // what is 'o'
164
+      // what is 'z'
165
+      if (r && console.log(e.status + " - " + e.txt), 201 == e.status) {
166
+        message = "Your activity has been created";
167
+      } else if (400 == e.status) {
168
+        message = "An error has occurred. If you've already uploaded the current activity, please delete it in Strava.";
169
+      } else if (401 == e.status) {
170
+        message = "Error - Unauthorized. Please check your credentials in the settings.", o.setAccessToken("");
171
+      } else {
172
+        try {
173
+          response_json = JSON.parse(e.txt)
174
+          response_json.error ? (r && console.log("error:" + response_json.error), message = response_json.error, o.setAccessToken("")) : response_json.status && (r && console.log("status:" + response_json.status), z = response_json.status)
175
+        } catch (e) {
176
+          console.log("Error log, " + e)
175 177
         }
178
+      }
179
+      message && Pebble.showSimpleNotificationOnPebble("Ventoo SE - Strava", message)
176 180
     }
177
-
178
-    // fetch or Blob or Formdata are not implemented in pebblekitJS
179
-    /*fetch('data:application/gpx+xml;base64,'.btoa(GPX))
180
-        .then(function(value) { return value.blob() })
181
-        .then(
182
-            function(value) {
183
-    var data = new FormData();
184
-    data.append("name", "test");
185
-    data.append("description", "description");
186
-    data.append("data_type", "gpx");
187
-    data.append("file", value, "blob.gpx");
188
-
189
-    var xhr = new XMLHttpRequest();
190
-    var url = "https://www.strava.com/api/v3/uploads";
191
-    xhr.withCredentials = true;
192
-    xhr.timeout = 10000; // time in milliseconds
193
-
194
-    xhr.open("POST", url, false);
195
-    xhr.setRequestHeader("Authorization", "Bearer 8a68d5b79f2fb3e00ad3eaa5025253990fbd6a58");
196
-
197
-    console.log('------GPX / xhr opened with authorization')
198
-    console.log('------array for blob: ' + [GPX])
199
-    xhr.onload = function() {
200
-        console.log('------xhr onload')
201
-        if (xhr.readyState === 4) {
202
-            console.log('------xhr request returned with ' + xhr.status);
203
-            console.log(this.responseText);
204
-            if (xhr.status == 200) {
205
-                //console.log('--> HTTP 200');
206
-                return true;
207
-            } else {
208
-                //console.log('--> HTTP ' + xhr.status);
209
-                return false;
210
-            }
211
-        }
212
-    };
213
-
214
-    xhr.send(data);
215
-    },
216
-            function(error) {
217
-                console.log('error')
218
-            }
219
-        )*/
220
-    /* -------------------- */
181
+  }
182
+  var XHR = new XMLHttpRequest;
183
+  console.log(params.url);
184
+  XHR.open(params.method, params.url, !0);
185
+  var body = "";
186
+  var boundary = Math.random().toString().substring(2);
187
+  XHR.setRequestHeader("content-type", "multipart/form-data; charset=utf-8; boundary=" + boundary)
188
+  XHR.setRequestHeader("Authorization", params.authorization);
189
+  for (var i in params.data) body += "--" + boundary + '\r\nContent-Disposition: form-data; name="' + i + '"\r\n\r\n' + params.data[i] + "\r\n";
190
+  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";
191
+  body += "--" + boundary + "--\r\n"
192
+
193
+  XHR.onreadystatechange = function () {
194
+    // what is 'n'
195
+    try {
196
+      4 == XHR.readyState && (n.status = XHR.status, n.txt = XHR.responseText, n.xml = XHR.responseXML, params.callback && params.callback())
197
+    } catch (e) {
198
+      console.error("Error2 loading, ", e)
199
+    }
200
+  }
201
+  XHR.send(body)
202
+
203
+
204
+
205
+  // fetch or Blob or Formdata are not implemented in pebblekitJS
206
+  /*fetch('data:application/gpx+xml;base64,'.btoa(GPX))
207
+      .then(function(value) { return value.blob() })
208
+      .then(
209
+          function(value) {
210
+  var data = new FormData();
211
+  data.append("name", "test");
212
+  data.append("description", "description");
213
+  data.append("data_type", "gpx");
214
+  data.append("file", value, "blob.gpx");
215
+
216
+  var xhr = new XMLHttpRequest();
217
+  var url = "https://www.strava.com/api/v3/uploads";
218
+  xhr.withCredentials = true;
219
+  xhr.timeout = 10000; // time in milliseconds
220
+
221
+  xhr.open("POST", url, false);
222
+  xhr.setRequestHeader("Authorization", "Bearer 8a68d5b79f2fb3e00ad3eaa5025253990fbd6a58");
223
+
224
+  console.log('------GPX / xhr opened with authorization')
225
+  console.log('------array for blob: ' + [GPX])
226
+  xhr.onload = function() {
227
+      console.log('------xhr onload')
228
+      if (xhr.readyState === 4) {
229
+          console.log('------xhr request returned with ' + xhr.status);
230
+          console.log(this.responseText);
231
+          if (xhr.status == 200) {
232
+              //console.log('--> HTTP 200');
233
+              return true;
234
+          } else {
235
+              //console.log('--> HTTP ' + xhr.status);
236
+              return false;
237
+          }
238
+      }
239
+  };
240
+
241
+  xhr.send(data);
242
+  },
243
+          function(error) {
244
+              console.log('error')
245
+          }
246
+      )*/
247
+  /* -------------------- */
221 248
 
222 249
 
223 250
 }
... ...
@@ -225,75 +252,75 @@ function SendToStrava() {
225 252
 
226 253
 // Build CSV
227 254
 function CSV(pos) {
228
-    var CSV = localStorage.getItem("CSV");
229
-    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";
255
+  var CSV = localStorage.getItem("CSV");
256
+  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";
230 257
 
231
-    localStorage.setItem("CSV", CSV + datapoint);
258
+  localStorage.setItem("CSV", CSV + datapoint);
232 259
 
233 260
 }
234 261
 // Send CSV to web server (need configuration on serverside)
235 262
 // TODO : secure it ?
236 263
 function PostToWeb() {
237
-    console.log('--- GPX upload to custom web server');
238
-    var GPX = localStorage.getItem("GPX");
239
-
240
-    var url = "https://jonget.fr/strava/upload.php?name=pebblegpx&type=application/gpx+xml";
241
-    var xhr = new XMLHttpRequest();
242
-    xhr.timeout = 10000; // time in milliseconds
243
-
244
-    xhr.open("POST", url, false);
245
-
246
-    //console.log('------ CSV / xhr opened')
247
-    xhr.onload = function() {
248
-        //console.log('------xhr onload')
249
-        if (xhr.readyState === 4) {
250
-            //console.log('------xhr request returned with ' + xhr.status);
251
-            //console.log(this.responseText);
252
-            if (xhr.status == 200) {
253
-                //console.log('--> HTTP 200');
254
-                return true;
255
-            } else {
256
-                //console.log('--> HTTP ' + xhr.status);
257
-                return false;
258
-            }
259
-        }
260
-    };
264
+  console.log('--- GPX upload to custom web server');
265
+  var GPX = localStorage.getItem("GPX");
266
+
267
+  var url = "https://jonget.fr/strava/upload.php?name=pebblegpx&type=application/gpx+xml";
268
+  var xhr = new XMLHttpRequest();
269
+  xhr.timeout = 10000; // time in milliseconds
270
+
271
+  xhr.open("POST", url, false);
272
+
273
+  //console.log('------ CSV / xhr opened')
274
+  xhr.onload = function () {
275
+    //console.log('------xhr onload')
276
+    if (xhr.readyState === 4) {
277
+      //console.log('------xhr request returned with ' + xhr.status);
278
+      //console.log(this.responseText);
279
+      if (xhr.status == 200) {
280
+        //console.log('--> HTTP 200');
281
+        return true;
282
+      } else {
283
+        //console.log('--> HTTP ' + xhr.status);
284
+        return false;
285
+      }
286
+    }
287
+  };
261 288
 
262
-    //send CSV in body
263
-    xhr.send(GPX);
289
+  //send CSV in body
290
+  xhr.send(GPX);
264 291
 
265 292
 }
266 293
 
267 294
 // Send location to web server for instant location (no tracking)
268 295
 // TODO : secure it ?
269 296
 function instantLocationUpdate(pos) {
270
-    console.log('--- Instant location update');
271
-    // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
272
-
273
-    var url = "https://jonget.fr/find_me/update.php?lat=" + pos.coords.latitude + "&long=" + pos.coords.longitude + "&acc=" + pos.coords.accuracy + "&timestamp=" + pos.timestamp;
274
-    var xhr = new XMLHttpRequest();
275
-    xhr.timeout = 10000; // time in milliseconds
276
-
277
-    xhr.open("POST", url);
278
-
279
-    //console.log('------ instant / xhr opened')
280
-    xhr.onload = function() {
281
-        //console.log('------xhr onload')
282
-        if (xhr.readyState === 4) {
283
-            //console.log('------xhr request returned with ' + xhr.status);
284
-            //console.log(this.responseText);
285
-            if (xhr.status == 200) {
286
-                //console.log('--> HTTP 200');
287
-                return true;
288
-            } else {
289
-                //console.log('--> HTTP ' + xhr.status);
290
-                return false;
291
-            }
292
-        }
293
-    };
297
+  console.log('--- Instant location update');
298
+  // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
299
+
300
+  var url = "https://jonget.fr/find_me/update.php?lat=" + pos.coords.latitude + "&long=" + pos.coords.longitude + "&acc=" + pos.coords.accuracy + "&timestamp=" + pos.timestamp;
301
+  var xhr = new XMLHttpRequest();
302
+  xhr.timeout = 10000; // time in milliseconds
303
+
304
+  xhr.open("POST", url);
305
+
306
+  //console.log('------ instant / xhr opened')
307
+  xhr.onload = function () {
308
+    //console.log('------xhr onload')
309
+    if (xhr.readyState === 4) {
310
+      //console.log('------xhr request returned with ' + xhr.status);
311
+      //console.log(this.responseText);
312
+      if (xhr.status == 200) {
313
+        //console.log('--> HTTP 200');
314
+        return true;
315
+      } else {
316
+        //console.log('--> HTTP ' + xhr.status);
317
+        return false;
318
+      }
319
+    }
320
+  };
294 321
 
295
-    //send without body
296
-    xhr.send();
322
+  //send without body
323
+  xhr.send();
297 324
 
298 325
 }
299 326
 
... ...
@@ -301,184 +328,184 @@ function instantLocationUpdate(pos) {
301 328
 // Adding leading characters to string for nice displays
302 329
 //
303 330
 function padStart(string, max_length, padding) {
304
-    if (string.length > max_length) {
305
-        return string;
306
-    } else {
307
-        var new_str = string;
308
-        for (index = string.length; index < max_length; index++) {
309
-            new_str = "0" + new_str;
310
-        }
311
-        return new_str;
331
+  if (string.length > max_length) {
332
+    return string;
333
+  } else {
334
+    var new_str = string;
335
+    for (index = string.length; index < max_length; index++) {
336
+      new_str = "0" + new_str;
312 337
     }
338
+    return new_str;
339
+  }
313 340
 }
314 341
 
315 342
 // called in case of successful geoloc gathering and sends the coordinate to watch
316 343
 //
317 344
 function locationSuccess(new_pos) {
318
-    console.log('--- locationSuccess');
319
-    // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
345
+  console.log('--- locationSuccess');
346
+  // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
320 347
 
321
-    var prev_pos = getLocation();
322
-    storeLocation(new_pos);
323
-    if (prev_pos === null) {
324
-        console.log('--- start building gpx');
348
+  var prev_pos = getLocation();
349
+  storeLocation(new_pos);
350
+  if (prev_pos === null) {
351
+    console.log('--- start building gpx');
325 352
 
326
-        if (gpx_to_strava || gpx_to_web) {
327
-            // Start the GPX file
328
-            GPXHeadersBuilder(new Date(new_pos.timestamp).toISOString(), "test", "18");
329
-        }
353
+    if (gpx_to_strava || gpx_to_web) {
354
+      // Start the GPX file
355
+      GPXHeadersBuilder(new Date(new_pos.timestamp).toISOString(), "test", "18");
356
+    }
357
+  } else {
358
+    //clear watch of new position to avoid overlap
359
+    //navigator.geolocation.clearWatch(geoloc_id);
360
+    //console.log('--- watch geoloc cleared');
361
+    //var speed = speed_from_distance_and_time(prev_pos, new_pos);
362
+
363
+    //get speed from geoloc API isntead of calculate it
364
+    // speed is initially in m/s, get it at km/h
365
+    if (new_pos.coords.speed === null) {
366
+      var speed = 0;
330 367
     } else {
331
-        //clear watch of new position to avoid overlap
332
-        //navigator.geolocation.clearWatch(geoloc_id);
333
-        //console.log('--- watch geoloc cleared');
334
-        //var speed = speed_from_distance_and_time(prev_pos, new_pos);
335
-
336
-        //get speed from geoloc API isntead of calculate it
337
-        // speed is initially in m/s, get it at km/h
338
-        if (new_pos.coords.speed === null) {
339
-            var speed = 0;
340
-        } else {
341
-            var speed = new_pos.coords.speed * 3.6;
342
-        }
368
+      var speed = new_pos.coords.speed * 3.6;
369
+    }
343 370
 
344
-        // Prepare display on watch
345
-        // now it's only raw data
346
-        // init strings
347
-        var latitudeString = "";
348
-        var longitudeString = "";
349
-        var accuracyString = "";
350
-        var altitudeString = "";
351
-        var speedString = "";
352
-
353
-        //formating for precision and max size
354
-        latitudeString = new_pos.coords.latitude.toString().substring(0, 12);
355
-        longitudeString = new_pos.coords.longitude.toString().substring(0, 12);
356
-        accuracyString = new_pos.coords.accuracy.toString().substring(0, 4);
357
-        //console.log("split num : " + new_pos.coords.altitude);
358
-        altitudeString = splitFloatNumber(new_pos.coords.altitude)[0].toString().substring(0, 5);
359
-        timestampISO = new Date(new_pos.timestamp).toISOString();
360
-        //console.log("split num : " + speed);
361
-        speedString = splitFloatNumber(speed)[0].toString().substring(0, 3); //+ "." + splitFloatNumber(speed)[1].toString().substring(0, 1);
362
-
363
-        //console.log("split num : " + getMaxSpeed(speed));
364
-        maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 4);
365
-
366
-        if (speedString == "NaN") {
367
-            speedString = "---";
368
-        }
371
+    // Prepare display on watch
372
+    // now it's only raw data
373
+    // init strings
374
+    var latitudeString = "";
375
+    var longitudeString = "";
376
+    var accuracyString = "";
377
+    var altitudeString = "";
378
+    var speedString = "";
379
+
380
+    //formating for precision and max size
381
+    latitudeString = new_pos.coords.latitude.toString().substring(0, 12);
382
+    longitudeString = new_pos.coords.longitude.toString().substring(0, 12);
383
+    accuracyString = new_pos.coords.accuracy.toString().substring(0, 4);
384
+    //console.log("split num : " + new_pos.coords.altitude);
385
+    altitudeString = splitFloatNumber(new_pos.coords.altitude)[0].toString().substring(0, 5);
386
+    timestampISO = new Date(new_pos.timestamp).toISOString();
387
+    //console.log("split num : " + speed);
388
+    speedString = splitFloatNumber(speed)[0].toString().substring(0, 3); //+ "." + splitFloatNumber(speed)[1].toString().substring(0, 1);
389
+
390
+    //console.log("split num : " + getMaxSpeed(speed));
391
+    maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 4);
392
+
393
+    if (speedString == "NaN") {
394
+      speedString = "---";
395
+    }
369 396
 
370
-        if (gpx_to_strava || gpx_to_web) {
371
-            //add a new datapoint to GPX file
372
-            GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
397
+    if (gpx_to_strava || gpx_to_web) {
398
+      //add a new datapoint to GPX file
399
+      GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
373 400
 
374
-        }
375
-
376
-        // Build message
377
-        message = "OK";
378
-        var dict = {
379
-            'accuracy': accuracyString,
380
-            'altitude': altitudeString,
381
-            'speed': speedString,
382
-            'max_speed': maxSpeedString,
383
-            'status': message
384
-        };
385
-
386
-        // Send the message
387
-        Pebble.sendAppMessage(dict, function() {
388
-            console.log('Message sent successfully: ' + JSON.stringify(dict));
389
-        }, function(e) {
390
-            console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
391
-        });
392 401
     }
393 402
 
403
+    // Build message
404
+    message = "OK";
405
+    var dict = {
406
+      'accuracy': accuracyString,
407
+      'altitude': altitudeString,
408
+      'speed': speedString,
409
+      'max_speed': maxSpeedString,
410
+      'status': message
411
+    };
412
+
413
+    // Send the message
414
+    Pebble.sendAppMessage(dict, function () {
415
+      console.log('Message sent successfully: ' + JSON.stringify(dict));
416
+    }, function (e) {
417
+      console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
418
+    });
419
+  }
420
+
394 421
 }
395 422
 
396 423
 function locationError(err) {
397 424
 
398
-    console.warn('location error (' + err.code + '): ' + err.message);
399
-    /*
400
-    if (gpx_to_web) {
425
+  console.warn('location error (' + err.code + '): ' + err.message);
426
+  /*
427
+  if (gpx_to_web) {
401 428
 
402
-        var CSV = localStorage.getItem("CSV");
403
-        var datapoint = Date.now() + ",location error," + err.code + "," + err.message + ",,,,";
429
+      var CSV = localStorage.getItem("CSV");
430
+      var datapoint = Date.now() + ",location error," + err.code + "," + err.message + ",,,,";
404 431
 
405
-        localStorage.setItem("CSV", CSV + datapoint);
406
-    }*/
432
+      localStorage.setItem("CSV", CSV + datapoint);
433
+  }*/
407 434
 
408 435
 }
409 436
 
410 437
 
411 438
 function get_coordinate() {
412
-    console.log('--- Starting regular getCurrentPosition loop using setInterval at 5 sec');
439
+  console.log('--- Starting regular getCurrentPosition loop using setInterval at 5 sec');
413 440
 
414
-    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, firstlocationOptions);
441
+  navigator.geolocation.getCurrentPosition(locationSuccess, locationError, firstlocationOptions);
415 442
 
416
-    locationInterval = setInterval(function() {
417
-        navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
418
-    }, 1000);
443
+  locationInterval = setInterval(function () {
444
+    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
445
+  }, 1000);
419 446
 
420
-    instantLocationInterval = setInterval(function() {
421
-        navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, locationOptions);
422
-    }, 60000);
447
+  instantLocationInterval = setInterval(function () {
448
+    navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, locationOptions);
449
+  }, 60000);
423 450
 
424 451
 }
425 452
 
426 453
 function init() {
427
-    // local storage init,
428
-    // todo : clear only temporary values, not clay config (and do it on exit ?)
429
-    localStorage.clear();
430
-    localStorage.setItem("CSV", "");
431
-    // clear any other var to do
432
-    clearInterval(locationInterval);
454
+  // local storage init,
455
+  // todo : clear only temporary values, not clay config (and do it on exit ?)
456
+  localStorage.clear();
457
+  localStorage.setItem("CSV", "");
458
+  // clear any other var to do
459
+  clearInterval(locationInterval);
433 460
 
434 461
 }
435 462
 
436 463
 // Get JS readiness events
437
-Pebble.addEventListener('ready', function(e) {
438
-    console.log('PebbleKit JS is ready');
439
-    // Update Watch on this
440
-    Pebble.sendAppMessage({ 'JSReady': 1 });
464
+Pebble.addEventListener('ready', function (e) {
465
+  console.log('PebbleKit JS is ready');
466
+  // Update Watch on this
467
+  Pebble.sendAppMessage({ 'JSReady': 1 });
441 468
 
442
-    init();
469
+  init();
443 470
 });
444 471
 
445 472
 // Get AppMessage events
446
-Pebble.addEventListener('appmessage', function(e) {
447
-    // Get the dictionary from the message
448
-    var dict = e.payload;
449
-    //console.log(dict[0].toString());
450
-    switch (dict[0]) {
451
-        case 'get':
452
-            get_coordinate();
453
-            break;
454
-        case 'exit':
455
-            clearInterval(instantLocationInterval);
456
-            clearInterval(locationInterval);
457
-            if (gpx_to_strava || gpx_to_web) {
458
-                //End GPX file
459
-                GPXfooterBuilder();
460
-                if (gpx_to_strava) {
461
-                    //send to strava through API
462
-                    SendToStrava();
463
-                }
464
-                if (gpx_to_web) {
465
-                    // send CSV to web server through API
466
-                    PostToWeb();
467
-                }
468
-            }
469
-            // Send the message
470
-            var dict = {
471
-                'status': "KO"
472
-            };
473
-            Pebble.sendAppMessage(dict, function() {
474
-                console.log('Message sent successfully: ' + JSON.stringify(dict));
475
-            }, function(e) {
476
-                console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
477
-            });
478
-
479
-            break;
480
-        default:
481
-            console.log('Sorry. I don\'t understand your request :' + dict[0]);
482
-    }
473
+Pebble.addEventListener('appmessage', function (e) {
474
+  // Get the dictionary from the message
475
+  var dict = e.payload;
476
+  //console.log(dict[0].toString());
477
+  switch (dict[0]) {
478
+    case 'get':
479
+      get_coordinate();
480
+      break;
481
+    case 'exit':
482
+      clearInterval(instantLocationInterval);
483
+      clearInterval(locationInterval);
484
+      if (gpx_to_strava || gpx_to_web) {
485
+        //End GPX file
486
+        GPXfooterBuilder();
487
+        if (gpx_to_strava) {
488
+          //send to strava through API
489
+          SendToStrava();
490
+        }
491
+        if (gpx_to_web) {
492
+          // send CSV to web server through API
493
+          PostToWeb();
494
+        }
495
+      }
496
+      // Send the message
497
+      var dict = {
498
+        'status': "KO"
499
+      };
500
+      Pebble.sendAppMessage(dict, function () {
501
+        console.log('Message sent successfully: ' + JSON.stringify(dict));
502
+      }, function (e) {
503
+        console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
504
+      });
505
+
506
+      break;
507
+    default:
508
+      console.log('Sorry. I don\'t understand your request :' + dict[0]);
509
+  }
483 510
 
484 511
 });
485 512
\ No newline at end of file