-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improve decoding fractional epoch timestamps
Add `test_timestamp_seconds_float`: Publish single reading in JSON format to MQTT broker, using a timestamp as Unix Epoch in seconds, as float number. Proof that the timestamp is processed and stored correctly.
- Loading branch information
Showing
2 changed files
with
49 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,7 @@ | ||
# -*- coding: utf-8 -*- | ||
# (c) 2015-2021 Andreas Motl <[email protected]> | ||
import math | ||
|
||
import requests | ||
from copy import deepcopy | ||
from funcy import project | ||
|
@@ -177,7 +179,7 @@ def format_chunk(self, meta, data): | |
# Decode timestamp. | ||
chunk['time'] = data[time_field] | ||
if is_number(chunk['time']): | ||
chunk['time'] = int(float(chunk['time'])) | ||
chunk['time'] = float(chunk['time']) | ||
|
||
# Remove timestamp from data payload. | ||
del data[time_field] | ||
|
@@ -209,18 +211,35 @@ def format_chunk(self, meta, data): | |
timestamp = chunk['time'] = parse_timestamp(chunk['time']) | ||
|
||
# Heuristically compute timestamp precision | ||
if isinstance(timestamp, int): | ||
if isinstance(timestamp, (int, float)): | ||
if timestamp >= 1e17 or timestamp <= -1e17: | ||
time_precision = 'n' | ||
elif timestamp >= 1e14 or timestamp <= -1e14: | ||
time_precision = 'u' | ||
elif timestamp >= 1e11 or timestamp <= -1e11: | ||
time_precision = 'ms' | ||
|
||
# FIXME: Is this a reasonable default? | ||
# TODO: Is this a reasonable default? | ||
else: | ||
time_precision = 's' | ||
|
||
# Support fractional epoch timestamps like `1637431069.6585083`. | ||
if isinstance(timestamp, float): | ||
fractional, whole = math.modf(timestamp) | ||
fracdigits = len(str(fractional)) - 2 | ||
if fracdigits > 0: | ||
if fracdigits <= 3: | ||
exponent = 3 | ||
time_precision = "ms" | ||
elif fracdigits <= 6: | ||
exponent = 6 | ||
time_precision = "u" | ||
else: | ||
exponent = 9 | ||
time_precision = "n" | ||
timestamp = timestamp * (10 ** exponent) | ||
|
||
chunk['time'] = int(timestamp) | ||
chunk['time_precision'] = time_precision | ||
|
||
""" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters