views.py
12.8 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
import datetime
from common.models import Log, WeatherWatch, SiteWatch, ScientificProgram, Config, PyrosUser, PlcDeviceStatus
from django.core import serializers
import utils.Logger as l
from django.forms import modelformset_factory
from dashboard.forms import ConfigForm, UserForm
from dashboard.decorator import superuser_only
from django.views.generic.edit import UpdateView
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.urls import reverse_lazy, reverse
from django.http import Http404
import json
from random import randint
from devices.Telescope import TelescopeController
from devices.TelescopeRemoteControl import TelescopeRemoteControl
from django.core.mail import send_mail
import time
log = l.setupLogger("dashboard", "dashboard")
def index(request):
if request.user.is_authenticated:
return render(request, 'dashboard/index.html', {'level': request.user.user_level.priority, 'base_template' : "base.html", 'weather_img': "normal"}) # return the initial view (the dashboard's one)
return render(request, 'dashboard/index.html', {'level': 0, 'base_template' : "base_unlogged.html", 'weather_img': "red"}) # return the initial view (the dashboard's one)
#@login_required
#def observation_status(request):
# return render(request, 'dashboard/observation_status.html')
def retrieve_env(request):
'''
TODO: integrate Alain's code do determine day/night with sunelev and switch to utc time when the plc will use it
'''
try:
weather_status = WeatherWatch.objects.latest('updated')
plc_timeout = Config.objects.get(pk=1).plc_timeout_seconds
timeout = (datetime.datetime.now() - weather_status.updated).total_seconds()
timeout_affichage = datetime.datetime.now() - datetime.timedelta(seconds=timeout)
t = datetime.datetime.now() + datetime.timedelta(hours=-7) #temporary method to demonstrate the day/night display
isDay = False
if t.hour > 5 and t.hour < 20:
isDay = True
return render(request, 'dashboard/observation_status_env.html', locals())
except WeatherWatch.DoesNotExist:
raise Http404("No WeatherWatch matches the given query.")
def retrieve_env_navbar(request):
if request.is_ajax():
try:
weather_status = WeatherWatch.objects.latest('updated')
plc_mode = PlcDeviceStatus.objects.latest('created').plc_mode
is_safe = PlcDeviceStatus.objects.latest('created').is_safe
ack = Config.objects.get(id=1).ack
weather = serializers.serialize('json', [weather_status])
weather = json.loads(weather)
weather[0]['sunelev'] = randint(-30, 30) #remplacer par l'appel au code d'Alain quand il sera dispo
weather[0]["plc_mode"] = plc_mode
weather[0]["is_safe"] = is_safe
return HttpResponse(json.dumps(weather), content_type="application/json")
except WeatherWatch.DoesNotExist:
raise Http404("No WeatherWatch matches the given query.")
def retrieve_main_icon(request):
if request.is_ajax():
try:
weather_status = WeatherWatch.objects.latest('updated')
plc_mode = PlcDeviceStatus.objects.latest('created').plc_mode
weather = serializers.serialize('json', [weather_status])
weather = json.loads(weather)
weather[0]["plc_mode"] = plc_mode
weather[0]["ACK"] = ack
return HttpResponse(json.dumps(weather), content_type="application/json")
except WeatherWatch.DoesNotExist:
raise Http404("No WeatherWatch matches the given query.")
@login_required
def users(request):
instance = PyrosUser.objects.order_by("-id")
return render(request, 'dashboard/users_management.html', {'instance': instance}) # return the initial view (the users management's one)
@login_required
def routines(request):
url_ = reverse('admin:common_request_changelist')
return redirect(url_)
def weather(request):
if request.user.is_authenticated:
return render(request, 'dashboard/reload_weather.html', {'base_template' : "base.html"}) # return the needed html file
return render(request, 'dashboard/reload_weather.html', {'base_template' : "base_unlogged.html"})
def weather_current(request):
try:
if (len(Config.objects.all()) == 1):
monitoring = int(int(Config.objects.get(id=1).row_data_save_frequency) / 5)
else:
monitoring = 60
if (len(WeatherWatch.objects.all()) > 0):
weather_info = WeatherWatch.objects.order_by("-id")[:monitoring] # Use 300 seconds by default with an iteration every 5 seconds # Get the number of data available
else:
weather_info = None
return render(request, 'dashboard/current_weather.html', {'weather_info' : weather_info, 'iteration' : monitoring})
except Config.DoesNotExist:
return render(request, 'dashboard/current_weather.html', {'weather_info' : None, 'iteration' : 60})
def site(request):
if request.user.is_authenticated:
return render(request, 'dashboard/reload_site.html', {'base_template' : "base.html"}) # return the needed html file
return render(request, 'dashboard/reload_site.html', {'base_template' : "base_unlogged.html"}) # return the needed html file
def site_current(request):
try:
if (len(Config.objects.all()) == 1):
monitoring = int(int(Config.objects.get(id=1).row_data_save_frequency) / 5)
else:
monitoring = 60
if (len(SiteWatch.objects.all()) > 0):
site_info = SiteWatch.objects.order_by("-id")[:monitoring]
else:
site_info = None
return render(request, 'dashboard/current_site.html', {'site_info' : site_info, 'iteration' : monitoring})
except Config.DoesNotExist:
return render(request, 'dashboard/current_site.html', {'site_info' : None, 'iteration' : 60})
@login_required
def proposal(request):
if (len(ScientificProgram.objects.all()) > 0): # checking if the observatory table is empty
proposal_info = ScientificProgram.objects.order_by("-id")[:100] # Sorting Weather table
nb_info_proposal = len(proposal_info) # Get the number of data available
else: # if empty set everything to 0 / None (variables are checked in src/templates/scheduler/current_weather.html)
proposal_info = None
nb_info_proposal = 0
return render(request, 'dashboard/proposal.html', {'proposal_info' : proposal_info, 'nb_info_proposal' : nb_info_proposal})
@login_required
@superuser_only
def configUpdate(request):
instance = get_object_or_404(Config, id=1)
form = ConfigForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return redirect('../user_manager/profile')
return render(request, 'dashboard/configuration.html', {'form': form})
@login_required
def devices(request):
url_ = reverse('admin:common_device_changelist')
return redirect(url_)
@login_required
def system(request):
return render(request, 'dashboard/system.html')
@login_required
def system_retrieve_logs(request):
'''
Called by the dashboard system page with ajax request every seconds, to get the logs and print them
'''
if request.is_ajax():
alert_logs = Log.objects.filter(agent='Alert manager')
scheduler_logs = Log.objects.filter(agent='Scheduler')
majordome_logs = Log.objects.filter(agent='Majordome')
obs_logs = Log.objects.filter(agent='Observation manager')
analyzer_logs = Log.objects.filter(agent='Analyzer')
monitoring_logs = Log.objects.filter(agent='Monitoring')
return render(request, 'dashboard/system_logs.html', locals())
def schedule(request):
url_ = reverse('admin:common_schedule_changelist')
return redirect(url_)
@login_required
def quotas(request):
url_ = reverse('admin:common_pyrosuser_changelist')
return redirect(url_)
@login_required
def change_globalMode(request):
try :
config = get_object_or_404(Config, id=1)
config.global_mode = not config.global_mode
config.save()
return redirect('states')
except Config.DoesNotExist:
return redirect('states')
@login_required
def change_ack(request):
try :
config = get_object_or_404(Config, id=1)
config.ack = not config.ack
config.save()
return redirect('states')
except Config.DoesNotExist:
return redirect('states')
@login_required
def change_bypass(request):
try :
config = get_object_or_404(Config, id=1)
config.bypass = not config.bypass
config.save()
return redirect('states')
except Config.DoesNotExist:
return redirect('states')
@login_required
def change_activate(request, pk):
try :
user = get_object_or_404(PyrosUser, pk=pk)
user.is_active = not user.is_active
text_mail = ""
text_object = ""
if (user.first_time == False and user.is_active == True):
user.first_time = True
text_mail = "Hi,\n\nCongratulations, your registration has been approuved by the PI. Welcome to the Colibri Control Center.\n\nCordialy,\n\nColibri Control Center"
text_object = "[COLIBRI CC] Welcome"
elif (user.is_active == True):
text_mail = "Hi,\n\nYour account on the Colibri Control Center have been re-activated.\n\nCordialy,\n\nColibri Control Center"
text_object = "[COLIBRI CC] Re-activation"
else :
text_mail = "Hi,\n\nYour account on the Colibri Control Center have benn desactivated. Please contact the PI for futher information.\n\nCordialy,\n\nColibri Control Center"
text_object = "[COLIBRI CC] Desactivation"
user.save()
send_mail(text_object, text_mail, '', [user.email], fail_silently=False,)
return redirect('user-detail', pk=pk)
except PyrosUser.DoesNotExist:
return redirect('user-detail', pk=pk)
@login_required
def send_command_to_telescope(request):
return render(request, "dashboard/send_command_telescope.html")
@login_required
def submit_command_to_telescope(request):
if request.method == 'POST':
commands = [request.POST.get("comande"), request.POST.get("param1")]
try: #TODO faire un truc plus joli pour gérer les param
param2 = request.POST.get("param2")
if param2:
commands.append(param2)
except Exception:
pass
TelescopeRemoteControl(commands, False).exec_command()
return redirect('send_command_to_telescope')
@login_required
def submit_command_to_telescope_expert(request):
import os
if request.method == 'POST':
param = request.POST.get("commande_expert")
if param:
response = TelescopeRemoteControl(param, expert_mode=True).exec_command()
os.system("echo \"status :" + response + "\" >> /home/portos/IRAP/pyros/src/status")
return HttpResponse(json.dumps({'message': "Command send OK", 'response': response}))
return HttpResponse(json.dumps({'message': "Missing command data"}))
return redirect('submit_command_to_telescope')
@login_required
def user_detail_view(request,pk):
try:
user_id=PyrosUser.objects.get(pk=pk)
current_user = request.user
except PyrosUser.DoesNotExist:
raise Http404("User does not exist")
return render(request, 'dashboard/user_detail.html', context={'user' : user_id, 'current_user' : current_user, 'level': request.user.user_level.priority})
@login_required
def user_detail_edit(request,pk):
edit = get_object_or_404(PyrosUser, pk=pk)
form = UserForm(request.POST or None, instance=edit)
if form.is_valid():
form.save()
return redirect('user-detail', pk=pk)
return render(request, 'dashboard/user_detail_edit.html', {'form': form})
@login_required
def operator_state(request):
instance = get_object_or_404(Config, id=1)
return render(request, 'dashboard/operator_state.html', {'config' : instance})