Created
March 1, 2016 20:33
-
-
Save Natureshadow/1433d23d19fd873bccfc to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
from datetime import datetime | |
from time import mktime | |
import os | |
def v_to_n(wind, vbatt, ibatt): | |
""" Merge three values into one 16-bit integer """ | |
return ((wind + 10)<<10) + ((vbatt + 10)<<5) + (ibatt + 10) | |
def n_to_v(n): | |
""" Convert 16-bit integer into three values """ | |
wind = (n>>10) - 10 | |
n -= (wind + 10) << 10 | |
vbatt = (n>>5) - 10 | |
n -= (vbatt + 10) << 5 | |
ibatt = n - 10 | |
return (wind, vbatt, ibatt) | |
def n_to_c(n): | |
""" Convert 16-bit integer into two bytes """ | |
a = n >> 8 | |
b = n - (a<<8) | |
return chr(a) + chr(b) | |
def c_to_n(c): | |
""" Convert two bytes into 16-bit integer """ | |
a = ord(c[0]) | |
b = ord(c[1]) | |
return (a<<8) + b | |
def writedata(datadir, c): | |
""" Write two bytes to correct place """ | |
# Start of day and tiemstamp now | |
sod = int(mktime(datetime.utcnow().date().timetuple())) | |
now = int(mktime(datetime.utcnow().timetuple())) | |
# Diff from now to start of day | |
diff = now - sod | |
# Open file | |
with open(os.path.join(datadir, str(sod)), "a+b") as f: | |
# Get file size and append zeroes if necessary | |
f.seek(0, 2) | |
missing = 2*diff - f.tell() - 2 | |
if missing > 0: | |
f.write(chr(0) * missing) | |
# Write data and close | |
f.write(c) | |
def readdata(datadir, t): | |
""" Read two bytes from correct position """ | |
# Start of day and given timestamp | |
now = int(mktime(t.timetuple())) | |
sod = int(mktime(t.date().timetuple())) | |
# Open file | |
with open(os.path.join(datadir, str(sod)), "r+b") as f: | |
# Seek to correct position and read two bytes | |
f.seek(2*(now - sod) - 2) | |
return f.read(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code under MirOS or Simplified BSD license