Mendes
Mendes

Reputation: 18511

How to convert a timestamp from libgpiod to epoch date and time?

Using libgpiod version 1 with C++ bindings, I'm waiting for an event using event_read to get line event changes.

I understand that event comes with a timestamp in the std::chrono::nanoseconds format:

  auto event = line.event_read();
  std::cout << "EVENT TYPE CODE: " << event.event_type << std::endl;
  std::cout << "EVENT TIMESTAMP: " << event.timestamp.count() << std::endl;

So, I'm getting output like:

EVENT TYPE CODE: 1
EVENT TIMESTAMP: 6603108649419

Now I need to convert that timestamp to Linux epoch date and time in seconds, as to register the exact moment the event occurred.

I've tried the following function:

unsigned long State::convert_timestamp_to_epoch(std::chrono::nanoseconds timestamp)
{


     // Extract total number of seconds from nanoseconds
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(timestamp);

    // Convert seconds to unsigned long
    unsigned long epoch_time = static_cast<unsigned long>(seconds.count());
    std::cout << "CONVERTING:" << std::endl;
    std::cout << timestamp.count() << std::endl;
    std::cout << seconds.count() << std::endl;
    std::cout << epoch_time << std::endl;

    return epoch_time;
}   

But I'm getting the following result:

CONVERTING:
6603108649419
6603
6603

None of them are epoch date and times...

How can I convert the std::chrono::nanoseconds timestamp that comes from libgpiod event to epoch date and time?

Upvotes: 0

Views: 72

Answers (0)

Related Questions