Skip to content
This repository was archived by the owner on Jan 11, 2024. It is now read-only.

Commit 13852ad

Browse files
committed
Fix timestamps on events
The event was reporting some crazy numbers from before 1970 and sometimes with a 10 year difference between events that took place within seconds. The code was losing information as it was forcing a 64 bit number into a 32 bit number. This fix provides the correct timestamp in nanoseconds.
1 parent 5652977 commit 13852ad

4 files changed

Lines changed: 15 additions & 4 deletions

File tree

README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,18 @@ Circuits.GPIO.Chip.listen_event("gpiochip0", 27)
8989

9090
When an event is received from the line it will be in the form of:
9191

92-
```
92+
```elixir
9393
{:circuits_cdev, pin_number, timestamp, new_value}
9494
```
9595

96+
The `timestamp` is the unix time in nanoseconds. In order to convert it into a
97+
`DateTime` you will need to pass the `:nanoseconds` as the unit to
98+
`DateTime.from_unix/3` function:
99+
100+
```elixir
101+
DateTime.from_unix(timestamp, :nanoseconds)
102+
{:ok, ~U[1990-07-24 07:30:03.123456Z]}
103+
```
96104

105+
Also when calculating the time delta between two events keep in mind the
106+
difference will be nanoseconds.

src/cdev_nif.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ static ERL_NIF_TERM read_event_data_nif(ErlNifEnv *env, int argc, const ERL_NIF_
166166
return common_make_error(env, enif_make_atom(env, "read_event_data_failed"));
167167

168168
ERL_NIF_TERM value = enif_make_int(env, event_data->id);
169-
ERL_NIF_TERM timestamp = enif_make_int(env, event_data->timestamp);
169+
ERL_NIF_TERM timestamp = enif_make_uint64(env, event_data->timestamp);
170170

171171
return enif_make_tuple3(env, priv->atom_ok, value, timestamp);
172172

src/gpio_chip.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ int chip_read_event_data(struct gpio_chip_event_handle *handle, struct gpio_chip
9797
return -1;
9898

9999
data->timestamp = event_data.timestamp;
100-
data->id = (int)event_data.id;
100+
data->id = event_data.id;
101101

102102
return 0;
103103
}

src/gpio_chip.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#define GPIO_CHIP_H
66

77
#include <linux/gpio.h>
8+
#include <stdint.h>
89
#include "erl_nif.h"
910

1011
#define GPIO_CHIP_LINE_INPUT 0x00
@@ -44,7 +45,7 @@ struct gpio_chip_event_handle {
4445
* Struct for event data
4546
*/
4647
struct gpio_chip_event_data {
47-
int timestamp;
48+
uint64_t timestamp;
4849
int id;
4950
};
5051

0 commit comments

Comments
 (0)