Blame view

src/core/pyros_django/monitoring/views.py 6.28 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
f958e3f4   Alexis Koralewski   Add new version o...
4
from common.models import AgentCmd, WeatherWatchHistory, SiteWatch
800f4279   Alexis Koralewski   Updating WeatherW...
5
from django.http import Http404
91232ca8   Alexis Koralewski   Adding export of ...
6
import json, csv
f958e3f4   Alexis Koralewski   Add new version o...
7
import os
800f4279   Alexis Koralewski   Updating WeatherW...
8
from django.db.models import Q
91232ca8   Alexis Koralewski   Adding export of ...
9
from django.views.decorators.csrf import csrf_exempt
800f4279   Alexis Koralewski   Updating WeatherW...
10
from django.core import serializers
f958e3f4   Alexis Koralewski   Add new version o...
11
from src.core.pyros_django.obsconfig.obsconfig_class import OBSConfig
3df2d31a   haribo   #3430 : dates are...
12
# Create your views here.
ae04c9dd   Patrick Maeght   __init__
13

5c9a5545   Patrick Maeght   send others weath...
14

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

ae04c9dd   Patrick Maeght   __init__
21

5c9a5545   Patrick Maeght   send others weath...
22

800f4279   Alexis Koralewski   Updating WeatherW...
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
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__
49
50
51
52
53
def weather_config(request):
    """ PM 20180926 prototype without database
        http://127.0.0.1:8000/dashboard/weather/config
        Moved to monitoring
    """
f958e3f4   Alexis Koralewski   Add new version o...
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    # 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})
e68e2cea   Patrick Maeght   weather config up...
72
73
74
75
76
77
78
79
80


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

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

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

91232ca8   Alexis Koralewski   Adding export of ...
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

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.")
f958e3f4   Alexis Koralewski   Add new version o...
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129


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())