Browse code

timeout system

Louis authored on13/06/2025 13:24:41
Showing2 changed files
1 1
Binary files a/build/bike_companion.pbw and b/build/bike_companion.pbw differ
... ...
@@ -9,6 +9,7 @@ var locate_me
9 9
 var firstlocationInterval = false;
10 10
 var locationInterval = false;
11 11
 var instantLocationInterval = false;
12
+var locationTimeout = false;
12 13
 
13 14
 // TODO to move to C for security
14 15
 var client_id = "94880";
... ...
@@ -21,8 +22,8 @@ var firstlocationOptions = {
21 22
 };
22 23
 var locationOptions = {
23 24
     'enableHighAccuracy': true, // default = false (quick and dirty mode), can be true (more accurate but need more power and time)
24
-    'timeout': 10000, // ms timeout to get a good signal
25
-    'maximumAge': 5000 // location can be x milliseconds old
25
+    'timeout': 30000, //30s timeout to get a good position
26
+    'maximumAge': 0 // no cache
26 27
 };
27 28
 
28 29
 Pebble.addEventListener('showConfiguration', function(e) {
... ...
@@ -379,7 +380,7 @@ function PostToWeb() {
379 380
 // Send location to web server for instant location (no live tracking)
380 381
 // TODO : secure it ?
381 382
 function instantLocationUpdate(pos) {
382
-    console.log('--- Instant location update');
383
+    // console.log('--- Instant location update');
383 384
     // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
384 385
 
385 386
     var url = JSON.parse(localStorage.getItem('clay-settings')).ping_location_url + "?lat=" + pos.coords.latitude + "&long=" + pos.coords.longitude + "&acc=" + pos.coords.accuracy + "&timestamp=" + pos.timestamp;
... ...
@@ -412,7 +413,7 @@ function instantLocationUpdate(pos) {
412 413
 // called in case of successful geoloc gathering and sends the coordinate to watch
413 414
 //
414 415
 function locationSuccess(new_pos) {
415
-    console.log('--- locationSuccess');
416
+    // console.log('--- locationSuccess');
416 417
     // console.log(" location is " + new_pos.coords.latitude + ',' + new_pos.coords.longitude + ' , acc. ' + new_pos.coords.accuracy);
417 418
 
418 419
     var prev_pos = getLocation(false);
... ...
@@ -427,7 +428,6 @@ function locationSuccess(new_pos) {
427 428
         GPXHeadersBuilder(new Date(new_pos.timestamp).toISOString(), "Pebble track", "18");
428 429
 
429 430
     } else {
430
-        storeLocation(new_pos, false);
431 431
 
432 432
         // Prepare display on watch
433 433
         // now it's only raw data
... ...
@@ -439,49 +439,55 @@ function locationSuccess(new_pos) {
439 439
         var speedString = "";
440 440
         var distanceString = "";
441 441
 
442
-        // get speed from geoloc API isntead of calculate it
443
-        // speed is initially in m/s, get it at km/h
444
-        if (new_pos.coords.speed === null) {
445
-            var speed = 0;
446
-        } else {
447
-            var speed = new_pos.coords.speed * 3.6;
448
-            localStorage.setItem("speedsum", parseInt(localStorage.getItem("speedsum")) + speed);
449
-        }
442
+        
450 443
 
451 444
         // distance since beginning in m
445
+        console.log("--------- coordinates : " + new_pos.coords.latitude +", " + new_pos.coords.longitude);
452 446
         var dist = distance_on_geoid(prev_pos.coords.latitude, prev_pos.coords.longitude, new_pos.coords.latitude, new_pos.coords.longitude);
453
-        var totaldist = parseInt(localStorage.getItem("dist"));
454
-        if (!isNaN(dist)) {
447
+        console.log("--------- distance since last : " + dist);
448
+       var totaldist = parseInt(localStorage.getItem("dist"));
449
+        if (isNaN(dist) || dist == 0) {
450
+            // early exit as distance since previous position is too small to be parsed
451
+            console.log("--------- not recording this waypoint ");
452
+        }else{
453
+            // get speed from geoloc API isntead of calculate it
454
+            // speed is initially in m/s, get it at km/h
455
+            if (new_pos.coords.speed === null) {
456
+                var speed = 0;
457
+            } else {
458
+                var speed = new_pos.coords.speed * 3.6;
459
+                localStorage.setItem("speedsum", parseInt(localStorage.getItem("speedsum")) + speed);
460
+            }
455 461
             totaldist = totaldist + parseInt(dist);
456 462
             localStorage.setItem("dist", totaldist);
457
-        }
458
-        distanceString = splitFloatNumber(totaldist / 1000)[0].toString() + "." + splitFloatNumber(totaldist / 1000)[1].toString().substring(0, 3);
459
-        //console.log("total dist is now " + totaldist);
460
-
461
-        // avg speed (also when not moving) since beginning
462
-        var avgspeed = parseInt(localStorage.getItem("speedsum")) / parseInt(localStorage.getItem("totalcoordinates"));
463
-        var avgSpeedString = splitFloatNumber(avgspeed)[0].toString() + "." + splitFloatNumber(avgspeed)[1].toString().substring(0, 1);
464
-        console.log("speedsum=" + parseInt(localStorage.getItem("speedsum")) + " / totalcoordinates=" + parseInt(localStorage.getItem("totalcoordinates")));
465
-        console.log("--avgspeed=" + avgspeed + " / avgSpeedString=" + avgSpeedString)
466
-        if (avgSpeedString == "0.N") {
467
-            avgSpeedString = "0.0";
468
-        }
469
-        //console.log("avg speed is : " + avgSpeedString);
463
+            storeLocation(new_pos, false);
464
+        
465
+            distanceString = splitFloatNumber(totaldist / 1000)[0].toString() + "." + splitFloatNumber(totaldist / 1000)[1].toString().substring(0, 3);
466
+            //console.log("total dist is now " + totaldist);
467
+
468
+            // avg speed (also when not moving) since beginning
469
+            var avgspeed = parseInt(localStorage.getItem("speedsum")) / parseInt(localStorage.getItem("totalcoordinates"));
470
+            var avgSpeedString = splitFloatNumber(avgspeed)[0].toString() + "." + splitFloatNumber(avgspeed)[1].toString().substring(0, 1);
471
+            // console.log("speedsum=" + parseInt(localStorage.getItem("speedsum")) + " / totalcoordinates=" + parseInt(localStorage.getItem("totalcoordinates")));
472
+            if (avgSpeedString == "0.N") {
473
+                avgSpeedString = "-.-";
474
+            }
475
+            // console.log("--avgspeed=" + avgspeed + " / avgSpeedString=" + avgSpeedString)
470 476
 
471
-        // Duration
477
+            // Duration
472 478
 
473
-        var duration = new_pos.timestamp - first_pos.timestamp;
474
-        const date = new Date(duration);
475
-        durationString = padStart(date.getUTCHours().toString(), 2, "0") + ":" + padStart(date.getMinutes().toString(), 2, "0") + ":" + padStart(date.getSeconds().toString(), 2, "0");
476
-        console.log("durationString is : " + durationString);
479
+            var duration = new_pos.timestamp - first_pos.timestamp;
480
+            const date = new Date(duration);
481
+            durationString = padStart(date.getUTCHours().toString(), 2, "0") + ":" + padStart(date.getMinutes().toString(), 2, "0") + ":" + padStart(date.getSeconds().toString(), 2, "0");
482
+            // console.log("durationString is : " + durationString + "." + date.getUTCMilliseconds().toString());
477 483
 
478
-        //formating for precision and max size
479
-        latitudeString = new_pos.coords.latitude.toString().substring(0, 12);
480
-        longitudeString = new_pos.coords.longitude.toString().substring(0, 12);
481
-        accuracyString = new_pos.coords.accuracy.toString().substring(0, 4);
482
-        //console.log("split num : " + new_pos.coords.altitude);
483
-        altitudeString = splitFloatNumber(new_pos.coords.altitude)[0].toString().substring(0, 5);
484
-        timestampISO = new Date(new_pos.timestamp).toISOString();
484
+            //formating for precision and max size
485
+            latitudeString = new_pos.coords.latitude.toString().substring(0, 12);
486
+            longitudeString = new_pos.coords.longitude.toString().substring(0, 12);
487
+            accuracyString = new_pos.coords.accuracy.toString().substring(0, 4);
488
+            //console.log("split num : " + new_pos.coords.altitude);
489
+            altitudeString = splitFloatNumber(new_pos.coords.altitude)[0].toString().substring(0, 5);
490
+            timestampISO = new Date(new_pos.timestamp).toISOString();
485 491
 
486 492
         //console.log("split num : " + speed);
487 493
         if (isNaN(speed)) {
... ...
@@ -492,36 +498,48 @@ function locationSuccess(new_pos) {
492 498
                 speedString = "0.-";
493 499
             }
494 500
 
495
-            //console.log("split num : " + getMaxSpeed(speed));
496
-            maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 3);
501
+                //console.log("split num : " + getMaxSpeed(speed));
502
+                maxSpeedString = splitFloatNumber(getMaxSpeed(speed))[0].toString().substring(0, 3);
503
+            }
504
+            // console.log("--speed=" + speed + " / speedString=" + speedString)
505
+
506
+            //add a new datapoint to GPX file
507
+            GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
508
+
509
+
510
+
511
+            // Build message
512
+            message = "L200";
513
+            var dict = {
514
+                'accuracy': accuracyString,
515
+                'distance': distanceString,
516
+                'avg_speed': avgSpeedString,
517
+                'duration': durationString,
518
+                'altitude': altitudeString,
519
+                'speed': speedString,
520
+                'max_speed': maxSpeedString,
521
+                'status': message
522
+            };
523
+
524
+            // Send the message
525
+            Pebble.sendAppMessage(dict, function() {
526
+                // console.log('Message sent successfully: ' + JSON.stringify(dict));
527
+            }, function(e) {
528
+                console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
529
+            });
497 530
         }
498 531
 
499
-        //add a new datapoint to GPX file
500
-        GPXtrkptBuilder(latitudeString, longitudeString, altitudeString, timestampISO);
501
-
502
-
503
-
504
-        // Build message
505
-        message = "L200";
506
-        var dict = {
507
-            'accuracy': accuracyString,
508
-            'distance': distanceString,
509
-            'avg_speed': avgSpeedString,
510
-            'duration': durationString,
511
-            'altitude': altitudeString,
512
-            'speed': speedString,
513
-            'max_speed': maxSpeedString,
514
-            'status': message
515
-        };
516
-
517
-        // Send the message
518
-        Pebble.sendAppMessage(dict, function() {
519
-            console.log('Message sent successfully: ' + JSON.stringify(dict));
520
-        }, function(e) {
521
-            console.log('Message (' + JSON.stringify(dict) + ') failed: ' + JSON.stringify(e));
522
-        });
523 532
     }
524
-
533
+    
534
+    if ( locationTimeout !== false) {    
535
+        // console.log("tracking is ongoing, clearing timeout ref and setting a new one");
536
+        clearTimeout(locationTimeout); 
537
+        locationTimeout = setTimeout(function() {
538
+            navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
539
+        }, 1000);
540
+    }else{
541
+        // console.log("tracking is stopped");
542
+    }
525 543
 
526 544
 }
527 545
 
... ...
@@ -533,15 +551,15 @@ function locationError(err) {
533 551
 
534 552
 
535 553
 function start_get_coordinate() {
536
-    clearInterval(firstlocationInterval);
537
-    firstlocationInterval = false;
538
-    locationInterval = setInterval(function() {
554
+    clearTimeout(locationTimeout);
555
+    locationTimeout = false;
556
+    locationTimeout = setTimeout(function() {
539 557
         navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
540 558
     }, 1000);
541
-
559
+    
542 560
     if (locate_me) {
543 561
         instantLocationInterval = setInterval(function() {
544
-            navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, locationOptions);
562
+            navigator.geolocation.getCurrentPosition(instantLocationUpdate, locationError, firstlocationOptions);
545 563
         }, 60000);
546 564
     }
547 565
 
... ...
@@ -566,34 +584,34 @@ function init() {
566 584
     locate_me = JSON.parse(localStorage.getItem('clay-settings')).ping_location_enabled;
567 585
 
568 586
 
569
-    console.log("Locate_me = " + locate_me);
570
-    console.log("Strava = " + se + " (" + typeof se + ")/ uploaded = " + su + " (" + typeof su + ")");
571
-    console.log("Custom web = " + ce + " (" + typeof ce + ")/ uploaded = " + cu + " (" + typeof cu + ")");
587
+    // console.log("Locate_me = " + locate_me);
588
+    // console.log("Strava = " + se + " (" + typeof se + ")/ uploaded = " + su + " (" + typeof su + ")");
589
+    // console.log("Custom web = " + ce + " (" + typeof ce + ")/ uploaded = " + cu + " (" + typeof cu + ")");
572 590
 
573 591
     if ((se && !su) || (ce && !cu)) {
574 592
 
575 593
         var GPX = localStorage.getItem("GPX");
576
-        console.log("last 6 char of GPX are " + GPX.substring(GPX.length - 6, GPX.length))
594
+        // console.log("last 6 char of GPX are " + GPX.substring(GPX.length - 6, GPX.length))
577 595
         if (GPX.substring(GPX.length - 6, GPX.length) !== "</gpx>") {
578 596
             console.log("WARNING - NO GPX FOOTER ")
579 597
                 /*var footer = '</trkseg></trk></gpx>';
580 598
                 localStorage.setItem("GPX", GPX + footer);*/
581 599
             GPXfooterBuilder();
582 600
             GPX = localStorage.getItem("GPX");
583
-            console.log("GPX FOOTER is now : " + GPX.substring(GPX.length - 6, GPX.length))
601
+            // console.log("GPX FOOTER is now : " + GPX.substring(GPX.length - 6, GPX.length))
584 602
         }
585 603
 
586 604
         if (se) {
587
-            console.log("GPX upload needed to Strava")
605
+            // console.log("GPX upload needed to Strava")
588 606
             SendToStrava();
589 607
         }
590 608
 
591 609
         if (ce) {
592
-            console.log("GPX upload needed to custom server")
610
+            // console.log("GPX upload needed to custom server")
593 611
             PostToWeb();
594 612
         }
595 613
     } else {
596
-        console.log("clearing var")
614
+        // console.log("clearing var")
597 615
         localStorage.setItem("maxSpeed", 0);
598 616
         localStorage.setItem("firstlatitude", "");
599 617
         localStorage.setItem("firstlongitude", "");
... ...
@@ -623,10 +641,10 @@ Pebble.addEventListener('appmessage', function(e) {
623 641
     //console.log(dict[0].toString());
624 642
     switch (dict[0]) {
625 643
         case 'startstop':
626
-            if (!locationInterval == false) {
644
+            if (!locationTimeout == false) {
627 645
                 console.log("Stopping the track");
628
-                clearInterval(locationInterval);
629
-                locationInterval = false;
646
+                clearInterval(locationTimeout);
647
+                locationTimeout = false;
630 648
                 clearInterval(instantLocationInterval);
631 649
                 instantLocationInterval = false;
632 650
                 /*firstlocationInterval = setInterval(function () {