Developer Portal Community

    cancel
    Showing results for 
    Search instead for 
    Did you mean: 

    Save data in database.

    Save data in database.

    ceser
    New Poster

    Hello!

    I want to save and store some data points to file or database. Accessing these values and displaying them on the screen of my smartphone was not complicated. But I have some problems to write them to a file or store them in a database. I used "local storage" and the code that you have given in a previous topic but it doesn't work.

    I'm not a Java or HTML developer, I just have some basic knowledge. So I really need your help actually.

    • My first option was to use Firebase to host my Web application (module) and to have a database. I have tested the connection of my web application with the database and it works without any problems. For example, with "surname" and "first name" blocks to be filled in, I can store the different surnames and first names written in the web app. But I don't know who to store the battery level, the speed, user Power... I am using the "SaveDataToLocalStorage" function which that looks a lot like your code. In this function, I am storing strings in local storage and then I try to get the value by using "getElementById"  and push the value to firebase. This function is launched as soon as I press my submit button (as you can see at the end of the code). But I don't get anything on firebase and I don't know why.

     

    <!DOCTYPE html>
    <html>
    <head>
      <img src=http://www.unistra.fr/fileadmin/_processed_/b/d/csm_Faculte_Physique_Etroit_Couleur_99fbbfd582.png alt=”alternate text” title=”infotip text” height=70 width=160 <h2> Data measurement-Can ESER</h2>
    </head>
      
    <body>
      <div id="header">
      <!--<h2>Data measurement-Can ESER</h2>-->
      </div>
      <div class="my-content">
        <h3>Battery values:</h3>
        <div id="BatteryCondition"></div>
        <h3>Motor values:</h3>
        <div id="assistanceIndicator"></div>
        <div id="range"></div>
        <div id="driveMode"></div>
        <div id="userPower"></div>
        <h3>User specific values:</h3>
        <div id="speed"></div>
        <div id="heartRateAvailability"></div>
        <div id="heartRate"></div>
        <div id="cadence"></div>
        <div id="ascent"></div>
        <h3>GPS Coordinates:</h3>
        <div id="latitude"></div>
        <div id="longitude"></div>
        <div id="altitude"></div>
      </div>
    
      <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    
      <!-- COBI.JS -->
      <script src="https://cdn.cobi.bike/cobi.js/0.44.0/cobi.js"></script>
    
      <!-- The core Firebase JS SDK is always required and must be listed first -->
      <script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-app.js"></script>
      <script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-database.js"></script>
    
      <!-- TODO: Add SDKs for Firebase products that you want to use
         https://firebase.google.com/docs/web/setup#available-libraries -->
         <script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-analytics.js"></script>
    
      <script>
        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        var firebaseConfig = {
          apiKey: "AIzaSyCxavRUxMBtDjltnShGoCZpOj-gfzWMPeI",
          authDomain: "caneserdata.firebaseapp.com",
          databaseURL: "https://caneserdata.firebaseio.com",
          projectId: "caneserdata",
          storageBucket: "caneserdata.appspot.com",
          messagingSenderId: "643551638164",
          appId: "1:643551638164:web:1d570cdef47c5f8cd2ba81",
          measurementId: "G-C2LBVPW7H9"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        firebase.analytics();
    
    
        //function writedata(){
         // firebase.database().ref("User").set({
         //   age: document.getElementById("ageField").value
         // });
       // }
    
        function SaveDataToLocalStorage(){
          var speedValues = [];
          var userPowerValues = [];
          var batteryLevelValues = [];
          var batteryLevelDataBase = document.getElementById('batteryLevelData').value
    
          // Parse the serialized data back into an aray of objects
          speedValues = JSON.parse(localStorage.getItem('speedData')) || [];
          userPowerValues = JSON.parse(localStorage.getItem('userPowerData')) || [];
          batteryLevelValues = JSON.parse(localStorage.getItem('batteryLevelData')) || [];
    
          // Push the new data (whether it be an object or anything else) onto the array
          speedValues.push(currentSpeed);
          userPowerData.push(currentUserPower);
          batteryLevelValues.push(batteryLevel);
    
          // Re-serialize the array back into a string and store it in localStorage
          localStorage.setItem('speedData', JSON.stringify(speedValues));
          localStorage.setItem('userPowerData', JSON.stringify(userPowerValues));
          localStorage.setItem('batteryLevelData', JSON.stringify(batteryLevelValues));
    
          firebase.database().ref("User").set({
            batteryLevelFirebase: batteryLevelDataBase
          });
        }
    
      </script>
    
      <script>
        // Authenticate your module
        COBI.init('token');
        
        // Baterry values measurement-------------------------------------------------------------------------
          // State of charge measurement
        COBI.battery.state.subscribe(function(BatteryCondition) {
          batteryLevel = JSON.stringify(BatteryCondition.batteryLevel)
          $('#BatteryCondition').html(`SOC: ${batteryLevel} %`)
        });
    
        // Motor values measurement----------------------------------------------------------------------- 
          // Assistance indicator
        COBI.motor.assistanceIndicator.subscribe(function(assistanceIndicator) {
          $('#assistanceIndicator').html(`Utilization level of set drive mode: ${assistanceIndicator} %`)
        });
    
          // Range
        COBI.motor.range.subscribe(function(range) {
          $('#range').html(`Predicted distance with this support level: ${range} km`)
        });
    
          // Drive Mode
        COBI.motor.driveMode.subscribe(function(driveMode) {
          $('#driveMode').html(`Drive Mode: ${driveMode}`)
        });
    
        // User values measuremet-------------------------------------------------------------------
          // Speed
        COBI.rideService.speed.subscribe(function(speed) {
          speed=speed*3.6
          $('#speed').html(`Speed: ${speed.toFixed(2)} km/h`)
        });
    
        // User Power measurement
        COBI.rideService.userPower.subscribe(function(userPower) {
          $('#userPower').html(`User Power: ${userPower} W`)
        });
    
        // Heart rate 
        COBI.rideService.heartRate.subscribe(function(heartRate) {
          $('#heartRate').html(`Heart rate: ${heartRate} bpm`)
        });
    
        // Hear Rate Sensor Availability
        COBI.rideService.heartRateAvailability.subscribe(function(heartRateAvailability) {
          $('#heartRateAvailability').html(`Heart Rate Sensor Availability: ${heartRateAvailability}`)
        }); 
    
        // Cadence
        COBI.rideService.cadence.subscribe(function(cadence) {
          $('#cadence').html(`Cadence: ${cadence} rpm`)
        });
    
        // Ascent
        COBI.tourService.ascent.subscribe(function(ascent) {
          $('#ascent').html(`Ascent: ${ascent.toFixed(2)} m`)
        });
          
        // GPS coordinates measurement------------------------------------------------------------
        COBI.mobile.location.subscribe(function(location) {
          latitude = JSON.stringify(location.coordinate.latitude);
          $('#latitude').html(`Latitude: ${latitude}`)
        });
        COBI.mobile.location.subscribe(function(location) {
          longitude = JSON.stringify(location.coordinate.longitude);
          $('#longitude').html(`Longitude: ${longitude}`)
        });
        COBI.mobile.location.subscribe(function(location) {
          altitude = JSON.stringify(location.altitude);
          $('#altitude').html(`Altitude: ${altitude}`)
        });    
      </script>
    
      <h1>User Database</h1>
      <button onclick = "SaveDataToLocalStorage()">Submit</button>
    </body>
    </html>​

     

    • Another option was to simply save the data to local storage and then displaying it when off-ride without storing them in database. This option should be easier as you said in a previous topic. But in this case, if I am just using your code:

     

    function SaveDataToLocalStorage(currentSpeed, currentUserPower)
    {
        var speedValues = [];
        var userPowerValues = []:
    
        // Parse the serialized data back into an aray of objects
        speedValues = JSON.parse(localStorage.getItem('speedData')) || [];
        userPowerValues = JSON.parse(localStorage.getItem('userPowerData')) || [];
    
        // Push the new data (whether it be an object or anything else) onto the array
        speedValues.push(currentSpeed);
        userPowerData.push(currentUserPower);
    
        // Re-serialize the array back into a string and store it in localStorage
        localStorage.setItem('speedData', JSON.stringify(speedValues));
        localStorage.setItem('userPowerData', JSON.stringify(userPowerValues));
    }

     

    With your code, I will be able to store data in localStorage but how can I get these values then? Should I have to create another web app? Or should I have to create a Python script to have access to data stored in localStorage?

    Thanks in advance, and hope you'll answer me because I'm really stuck...

    Can ESER.

    2 REPLIES 2

    dfarache-ebike
    Community Moderator
    Community Moderator

    Hello ceser,

    Thank you for posting your question in the COBI.Bike SDK forum.

    I will try to solve the issue you are currently facing. For that, it would be helpful if you could describe the use case you are trying to implement. With that I should be able to tell you what are your options.

    Best regards,

    Hello @dfarache-ebike,

    Thank you for your quick response.

    I want to save and store some data points to file or database. With these stored data, I would like to study the route I have taken and how I can optimize my use of energy according to the level of assistance and the route I have taken. The idea is just to have a record of my day's route with the different parameters stored.

    King regards,

    Can ESER.

    Icon--AD-black-48x48Icon--address-consumer-data-black-48x48Icon--appointment-black-48x48Icon--back-left-black-48x48Icon--calendar-black-48x48Icon--center-alignedIcon--Checkbox-checkIcon--clock-black-48x48Icon--close-black-48x48Icon--compare-black-48x48Icon--confirmation-black-48x48Icon--dealer-details-black-48x48Icon--delete-black-48x48Icon--delivery-black-48x48Icon--down-black-48x48Icon--download-black-48x48Ic-OverlayAlertIcon--externallink-black-48x48Icon-Filledforward-right_adjustedIcon--grid-view-black-48x48IC_gd_Check-Circle170821_Icons_Community170823_Bosch_Icons170823_Bosch_Icons170821_Icons_CommunityIC-logout170821_Icons_Community170825_Bosch_Icons170821_Icons_CommunityIC-shopping-cart2170821_Icons_CommunityIC-upIC_UserIcon--imageIcon--info-i-black-48x48Icon--left-alignedIcon--Less-minimize-black-48x48Icon-FilledIcon--List-Check-grennIcon--List-Check-blackIcon--List-Cross-blackIcon--list-view-mobile-black-48x48Icon--list-view-black-48x48Icon--More-Maximize-black-48x48Icon--my-product-black-48x48Icon--newsletter-black-48x48Icon--payment-black-48x48Icon--print-black-48x48Icon--promotion-black-48x48Icon--registration-black-48x48Icon--Reset-black-48x48Icon--right-alignedshare-circle1Icon--share-black-48x48Icon--shopping-bag-black-48x48Icon-shopping-cartIcon--start-play-black-48x48Icon--store-locator-black-48x48Ic-OverlayAlertIcon--summary-black-48x48tumblrIcon-FilledvineIc-OverlayAlertwhishlist