Blame view

src/core/pyros_django/monitoring/views.py 5.42 KB
800f4279   Alexis Koralewski   Updating WeatherW...
1
from datetime import datetime
ae04c9dd   Patrick Maeght   __init__
2
from django.http import HttpResponse
3df2d31a   haribo   #3430 : dates are...
3
from django.shortcuts import render
800f4279   Alexis Koralewski   Updating WeatherW...
4
5
from common.models import AgentCmd, WeatherWatchHistory
from django.http import Http404
91232ca8   Alexis Koralewski   Adding export of ...
6
import json, csv
800f4279   Alexis Koralewski   Updating WeatherW...
7
from django.db.models import Q
91232ca8   Alexis Koralewski   Adding export of ...
8
from django.views.decorators.csrf import csrf_exempt
800f4279   Alexis Koralewski   Updating WeatherW...
9
from django.core import serializers
3df2d31a   haribo   #3430 : dates are...
10
11

# Create your views here.
ae04c9dd   Patrick Maeght   __init__
12

5c9a5545   Patrick Maeght   send others weath...
13

ae04c9dd   Patrick Maeght   __init__
14
def index(request):
b41fdcf9   Alexis Koralewski   fixing home redir...
15
16
    if request.user.is_authenticated:
        # return the initial view (the dashboard's one)
39bd6df6   Alexis Koralewski   Add menu page for...
17
        return render(request, 'monitoring/monitoring_index.html',{"base_template":"base.html"})                              
02d94ed3   Alexis Koralewski   Reworking UI of w...
18
    return render(request, 'monitoring/monitoring_index.html',{'USER_LEVEL': "Visitor", 'base_template' : "base.html"})                              
b41fdcf9   Alexis Koralewski   fixing home redir...
19

ae04c9dd   Patrick Maeght   __init__
20

5c9a5545   Patrick Maeght   send others weath...
21

800f4279   Alexis Koralewski   Updating WeatherW...
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
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
    })

ae04c9dd   Patrick Maeght   __init__
48
49
50
51
52
53
54
55
56
57
58
59
60
def weather_config(request):
    """ PM 20180926 prototype without database
        http://127.0.0.1:8000/dashboard/weather/config
        Moved to monitoring
    """
    try:
        # 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()
e2f16220   Patrick Maeght   weather config up...
61
        _struct = {"origin":plc_checker.origin, "sensors_table":plc_checker.sensors_table, "monitoring_names":list(plc_checker.monitoring_names.keys())}
ae04c9dd   Patrick Maeght   __init__
62
63
64
65
        # Return template with sensors list
        return render(request, 'dashboard/config_weather.html', {'weather_config' : _struct, 'base_template' : "base.html"})
    except Config.DoesNotExist:
        return render(request, 'dashboard/config_weather.html', {'weather_info' : None})
e68e2cea   Patrick Maeght   weather config up...
66
67
68
69
70
71
72
73
74


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"])
4475e3d4   Etienne Pallier   Commande bien env...
75
        cmd_name, cmd_args = request.GET["data"].split(" ", 1)
e970e46d   Patrick Maeght   weather config up...
76
        # ['nom', 'monitoring_name actuel', 'id(json path) du capteur', 'nouveau monitoring_name']
e2f16220   Patrick Maeght   weather config up...
77
        # <class 'list'>: ['monitor_name_switch', 'None', 'Came:/S/N_A5EM:/Power_input', 'Rain_boolean']
12086fdb   Patrick Maeght   weather config up...
78
79
        if "Error_code" in cmd_args:
            something = 5/0
8e15e893   Etienne Pallier   Renommé classes C...
80
        AgentCmd.send_command('Dashboard', 'AgentM', cmd_name, cmd_args)
ea7ad435   Patrick Maeght   weather config up...
81

4475e3d4   Etienne Pallier   Commande bien env...
82
        #TODO: Pour l'instant, on ne recupere pas encore ce retour
25c7f6db   Patrick Maeght   weather config up...
83

94b23031   Patrick Maeght   send others weath...
84
        return HttpResponse('{"update":"OK", "cmd_name":"' + cmd_name + '"}', content_type="application/json")
e68e2cea   Patrick Maeght   weather config up...
85
    except:
94b23031   Patrick Maeght   send others weath...
86
87
        return HttpResponse('{"update":"ERROR", "cmd_name":"' + cmd_name + '"}', content_type="application/json", status="500")

91232ca8   Alexis Koralewski   Adding export of ...
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

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.")