backend_iot/db.py (view raw)
1from peewee import Model, IntegerField, DateTimeField, DoesNotExist, FloatField, BooleanField
2from playhouse.sqliteq import SqliteQueueDatabase
3from backend_iot.api import get_aqi_owm
4from datetime import datetime, timedelta
5
6db = SqliteQueueDatabase("records.db")
7api_interval = timedelta(minutes=3)
8lat_threshold = 0.03
9lon_threshold = 0.03
10
11class BaseModel(Model):
12 class Meta:
13 database = db
14
15class Record(BaseModel):
16 timestamp = DateTimeField(default=datetime.now)
17 latitude = FloatField()
18 longitude = FloatField()
19 aqi = IntegerField()
20 t_in = FloatField()
21 t_out = FloatField()
22 t_setpoint = FloatField()
23 fan_speed = IntegerField()
24 power = BooleanField()
25 auto = BooleanField()
26 co_in = FloatField()
27 co_out = FloatField()
28 no2_in = FloatField()
29 pm10_out = FloatField()
30 airflow = IntegerField()
31 aq_in = IntegerField()
32
33class AQI(BaseModel):
34 timestamp = DateTimeField(default=datetime.now)
35 value = IntegerField()
36
37def set_aqi(value: int):
38 try:
39 AQI.delete().execute()
40 except DoesNotExist:
41 pass
42 return AQI.create(value=value)
43
44def get_aqi_from_cache(latitude, longitude):
45 try:
46 temp = AQI.select().order_by(AQI.timestamp.desc()).get()
47 except DoesNotExist:
48 return None
49
50 if temp.latitude - latitude > lat_threshold:
51 return None
52
53 if temp.longitude - longitude > lon_threshold:
54 return None
55
56 delta = datetime.now() - temp.timestamp
57 if delta > api_interval:
58 return None
59
60 return temp
61
62def get_aqi(latitude, longitude):
63 aqi = get_aqi_from_cache(latitude, longitude)
64
65 if aqi is not None:
66 return aqi.value
67
68 return get_aqi_owm(latitude, longitude)
69
70db.connect()
71db.create_tables([Record])
72
73def getLatestRecord():
74 #User.select().order_by(User.id.desc()).get()
75 try:
76 return Record.select().order_by(Record.timestamp.desc()).get()
77 except DoesNotExist:
78 return None
79
80def addRecord(**info):
81 Record.create(**info)