37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
# sensors/views.py
|
|
|
|
from django.http import JsonResponse
|
|
|
|
from .models import Sensor
|
|
|
|
|
|
def get_sensor_data(request, area_code, parameter_type):
|
|
try:
|
|
sensors = Sensor.objects.filter(area_code=area_code)
|
|
if not sensors.exists():
|
|
return JsonResponse({'error': 'No sensors found for this area code'}, status=404)
|
|
|
|
data_list = []
|
|
for sensor in sensors:
|
|
# 获取该传感器最新的指定参数的数据
|
|
data = sensor.data.filter(parameter_type=parameter_type).order_by('-timestamp').first()
|
|
if data:
|
|
data_list.append({
|
|
'sensor_uuid': str(sensor.uuid),
|
|
'value': float(data.value),
|
|
'timestamp': data.timestamp.isoformat()
|
|
})
|
|
|
|
if not data_list:
|
|
return JsonResponse({'error': f'No {parameter_type} data available for this area'}, status=404)
|
|
|
|
response = {
|
|
'area_code': area_code,
|
|
'parameter_type': parameter_type,
|
|
'sensors': data_list
|
|
}
|
|
|
|
return JsonResponse(response)
|
|
except Exception as e:
|
|
return JsonResponse({'error': str(e)}, status=500)
|