from datetime import datetime from django.http import HttpResponse from django.shortcuts import render from common.models import AgentCmd, WeatherWatchHistory, SiteWatch from django.http import Http404 import json, csv import os from django.db.models import Q from django.views.decorators.csrf import csrf_exempt from django.core import serializers from src.core.pyros_django.obsconfig.obsconfig_class import OBSConfig # Create your views here. def index(request): if request.user.is_authenticated: # return the initial view (the dashboard's one) return render(request, 'monitoring/monitoring_index.html',{"base_template":"base.html"}) return render(request, 'monitoring/monitoring_index.html',{'USER_LEVEL': "Visitor", 'base_template' : "base.html"}) def get_weather_history_from_date(start_datetime:datetime, end_datetime:datetime): if WeatherWatchHistory.objects.all().exists(): weather_history_queryset = WeatherWatchHistory.objects.filter(Q(datetime__gte=start_datetime) & Q(datetime__lte=end_datetime)).order_by("datetime") weather = serializers.serialize('json', weather_history_queryset) return weather def weather_history(request): if request.GET: start_datetime = request.GET.get("start_datetime") end_datetime = request.GET.get("end_datetime") if start_datetime and end_datetime: start_datetime = datetime.strptime(start_datetime, "%d/%m/%Y %H:%M:%S") end_datetime = datetime.strptime(end_datetime, "%d/%m/%Y %H:%M:%S") try: weather_history = get_weather_history_from_date(start_datetime, end_datetime) #return HttpResponse(json.dumps(weather), content_type="application/json") return HttpResponse(weather_history, content_type="application/json") except WeatherWatchHistory.DoesNotExist: raise Http404("No WeatherWatchHistory matches the given query.") else: return HttpResponse(json.dumps({"result":"No required start and end datetime found in query"}), content_type="application/json") end_datetime =datetime.utcnow().strftime("%d/%m/%Y %H:%M:%S") return render(request,"monitoring/weather_history.html",{ "default_end_datetime" : end_datetime }) def weather_config(request): """ PM 20180926 prototype without database http://127.0.0.1:8000/dashboard/weather/config Moved to monitoring """ # Import PLC status sensor parser from monitoring.plc_checker import PlcChecker # Parse PLC status in colibri-new-fixed-2.json #colibri_json = open("../simulators/plc/colibri-new-fixed-2.json") #colibri_struct = json.load(colibri_json) #plc_status = colibri_struct["statuses"][1]["entities"][0] plc_checker = PlcChecker() _struct = {"origin":plc_checker.origin, "sensors_table":plc_checker.sensors_table, "monitoring_names":list(plc_checker.monitoring_names.keys())} config = OBSConfig( os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"]) monitoring_devices = config.get_monitoring_devices() devices = config.get_devices() devices_config = [] for device in monitoring_devices: device_config = devices[device] devices_config.append(device_config) # Return template with sensors list return render(request, 'dashboard/config_weather.html', {'weather_config' : _struct, 'base_template' : "base.html","devices_config":devices_config}) def weather_config_update(request): """ PM 20190716 ajax http://127.0.0.1:8000/dashboard/weather/config/update Get data... """ try: # print(request.GET["data"]) cmd_name, cmd_args = request.GET["data"].split(" ", 1) # ['nom', 'monitoring_name actuel', 'id(json path) du capteur', 'nouveau monitoring_name'] # : ['monitor_name_switch', 'None', 'Came:/S/N_A5EM:/Power_input', 'Rain_boolean'] if "Error_code" in cmd_args: something = 5/0 AgentCmd.send_command('Dashboard', 'AgentM', cmd_name, cmd_args) #TODO: Pour l'instant, on ne recupere pas encore ce retour return HttpResponse('{"update":"OK", "cmd_name":"' + cmd_name + '"}', content_type="application/json") except: return HttpResponse('{"update":"ERROR", "cmd_name":"' + cmd_name + '"}', content_type="application/json", status="500") def export_weather_data(request): if request.GET: start_datetime = request.GET.get("start_datetime") end_datetime = request.GET.get("end_datetime") if start_datetime and end_datetime: start_datetime = datetime.strptime(start_datetime, "%d/%m/%Y %H:%M:%S") end_datetime = datetime.strptime(end_datetime, "%d/%m/%Y %H:%M:%S") try: weather_history_queryset = WeatherWatchHistory.objects.filter(Q(datetime__gte=start_datetime) & Q(datetime__lte=end_datetime)).order_by("datetime") response = HttpResponse( content_type='text/csv', headers={f'Content-Disposition': 'attachment; filename="weather_history_{}_{}.csv"'.format(start_datetime,end_datetime)}, ) writer = csv.writer(response) writer.writerow(["datetime","humidity","wind","wind_dir","temperature","pressure","rain","cloud"]) for weather in weather_history_queryset: writer.writerow([weather.datetime,weather.humidity,weather.wind,weather.wind_dir,weather.temperature,weather.pressure,weather.rain,weather.cloud]) return response except WeatherWatchHistory.DoesNotExist: raise Http404("No WeatherWatchHistory matches the given query.") def internal_monitoring(request): current_internal_state, created = SiteWatch.objects.get_or_create(id=1) if not created: current_internal_state.setAttribute("InsideHumidity",0) current_internal_state.setAttribute("Pressure",1) current_internal_state.setAttribute("InsideTemp",19) current_internal_state.setAttribute("Roof_state","closed") current_internal_state.setAttribute("Power_input",1) current_internal_state.save() current_internal_state.setGlobalStatus() return render(request, "monitoring/internal_state.html", locals())