cachew for bluemaestro

This commit is contained in:
Dima Gerasimov 2019-08-04 20:20:19 +01:00
parent f34c796ee8
commit 1d7c0905e1

View file

@ -1,46 +1,43 @@
#!/usr/bin/python3 #!/usr/bin/python3
import sqlite3
# ugh, dataset stumpled over date format
from itertools import islice, chain
from typing import Dict, Any
from datetime import datetime
import logging import logging
from kython import setup_logzero import sqlite3
from datetime import datetime
from itertools import chain, islice
from pathlib import Path from pathlib import Path
from typing import Any, Dict, Iterable, NamedTuple, Set
from cachew import cachew
from kython import dictify
from kython.klogging import LazyLogger
CACHE = Path('/L/data/.cache/bluemaestro.cache')
DIR = Path("/L/zzz_syncthing_backups/bluemaestro/") DIR = Path("/L/zzz_syncthing_backups/bluemaestro/")
# TODO how to move them back? # TODO how to move them back?
DIR2 = Path("/L/zzz_syncthing_phone/phone-syncthing/backups/bluemaestro/") DIR2 = Path("/L/zzz_syncthing_phone/phone-syncthing/backups/bluemaestro/")
def get_logger(): logger = LazyLogger('bluemaestro', level=logging.DEBUG)
return logging.getLogger('bluemaestro')
def get_temperature(all_=False): def get_backup_files():
logger = get_logger() return list(sorted(chain(
backups = list(sorted(chain(
DIR.glob('*.db'), DIR.glob('*.db'),
DIR2.glob('*.db'), DIR2.glob('*.db'),
))) )))
if not all_:
backups = [backups[-1]]
merged: Dict[datetime, Any] = {}
for f in backups: class Point(NamedTuple):
def reg(dt: datetime, value): dt: datetime
v = merged.get(dt, None) temp: float
if v is None:
merged[dt] = value
return @cachew(db_path=CACHE)
if value == v or (isinstance(v, set) and value in v): def iter_points(dbs) -> Iterable[Point]:
return # I guess we can affort keeping them in sorted order
if isinstance(v, set): points: Set[Point] = set()
v.add(value) # TODO do some sanity check??
else: for f in dbs:
merged[dt] = {v, value}
# err = f'{f}: mismatch: {v} vs {value}' # err = f'{f}: mismatch: {v} vs {value}'
# if abs(v - value) > 0.4: # if abs(v - value) > 0.4:
# logger.warning(err) # logger.warning(err)
@ -48,36 +45,46 @@ def get_temperature(all_=False):
# # raise AssertionError(err) # # raise AssertionError(err)
# else: # else:
# pass # pass
with sqlite3.connect(str(f)) as db:
datas = list(db.execute('select * from data'))
for _, tss, temp, hum, pres, dew in datas:
# TODO is that utc???
tss = tss.replace('Juli', 'Jul').replace('Aug.', 'Aug')
dt = datetime.strptime(tss, '%Y-%b-%d %H:%M')
p = Point(
dt=dt,
temp=temp,
)
if p in points:
continue
points.add(p)
for p in sorted(points, key=lambda p: p.dt):
yield p
db = sqlite3.connect(str(f)) # logger.info('total items: %d', len(merged))
datas = list(db.execute('select * from data'))
for _, tss, temp, hum, pres, dew in datas:
# TODO is that utc???
tss = tss.replace('Juli', 'Jul').replace('Aug.', 'Aug')
dt = datetime.strptime(tss, '%Y-%b-%d %H:%M')
reg(dt, temp)
db.close()
logger.info('total items: %d', len(merged))
# TODO assert frequency? # TODO assert frequency?
# for k, v in merged.items(): # for k, v in merged.items():
# # TODO shit. quite a few of them have varying values... how is that freaking possible???? # # TODO shit. quite a few of them have varying values... how is that freaking possible????
# # most of them are withing 0.5 degree though... so just ignore? # # most of them are withing 0.5 degree though... so just ignore?
# if isinstance(v, set) and len(v) > 1: # if isinstance(v, set) and len(v) > 1:
# print(k, v) # print(k, v)
return merged # for k, v in merged.items():
# yield Point(dt=k, temp=v) # meh?
# TODO does it even have to be a dict?
@dictify(key=lambda p: p.dt)
def get_temperature(backups=get_backup_files()):
yield from iter_points(backups)
def test(): def test():
get_temperature(all_=False) get_temperature(get_backup_files()[-1:])
def main(): def main():
setup_logzero(get_logger(), level=logging.DEBUG) ll = list(iter_points(get_backup_files()))
get_temperature() print(len(ll))
# print(get_temperature(get_backup_files()[-1:]))
# print(type(t))
if __name__ == '__main__': if __name__ == '__main__':