summaryrefslogtreecommitdiff
path: root/api/routes/sensors.py
blob: e9a2107a2ee8d8b962491d00766586b892bb460e (plain)
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
from fastapi import APIRouter, HTTPException
from sqlalchemy import select
from ..database import SessionLocal
from ..models import SensorDevice, Station
from pydantic import BaseModel
from datetime import datetime

router = APIRouter(
    prefix='/sensors',
    tags=['sensors']
)

@router.get('/')
async def get_sensors():
    dc = {'sensors': []}
    session = SessionLocal()
    stmt = select(SensorDevice)
    devices = session.execute(stmt)
    for device in devices.scalars():
         dev = {
             'id': device.id,
             'name': device.name,
             'installation_date': device.installation_date,
             'station_id': device.station_id,
             'is_active': device.is_active
             }
         dc['sensors'].append(dev)
    dc['size'] = len(dc['sensors'])
    session.close()
    return dc

class PostSensor(BaseModel):
    name: str
    installation_date: int
    station_id: int

@router.post('/')
async def post_sensor(sensor: PostSensor):
    session = SessionLocal()
    station = session.get(Station, sensor.station_id)
    if not station:
        session.close()
        raise HTTPException(
            status_code=404,
            detail=f"Não existe estação com id {sensor.station_id}"
        )
    installation_date = datetime.fromtimestamp(sensor.installation_date)

    session.add(SensorDevice(name=sensor.name, installation_date=installation_date, station_id=sensor.station_id, is_active=True))
    session.commit()
    session.close()
    return {'msg': 'Sensor criado com sucesso.'}