@@ -12,9 +12,29 @@ def __init__(self):
1212
1313 def receive_moisture_data (self , sensors : List [MoistureDataSchema ]):
1414 try :
15+ # Ensure the table exists
16+ self .cursor .execute ("""
17+ CREATE TABLE IF NOT EXISTS raw_sensors (
18+ id INTEGER NOT NULL,
19+ timestamp TIMESTAMP NOT NULL,
20+ sensor_id INTEGER NOT NULL,
21+ adc_value FLOAT NOT NULL,
22+ moisture_level FLOAT NOT NULL,
23+ digital_status VARCHAR(255) NOT NULL,
24+ weather_temp FLOAT,
25+ weather_humidity FLOAT,
26+ weather_sunlight FLOAT,
27+ weather_wind_speed FLOAT,
28+ location VARCHAR(255),
29+ weather_fetched TEXT,
30+ device_id VARCHAR(255) NOT NULL
31+ );
32+ """ )
33+ self .conn .commit ()
34+
1535 # Bulk insert query
1636 insert_query = """
17- INSERT INTO sensors (
37+ INSERT INTO raw_sensors (
1838 id, timestamp, sensor_id, adc_value, moisture_level, digital_status,
1939 weather_temp, weather_humidity, weather_sunlight, weather_wind_speed, location, weather_fetched, device_id
2040 ) VALUES %s RETURNING id;
@@ -28,11 +48,11 @@ def receive_moisture_data(self, sensors: List[MoistureDataSchema]):
2848 )
2949 for sensor in sensors
3050 ]
31- # Execute bulk insert
51+ # Execute bulk insert for sensors table
3252 psycopg2 .extras .execute_values (self .cursor , insert_query , values )
3353 self .conn .commit ()
3454
35- # Get the returned sensor_id
55+ # Get the returned id
3656 inserted_ids = [row [0 ] for row in self .cursor .fetchall ()]
3757 return {"status" : "success" , "inserted_ids" : inserted_ids }
3858
0 commit comments