all repos — iot-project @ d03d40d836de47ef3e661a2b2052bb97ffc452e7

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(default=0)
18    longitude = FloatField(default=0)
19    aqi = IntegerField(default=0)
20    t_in = FloatField(default=0)
21    t_out = FloatField(default=0)
22    t_setpoint = FloatField(default=0)
23    fan_speed = IntegerField(default=0)
24    power = BooleanField(default=False)
25    auto = BooleanField(default=False)
26    co_in = FloatField(default=0)
27    co_out = FloatField(default=0)
28    no2_in = FloatField(default=0)
29    pm10_out = FloatField(default=0)
30    airflow = IntegerField(default=0)
31    aq_in = IntegerField(default=0)
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, AQI])
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 addRecord()
79
80def addRecord(**info):
81    return Record.create(**info)