Determine the timing and add it to an array

I am currently working on an application that reads values from external devices and then writes these values to a database.

The values I deal with include acceleration, gyroscope, magnetometer, and pressure.

For acceleration, gyroscope, and magnetometer, the readings are obtained along with a timestamp as shown below:

(for example, for acceleration)

const buf = Buffer.from(characteristic.value, "base64");
        const [time, ...acc] = [0,2,4,6].map(index => buf.readInt16LE(index));
        this.setState(state => ({
          time,
          acc,
          array_acc_sx: [
            ...state.array_acc_sx, 
            [time , acc ]  
          ]
        }));

However, obtaining the timestamp for pressure readings poses a challenge since it doesn't come automatically. To address this issue, I have considered setting a variable 'timeP' equal to the timestamp of the accelerometer, gyroscope, and magnetometer readings.

But doing so results in the timestamp for pressure starting before the actual pressure values are read, leading to inaccurate data representation like the one shown below:

   "PL":
     "[740,740,740,740,700,700,660,660,580,580,580,
560,500,500,500,500,500,440,400,400,340,340,320,300,
280,260,260,260,200,180,160,160,140,
// timestamps + pressure values commence here.
[140,[0,0,0,0,0]],[160,[0,0,0,0,0]],[160,[0,0,0,0,0]],
[180,[0,0,0,0,0]],[200,[0,0,0,0,0]],[260,[0,0,0,0,0]],
[260,[0,0,0,0,0]],[260,[0,0,0,0,0]],[280,[0,0,0,0,0]],
[300,[0,0,0,0,0]],[320,[0,0,0,0,0]],[340,[0,0,0,0,0]],
[340,[0,0,0,0,0]],[400,[0,0,0,0,0]],[400,[0,0,0,0,0]],
[440,[0,0,0,0,0]],[500,[0,0,0,0,0]],[500,[0,0,0,0,0]],
.....

In order to address this issue, I've included code snippets that handle reading and storing the sensor data in the application. However, I'm seeking advice on how to effectively solve this problem. Any insights would be greatly appreciated. Thank you.

Answer №1

If you're interested in capturing the time of each state, one approach is to utilize a setInterval() function:

let currentTime = 0;

function resetTimer()
{
  currentTime = 0;
  clearInterval(stateInterval);
  console.log("State timer reset");
}

function initiateStateTimer(unit)
{
  // Unit will determine the timing increment (e.g., 1 for milliseconds, 1000 for seconds)
  setInterval(updateTimer, unit);
}

function updateTimer()
{
  currentTime++;
}

function initialize()
{
  device.monitorCharacteristicForService(
    service,
    this.Pressure,
    (error, characteristic) => {
      if (error) {
        this.error(error.message);
        return;
      }
      console.log("Current Time - ", currentTime);
      const buf = Buffer.from(characteristic.value, "base64");
      const [...pressureValues] = [0, 2, 4, 6, 8].map(index => buf.readUInt16LE(index));
      this.setState(state => ({
        ...state.timeData, 
        pressureValues, 
        arrayPressureValues: [
          this.state.timeData, 
          ...state.arrayPressureValues, 
          [this.state.timeData, pressureValues]
        ]
      }));
    });
  
  initiateStateTimer(1); // Increment by 1 millisecond
}

initialize(); // Start monitoring

Feel free to let me know if this aligns with your requirements! :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring texture consistency for scene backgrounds in three.js

I am facing an issue with adding a background to a scene using a PNG image of 2k resolution. The background appears correctly sized on PC, but on mobile devices, it looks disproportionated. Here is the code snippet I am using: var texture = THREE.ImageUti ...

Retrieve various key-value pairs from the JSON data in the global market API using AJAX

I have recently developed a real-time API specifically designed for monitoring World Stock Markets. This API covers popular indices such as Nifty, Dow Jones, Nasdaq, and SGX Nifty. If you are interested in accessing this Real Time API, you can do so by vi ...

The Fixed Navbar is causing sections to be slightly off from their intended positions

Utilizing a bootstrap navigation menu on my website with a fixed position. When clicking a menu item, it takes me to the designated section but slightly above the desired position. How can I ensure that it goes to the exact position upon clicking the men ...

Strategies for obtaining newly updated data with every request and implementing a no-cache approach in Apollo GraphQL and Angular

Every time a request is made, we need a fresh value, like a unique nonce. However, I am facing issues while trying to achieve this with Apollo's Angular client. My initial solution was to utilize watchQuery with the no-cache strategy: this.apollo.wat ...

Move the Form to the Top of the Window and Highlight the First Input Field

There's a link in the header that says "Let's chat": <div class="letstalk"> <a href="javascript:scrollForm();"> Let's chat <img src="/wp-content/uploads/link-icon.png"> </a> </div> ...

Adding a button to a shadow root that already exists is not the proper procedure

var shadow = document.getElementById( "3rd-party-div" ).shadowRoot; let style = document.createElement("style"); style.textContent = ` .custom_button{ padding: 10px; display:block; float:left; text-ali ...

Is there a way to adjust the size of the canvas element in HTML without compromising quality or resorting to zooming?

I'm currently working on a basic modeling application for the web. The main component of my app is a canvas element that I'm trying to size correctly. However, when I set the height and width using CSS, it scales the entire canvas and compromises ...

Responsive jQuery drop-down navigation menu for touchscreen devices struggles with hiding one menu item while clicking on another

I'm currently working on implementing a dropdown navigation menu for touch devices utilizing jQuery. I have managed to successfully hide dropdowns when tapping on the menu item title or outside the navigation area. However, I am facing an issue where ...

Guide on invoking Objective-C function from JavaScript on iOS

I'm currently working on integrating Highchart into an iOS app. I have a requirement where I need to pass values from JavaScript (HTML file) to an Objective-C method. For example, when a user zooms in on the chart displayed in a UIWebView using Highch ...

What is the best way to modify an object within a pure function in JavaScript?

Currently, I am exploring different strategies to ensure that a function remains pure while depending on object updates. Would creating a deep copy be the only solution? I understand that questions regarding object copying are quite common here. However, ...

I am encountering an Uncaught TypeError while diagnosing the issue: why is __webpack_require__(...).createServer not functioning as expected

I am currently working on a Vue project that integrates with Stripe. However, I encountered an error when I loaded my workspace recently, and I am having trouble figuring out how to resolve it. Oddly enough, the live version of my project is functioning p ...

Looking to migrate my current firebase/react project to typescript. Any tips on how to batch.update?

Having difficulty resolving a typescript error related to batch.update in my code. const batch = db.batch(); const listingDoc = await db.collection("listings").doc(listingID).get(); const listingData = listingDoc.data( ...

Deleting a specific element in React: Step-by-step guide

Having an issue with the handleDelete() method in DisplayList.JSX where it is deleting the first element instead of the selected element. How can this be resolved? Github Display.jsx import {DisplayList} from './DisplayList'; class Display e ...

What triggers the firing of onAuthStateChanged() in a Netxjs application?

Hey everyone, I've encountered an issue with a useEffect hook in my root page.tsx file within a Next.js app. Specifically, on my /SignIn page.tsx, I've set up Google as a login provider using FirebaseAuth. When I log in with signInWithPopup, I ex ...

Searching and selecting columns in React using Material-UI

Currently, I am using Material-UI data tables and have implemented a search functionality similar to this Codesandbox example, which only searches the Name/Food column. This is my existing code snippet: const [filterFn, setFilterFn] = useState({ fn: items ...

Is there a way to incorporate Vue script in Laravel without utilizing Vue templates?

I have a question that may seem simple, but I'm curious about the best way to use vue script on pages individually without declaring it globally. For example, I have multiple pages in Laravel Blade such as the home page, category page, and product pag ...

Is there a way for me to position my button above the text?

I am trying to align my text and button at the top of the screen, but there seems to be a gap between the two elements. I attempted to add marginBottom to the text, which helped move it to the top. However, when I added marginBottom to the button as well, ...

Sharing information among v-for divisions - Vue.js

I am currently delving into the world of VueJS. While my code may not be the most elegant, it does the job almost as intended. The issue I am facing is that the API provides the title and href separately in different v-for loops, even though each loop only ...

Tips for showing items on the screen with a search text input in Expo and React Native

Utilizing react native and expo, I have JSON data presented on the iOS simulator screen that was fetched from an API. Positioned at the top is a search bar where users can query the displayed data. For instance, if the data appears as follows: A a compa ...

What is the method for assigning a class name to a child element within a parent element?

<custom-img class="decrease-item" img-src="images/minus-green.svg" @click="event => callDecreaseItem(event, itemId)" /> Here we have the code snippet where an image component is being referenced. <template&g ...