-
Notifications
You must be signed in to change notification settings - Fork 0
/
plant_monitoring.py
325 lines (252 loc) · 11.6 KB
/
plant_monitoring.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
from typing import Annotated, Union
from fastapi import HTTPException, status, APIRouter, Security
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel
import os
from dotenv import load_dotenv
import motor.motor_asyncio
from bson import ObjectId
from typing import List
from dotenv import load_dotenv
from datetime import datetime
from authentication import get_current_user
load_dotenv()
router = APIRouter()
MONGODB_URL = os.getenv("MONGODB_URL")
client = motor.motor_asyncio.AsyncIOMotorClient(MONGODB_URL)
db = client.plant_monitoring
# CLASSES
class Plant(BaseModel):
id: str
name: str
type: str
location: str
description: str
class CreatePlant(BaseModel):
_id: ObjectId
name: str
type: str
location: str
description: str
class SensorOutput(BaseModel):
id: str
plant_id: str
timestamp: datetime
temperature: float
soil_moisture: float
light_level: float
humidity: float
class CreateSensorOutput(BaseModel):
plant_id: str
temperature: float
soil_moisture: float
light_level: float
humidity: float
# MARK: START OF ENDPOINTS FOR PLANT MONITORING
# GET endpoint to retrieve all plants
@router.get("/GetPlants/", response_description="List all plants", response_model=List[Plant], tags=["Plant Monitoring"])
async def get_plants(current_user: dict = Security(get_current_user)):
roles = current_user.get("role", [])
if "plant_monitoring" not in roles and "admin" not in roles:
raise HTTPException(status_code=401, detail="You do not have access to send request to this endpoint.")
try:
# Use the aggregation framework to convert _id to string
pipeline = [
{
"$project": {
"id": {
"$toString": "$_id"
},
"name": 1,
"type": 1,
"location": 1,
"description": 1
}
}
]
# Apply the aggregation pipeline to the collection
plants_cursor: motor.motor_asyncio.AsyncIOMotorCollection = db["plants"].aggregate(
pipeline)
plants = await plants_cursor.to_list(length=None)
return plants
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# GET endpoint to get a plant
@router.get("/GetPlant", response_description="Get a plant", response_model=Plant, tags=["Plant Monitoring"])
async def get_plant(request_body: dict, current_user: dict = Security(get_current_user)):
roles = current_user.get("role", [])
if "plant_monitoring" not in roles and "admin" not in roles:
raise HTTPException(status_code=401, detail="You do not have access to send request to this endpoint.")
try:
# Use the aggregation framework to convert _id to string
plant_id = request_body.get("id")
# Ensure that the plant_id is provided in the request body
if not plant_id:
return Response(content="Plant ID not provided in the request body", status_code=status.HTTP_400_BAD_REQUEST)
# Convert the provided plant_id to an ObjectId
plant_object_id = ObjectId(plant_id)
pipeline = [
{
"$match": {
"_id": plant_object_id
}
},
{
"$project": {
"id": {
"$toString": "$_id"
},
"name": 1,
"type": 1,
"location": 1,
"description": 1
}
}
]
try:
plant = await db["plants"].aggregate(pipeline).next()
return plant
except:
return Response(content="Plant not found", status_code=status.HTTP_400_BAD_REQUEST)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# PUT endpoint to update a plant
@router.put("/UpdatePlant/", response_description="Update a plant by ID", response_model=Plant, tags=["Plant Monitoring"])
async def update_plant(updated_plant: Plant, current_user: dict = Security(get_current_user)):
roles = current_user.get("role", [])
if "plant_monitoring" not in roles and "admin" not in roles:
raise HTTPException(status_code=401, detail="You do not have access to send request to this endpoint.")
try:
plant_id = updated_plant.id
plant_object_id = ObjectId(plant_id)
existing_plant = await db["plants"].find_one({"_id": plant_object_id})
if existing_plant is None:
return Response(content="Plant not found", status_code=status.HTTP_400_BAD_REQUEST)
update_data = updated_plant.model_dump(exclude={"id"})
# Update the plant with the provided data
update_response = await db["plants"].update_one({"_id": plant_object_id}, {"$set": update_data})
update_details = {
"plant_id": plant_id,
"matchedCount": update_response.matched_count,
"modifiedCount": update_response.modified_count,
"upsertedId": str(update_response.upserted_id),
"acknowledged": update_response.acknowledged,
}
return JSONResponse(status_code=status.HTTP_201_CREATED, content=update_details)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# DELETE endpoint to delete a plant
@router.delete("/DeletePlant/", response_description="Delete a plant by ID", tags=["Plant Monitoring"])
async def delete_plant(request_body: dict, current_user: dict = Security(get_current_user)):
roles = current_user.get("role", [])
if "plant_monitoring" not in roles and "admin" not in roles:
raise HTTPException(status_code=401, detail="You do not have access to send request to this endpoint.")
try:
# Use the aggregation framework to convert _id to string
plant_id = request_body.get("id")
# Ensure that the plant_id is provided in the request body
if not plant_id:
return Response(content="Plant ID not provided in the request body", status_code=status.HTTP_400_BAD_REQUEST)
# Convert the provided plant_id to an ObjectId
plant_object_id = ObjectId(plant_id)
# Check if the plant with the provided ID exists
existing_plant = await db["plants"].find_one({"_id": plant_object_id})
if existing_plant is None:
return Response(content="Plant not found", status_code=status.HTTP_400_BAD_REQUEST)
# Delete the plant with the provided ID
delete_result = await db["plants"].delete_one({"_id": plant_object_id})
# Check if the deletion was successful
if delete_result.deleted_count == 1:
delete_details = {
"message": "Plant deleted successfully",
"plant_id": plant_id,
"acknowledged": delete_result.acknowledged,
"deletedCount": delete_result.deleted_count
}
return JSONResponse(status_code=status.HTTP_201_CREATED, content=delete_details)
else:
raise HTTPException(
status_code=500, detail="Failed to delete plant")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# POST endpoint to add a new plant
@router.post("/CreatePlant/", response_description="Add a new plant", response_model=CreatePlant, tags=["Plant Monitoring"])
async def create_plant(plant: CreatePlant, current_user: dict = Security(get_current_user)):
roles = current_user.get("role", [])
if "plant_monitoring" not in roles and "admin" not in roles:
raise HTTPException(status_code=401, detail="You do not have access to send request to this endpoint.")
try:
plant = jsonable_encoder(plant)
new_plant = await db["plants"].insert_one(plant)
return JSONResponse(status_code=status.HTTP_201_CREATED, content={"_id": str(new_plant.inserted_id)})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# END OF ENDPOINTS AND CLASSES FOR PLANT
# START OF ENDPOINTS AND CLASSES FOR SENSOR OUTPUT
# GET endpoint to retrieve all sensor outputs by a given plant ID
@router.get("/GetSensorOutputs/", response_description="List all Sensor Outputs By Plant ID", response_model=List[SensorOutput], tags=["Plant Monitoring"])
async def get_sensor_outputs(request_body: dict, current_user: dict = Security(get_current_user)):
roles = current_user.get("role", [])
if "plant_monitoring" not in roles and "admin" not in roles:
raise HTTPException(status_code=401, detail="You do not have access to send request to this endpoint.")
try:
# Use the aggregation framework to convert _id to string
plant_id = request_body.get("id")
# Ensure that the plant_id is provided in the request body
if not plant_id:
return Response(content="Plant ID not provided in the request body", status_code=status.HTTP_400_BAD_REQUEST)
# Convert the provided plant_id to an ObjectId
plant_object_id = ObjectId(plant_id)
# Use the aggregation framework to convert _id to string
pipeline = [
{
"$match": {
"plant_id": plant_object_id
}
},
{
"$project": {
"id": {
"$toString": "$_id"
},
"plant_id": {
"$toString": "$plant_id"
},
"timestamp": 1,
"temperature": 1,
"soil_moisture": 1,
"light_level": 1,
"humidity": 1
}
}
]
# Apply the aggregation pipeline to the collection
senor_outputs_cursor: motor.motor_asyncio.AsyncIOMotorCollection = db["sensor_outputs"].aggregate(
pipeline)
sensor_outputs = await senor_outputs_cursor.to_list(length=None)
if not sensor_outputs:
return Response(content="No sensor values found for the specified plant", status_code=status.HTTP_404_NOT_FOUND)
return sensor_outputs
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# POST endpoint to add a new plant
@router.post("/CreateSensorOutput/", response_description="Create a sensor output by a Plant ID", response_model=CreateSensorOutput, tags=["Plant Monitoring"])
async def create_sensor_output(sensor_output: CreateSensorOutput, current_user: dict = Security(get_current_user)):
roles = current_user.get("role", [])
if "plant_monitoring" not in roles and "admin" not in roles:
raise HTTPException(status_code=401, detail="You do not have access to send request to this endpoint.")
try:
plant_id = ObjectId(sensor_output.plant_id)
new_sensor_output_object = {
"plant_id": plant_id,
"timestamp": datetime.now().isoformat(),
"temperature": sensor_output.temperature,
"soil_moisture": sensor_output.soil_moisture,
"light_level": sensor_output.light_level,
"humidity": sensor_output.humidity
}
new_sensor_output = await db["sensor_outputs"].insert_one(new_sensor_output_object)
return JSONResponse(status_code=status.HTTP_201_CREATED, content={"_id": str(new_sensor_output.inserted_id)})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))