1
1
from datetime import datetime , timedelta , timezone
2
2
from typing import Generic , List , Optional , Type , TypeVar
3
3
4
+ from bson import Binary
4
5
from fastapi import APIRouter , Depends , HTTPException , Path , Query , Response , status
5
6
from fastapi_pagination .default import Page as BasePage
6
7
from fastapi_pagination .default import Params as BaseParams
22
23
from opensensor .db import get_open_sensor_db
23
24
from opensensor .users import (
24
25
User ,
25
- _record_data_point_to_ts_collection ,
26
26
auth ,
27
27
device_id_is_allowed_for_user ,
28
28
get_api_keys_by_device_id ,
@@ -46,6 +46,27 @@ class Page(BasePage[T], Generic[T]):
46
46
router = APIRouter ()
47
47
48
48
49
+ def _record_data_point_to_ts_collection (
50
+ collection ,
51
+ ts_column_name : str ,
52
+ device_metadata : DeviceMetadata ,
53
+ data_point ,
54
+ user : User = None ,
55
+ ):
56
+ metadata = device_metadata .dict ()
57
+ metadata .pop ("api_key" , None )
58
+ if user :
59
+ metadata ["user_id" ] = Binary .from_uuid (user .fief_user_id )
60
+ if hasattr (data_point , "unit" ):
61
+ metadata ["unit" ] = data_point .unit
62
+ data = {
63
+ "timestamp" : datetime .utcnow (),
64
+ "metadata" : metadata ,
65
+ ts_column_name : str (getattr (data_point , ts_column_name )),
66
+ }
67
+ collection .insert_one (data )
68
+
69
+
49
70
@router .post ("/rh/" , response_model = Humidity )
50
71
async def record_humidity (
51
72
device_metadata : DeviceMetadata ,
@@ -112,6 +133,17 @@ async def record_moisture_readings(
112
133
return Response (status_code = status .HTTP_201_CREATED )
113
134
114
135
136
+ @app .post ("/pH/" , response_model = PH )
137
+ async def record_ph (
138
+ device_metadata : DeviceMetadata ,
139
+ ph : PH ,
140
+ user : User = Depends (validate_device_metadata ),
141
+ ):
142
+ db = get_open_sensor_db ()
143
+ _record_data_point_to_ts_collection (db .pH , "pH" , device_metadata , ph , user )
144
+ return Response (status_code = status .HTTP_201_CREATED )
145
+
146
+
115
147
def get_collection_name (response_model : Type [T ]):
116
148
if hasattr (response_model , "collection_name" ):
117
149
return response_model .collection_name ()
@@ -246,17 +278,6 @@ async def historical_data_route(
246
278
return historical_data_route
247
279
248
280
249
- @app .post ("/pH/" , response_model = PH )
250
- async def record_ph (
251
- device_metadata : DeviceMetadata ,
252
- ph : PH ,
253
- user : User = Depends (validate_device_metadata ),
254
- ):
255
- db = get_open_sensor_db ()
256
- _record_data_point_to_ts_collection (db .pH , "pH" , device_metadata , ph , user )
257
- return Response (status_code = status .HTTP_201_CREATED )
258
-
259
-
260
281
router .add_api_route (
261
282
"/temp/{device_id}" ,
262
283
create_historical_data_route (Temperature ),
0 commit comments