Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CurrentRanger output to redis-timeseries
import io
import time
import math
import serial
import threading
from redistimeseries.client import Client as RedisTimeSeries
from time import sleep
from datetime import datetime
#from redis import Redis
redis_host = 'ubuntu' #changeme
redis_port = 6379
redis_key = 'energy'
redis_downsample = redis_key + ':sub'
redis_sum = redis_key + ':sum'
serialdev = '/dev/cu.usbmodem401' #changeme
baud = 230400
rts = RedisTimeSeries(port=redis_port,host=redis_host)
rts.redis.flushdb()
rts.create(key=redis_key, retention_msecs=600000) # keep 10 minutes' worth
rts.create(key=redis_downsample, retention_msecs=36000000) # keep downsamples for 10 hours
rts.create(key=redis_sum, retention_msecs=36000000)
rts.createrule(\
source_key=redis_key,\
dest_key=redis_downsample,\
aggregation_type='avg',\
bucket_size_msec=100) # aggregate average over 100 ms for downsamples
sio = serial.Serial(serialdev, baud)
total = 0
count = 0
firstSampleTime = 0
prevTime = 0
mAh = 0
timer = 0
def logTotal(milliAmpSecond, timer):
global mAh
mAh += milliAmpSecond/3600
print(mAh)
rts.add(key=redis_sum, timestamp=t, value=mAh) # mAh
rts.redis.set('estimate', 86400 * (float(mAh)/timer))
rts.redis.set('estimate_time', timer)
# x = threading.Thread(target=logTotal)
# x.start()
while True:
line = sio.readline().decode("utf-8").split(':',2)
sampleTime = int(line[0])
if not firstSampleTime:
t = math.floor(time.time()*1000)
count = 1
firstSampleTime = sampleTime
try:
val = f'{float(line[1])/1000000:.10f}' # milliamps
if float(val) > 100 or float(val) < -1:
print('rejected value: ' + line[1])
continue
count += 1
timeOffset = (sampleTime - firstSampleTime)
if t+timeOffset <= prevTime:
continue
prevTime = t+timeOffset
total += float(val)
rts.add(key=redis_key, timestamp=prevTime, value=val)
if timeOffset >= 1000:
timer += timeOffset / 1000
avg = f'{(total / count) * (timeOffset / 1000):.20f}' # milli amps second
total = 0
firstSampleTime = 0
# print(avg)
logTotal(float(avg), float(timer))
except ValueError:
print('non-data output: ' + val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment