update : 15.01.2025 1:12:13,80

This commit is contained in:
Sabron 2025-01-15 01:12:13 +07:00
parent 5bf6ae4de1
commit ef675193e5
6 changed files with 1042 additions and 0 deletions

View File

@ -24,6 +24,9 @@
<div class="row">
<div class="col-md-12">
<div class="card card-primary card-outline ">
<div class="card-header text-sm">
<a href="/gto/reports/">Отчеты</a>
</div>
<div class="card-body">
<div class="tab-content">
<div class="row">

View File

@ -0,0 +1,49 @@
{% extends "default.html" %}
{% load static %}
{% load mysettings %}
{% block header_link %}
{% endblock header_link %}
{% block content %}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Main content -->
<div class="invoice p-3 mb-3">
<!-- title row -->
<div class="row">
<div class="col-12">
<h4>
<i class="nav-icon fas fa-copy"></i> Отчеты
</h4>
</div>
<!-- /.col -->
</div>
<!-- info row -->
<div class="row ">
<div class="col-sm-4 invoice-col">
<a href="?name=reportspeed"><strong>Превышения скорости</strong></a>
<br><p style="font-size:12px;fon">Отчет показывает отметки с превышением скорости</p>
<a href="?name=reportskuv"><strong>Отчет по событиям</strong></a>
<br><p style="font-size:12px;fon">Отчет данные системы контроля усталости водителя</p>
</div>
<!--<div class="col-sm-4 invoice-col">
<a href=""><strong>Отчет колонка 3</strong></a>
<br><p style="font-size:12px;fon">Отчет </p>
</div>-->
<!-- /.col -->
</div>
</div>
<!-- /.invoice -->
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</section>
{% endblock %}
{% block script_footer %}
{% endblock script_footer %}

View File

@ -0,0 +1,176 @@
{% extends "default.html" %}
{% load static %}
{% load mysettings %}
{% block header_link %}
<link type="text/css" rel="stylesheet" href="{% static '/css/speedometer.css' %}?ver={% settings_value 'APP_VER' %}">
<!-- daterange picker -->
<link rel="stylesheet" href="{% static 'lte/plugins/daterangepicker/daterangepicker.css' %}?ver={% settings_value 'APP_VER' %}">
<!-- Select2 -->
<link rel="stylesheet" href="{% static 'lte/plugins/select2/css/select2.min.css' %}?ver={% settings_value 'APP_VER' %}">
<link rel="stylesheet" href="{% static 'lte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}?ver={% settings_value 'APP_VER' %}">
{% endblock header_link %}
{% block content %}
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 id="sensorname">Система контроля усталости водителя </h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="/gto/reports/">Главная</a></li>
<li class="breadcrumb-item active">Система контроля усталости водителя</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<section class="content">
<div class="containe col-sm-8">
<form class="form-horizontal">
{% csrf_token %}
<div id="card_param" class="card card-primary card-outline card-tabs">
<div class="card-header p-0 pt-1 border-bottom-0">
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="form-group row">
<label class="col-sm-2 col-form-label">Начальная дата:</label>
<div class="input-group date col-sm-4" id="datestart" data-target-input="nearest">
<input id="id_datestart" type="date" class="form-control datetimepicker-input" data-target="#datestart">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Конечная дата :</label>
<div class="input-group date col-sm-4" id="datestop" data-target-input="nearest">
<input id="id_datestop" type="date" class="form-control datetimepicker-input" data-target="#datestop">
</div>
</div>
</div>
<div class="card-footer">
<a type="button" onclick="reportshow()" class="btn btn-success">Сформировать</a>
<a type="button" onclick="cancel()" class="btn btn-default float-right">Закрыть</a>
</div> <!-- /.card -->
</div>
</form>
</div>
<div id="print_Panel" class="container-fluid" style="height:100px;">
<div id="reportPanel" class="card card-primary card-outline card-tabs">
<div id="reportPanelBody" class="card-body">
<div class="alert alert-warning alert-dismissible" style="max-width:450px;">
<!--<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>-->
<h5><i class="icon fas fa-exclamation-triangle"></i> </h5>
Отчет не сформирован. Нажмите "Сформировать" для получения отчета
</div>
</div>
<!-- /.card -->
</div>
</div>
</section>
{% endblock %}
{% block script_footer %}
<script src="{% static 'js/gauge.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<script src="{% static 'js/speedometer.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<!-- date-range-picker -->
<script src="{% static 'lte/plugins/daterangepicker/daterangepicker.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<script>
$(function () {
$('.date').datetimepicker({
locale: 'ru',
format: 'L',
format: 'DD.MM.YYYY',
autoclose: true,
});
});
function reportshow() {
var DataStart = $("#id_datestart").val();
var DataStop = $("#id_datestop").val();
if (DataStart.trim() == "") {
$("#id_datestart").css('border', "3px solid #80bdff").focus();
return false;
} else {
$("#id_datestart").css('border', "1px solid rgb(206, 212, 218)");
}
if (DataStop.trim() == "") {
$("#id_datestop").css('border', "3px solid #80bdff").focus();
return false;
} else {
$("#id_datestop").css('border', "1px solid rgb(206, 212, 218)");
}
if (!!DataStart) {
$("#reportPanelBody").html('<div class="overlay"><i class="fas fa-3x fa-sync-alt fa-spin"></i></div>')
$.ajax({
type: 'POST', // метод отправки
url: window.location.pathname + '?name=reportskuv',
async: true,
data: {
"DataStart": DataStart,
"DataStop": DataStop,
"metod": 'create',
},
success: function (data) {
$('#card_param').CardWidget('collapse')
document.getElementById('reportPanel').style.height = '';
$("#reportPanelBody").html(data); // при успешном получении ответа от сервера, заносим полученные данные в элемент с классом answer
$("#id_table").DataTable({
"language": {
"sZeroRecords": "Записи отсутствуют.",
},
"responsive": true,
"lengthChange": false,
"autoWidth": false,
"searching": false,
"paging": false,
"info": false,
"buttons": ["excel", "pdf", "print"],
}).buttons().container().appendTo('#id_table_wrapper .col-md-6:eq(0)');
},
error: function (dataerr) {
$("#reportPanelBody").html(dataerr); // при успешном получении ответа от сервера, заносим полученные данные в элемент с классом answer
},
timeout: 6000000 // sets timeout to 3 seconds
});
}
}
function cancel() {
document.location.href = "./";
}
function CallPrint(strid) {
var prtContent = document.getElementById(strid);
var WinPrint = window.open('', '', 'left=50,top=50,width=800,height=640,toolbar=0,scrollbars=1,status=0');
WinPrint.document.write('');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.write('');
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
prtContent.innerHTML = strOldOne;
}
</script>
{% endblock script_footer %}

View File

@ -4,6 +4,7 @@ from django.contrib.auth.decorators import login_required
from django.conf.urls import include # Используйте include() чтобы добавлять URL из каталога приложения
from apps.gto.views import views_main
from apps.gto.views import views_report
urlpatterns = [
url(r'^$', views_main.main_index, name='main_index'),
@ -12,5 +13,6 @@ urlpatterns = [
url(r'^object/sensor/$', views_main.sensor_edit, name='sensor_edit'),
url(r'^object/sensor/sensor_ajax/$', views_main.sensor_ajax, name='sensor_ajax'),
url(r'^update_object/$', views_main.update_object, name='update_object'),
url(r'^reports/$', views_report.report_list, name='report_list'),
]

410
apps/gto/views/FAR4AB2.tmp Normal file
View File

@ -0,0 +1,410 @@
import traceback
import requests
from datetime import datetime,timedelta
from requests.auth import HTTPBasicAuth
from django.conf import settings
from django.db.models import Q
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.db.models import Avg, Max, Min
from django.db.models.functions import (
TruncDate, TruncDay, TruncHour, TruncMinute, TruncSecond,Greatest,
)
from apps.util import generalmodule
from sabron.util import logging
def float_range(A, L=None, D=None):
#Use float number in range() function
# if L and D argument is null set A=0.0 and D = 1.0
if L == None:
L = A + 0.0
A = 0.0
if D == None:
D = 1.0
while True:
if D > 0 and A >= L:
break
elif D < 0 and A <= L:
break
yield ("%g" % A) # return float number
A = A + D
#end of function float_range()
@login_required(login_url='/accounts/login/?next=')
@never_cache
def show_report_error_ToHTML(request):
try:
dict_param=request.POST.dict()
data_start=datetime.strptime(dict_param['DataStart']+' 00:00:00', "%d.%m.%Y %H:%M:%S")
data_stop=datetime.strptime(dict_param['DataStop']+' 23:59:59', "%d.%m.%Y %H:%M:%S")
sensor = AcsSensor.objects.filter(id = dict_param['id_sensor']).first()
myquery =Q(sensor = sensor)
myquery &= Q(date_time__range=[data_start,data_stop])
myquery &= Q(value__range=[sensor.critical_value_from*sensor.ratio,99999999.0])
indicators_list = AcsIndicators.objects.filter(myquery).order_by('date_time').all()
html="""
<table id = 'id_table' class='table table-bordered table-striped'>
<thead>
<tr>
<th style='width: 15px'>№</th>
<th>Датчик</th>
<th>Дата</th>
<th style='width: 40px'>Показание</th>
</tr>
</thead>
<tbody>
"""
nom = 0
for indicators in indicators_list:
nom = nom +1
html = html+"""
<tr>
<td>"""+str(nom)+"""</td>
<td>"""+str(indicators.sensor)+"""</td>
<td>"""+indicators.date_time.strftime('%d.%m.%Y %H:%M')+"""</td>
"""
html = html+"""<td>"""+str(indicators.value/indicators.sensor.ratio)+""" """+str(indicators.sensor.unit)+"""</td></tr>"""
html = html+"""
</tbody>
</table>
"""
return HttpResponse(html, content_type='application/text')
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def show_report_value_ToHTML(request):
try:
dict_param=request.POST.dict()
data_start=datetime.strptime(dict_param['DataStart']+' 00:00:00', "%d.%m.%Y %H:%M:%S")
data_stop=datetime.strptime(dict_param['DataStop']+' 23:59:59', "%d.%m.%Y %H:%M:%S")
sensor = AcsSensor.objects.filter(id = dict_param['id_sensor']).first()
myquery =Q(sensor = sensor)
myquery &= Q(date_time__range=[data_start,data_stop])
#myquery &= Q(value__range=[sensor.critical_value_from,sensor.critical_value_to])
indicators_list = AcsIndicators.objects.filter(myquery).order_by('date_time').all()
html="""
<table id = 'id_table' class='table table-bordered'>
<thead>
<tr>
<th style='width: 15px'>№</th>
<th>Датчик</th>
<th>Дата</th>
<th style='width: 40px'>Показание</th>
</tr>
</thead>
<tbody>
"""
nom = 0
for indicators in indicators_list:
nom = nom +1
style = 'color:black;'
if float(indicators.value) >= float(sensor.critical_value_from*sensor.ratio) :
style = 'color:red;'
html = html+"""
<tr>
<td style="""+style+"""'>"""+str(nom)+"""</td>
<td style="""+style+"""'>"""+str(indicators.sensor)+"""</td>
<td style="""+style+"""'>"""+indicators.date_time.strftime('%d.%m.%Y %H:%M')+"""</td>
"""
html = html+"""<td style="""+style+"""'>"""+str(indicators.value/indicators.sensor.ratio)+""" """+str(indicators.sensor.unit)+"""</td></tr>"""
html = html+"""
</tbody>
</table>
"""
return HttpResponse(html, content_type='application/text')
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def show_report_alarm_ToHTML(request):
try:
dict_param=request.POST.dict()
data_start=datetime.strptime(dict_param['DataStart']+' 00:00:00', "%d.%m.%Y %H:%M:%S")
data_stop=datetime.strptime(dict_param['DataStop']+' 23:59:59', "%d.%m.%Y %H:%M:%S")
if dict_param['id_sensor']=='-1':
myquery =Q()
else:
sensor = AcsSensor.objects.filter(id = dict_param['id_sensor']).first()
myquery =Q(sensor = sensor)
myquery &= Q(date_time__range=[data_start,data_stop])
indicators_list = AcsAlarm.objects.filter(myquery).order_by('date_time').order_by('sensor').all().prefetch_related("sensor")
html="""
<table id = 'id_table' class='table table-bordered'>
<thead>
<tr>
<th style='width: 15px'>№</th>
<th>Дата</th>
<th>Датчик</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
"""
nom = 0
for indicators in indicators_list:
nom = nom +1
style = 'color:black;'
html = html+"""
<tr>
<td style="""+style+"""'>"""+str(nom)+"""</td>
<td style="""+style+"""'>"""+indicators.date_time.strftime('%d.%m.%Y %H:%M')+"""</td>
<td style="""+style+"""'>"""+str(indicators.sensor)+"""</td>
<td style="""+style+"""'>"""+str(indicators.text_alarm)+"""</td>
</tr>
"""
html = html+"""
</tbody>
</table>
<br>
<br>
<br>
"""
return HttpResponse(html, content_type='application/text')
except Exception as err:
logging.error(traceback.format_exc())
def get_ajax(request):
try:
if request.method == "POST":
param=request.GET.dict()
type = 0
myquery =Q(active=True)
if 'type' in param:
type = param['type']
myquery &= Q(type=type)
sensor_list = AcsSensor.objects.filter(myquery).all().order_by('name')
m_sensor = []
for sensor in sensor_list:
sensor_dict = dict()
sensor_dict.update(sensor_id=sensor.id)
sensor_dict.update(value=sensor.value / sensor.ratio)
sensor_dict.update(critical_value=sensor.critical_value)
sensor_dict.update(unit=sensor.unit)
pecent = ((sensor.value / sensor.ratio) * 100) / sensor.critical_value
sensor_dict.update(pecent_value=pecent)
#sensor.critical_value
#color=0 зеленый
#color=1 желтый
#color=2 красный
color = 'bg-success'
if sensor.critical_type == 'max':
if sensor.value / sensor.ratio >= sensor.critical_value:
color = 'bg-danger'
else:
if sensor.value / sensor.ratio <= sensor.critical_value:
color = 'bg-danger'
sensor_dict.update(color=color)
m_sensor.append(sensor_dict)
return generalmodule.ReturnJson(200,m_sensor)
except Exception as err:
logging.error(traceback.format_exc())
data = dict()
data.update(status=-1)
return generalmodule.ReturnJson(200,data)
def MainIndexDefault(request):
if request.method == "GET":
position_list = BlockSensor.objects.values('position').order_by('position').distinct()
i = 0
for position in position_list:
i =i+1
position_dict = dict()
position_dict.update(id = i)
position_dict.update(name = position['position'])
param=request.GET.dict()
type = 0
sensor_list = BlockSensor.objects.all().order_by('value').order_by('name')
m_sensor = []
for sensor in sensor_list:
str_value=str(sensor.value)
sensor_dict = dict()
sensor_dict.update(position=sensor.position)
sensor_dict.update(sensor=sensor)
sensor_dict.update(name=sensor.name)
sensor_dict.update(value=sensor.value)
sensor_dict.update(connect_time=sensor.connect_time)
sensor_dict.update(str_value=str_value)
m_sensor.append(sensor_dict)
context = {
'updatepage':True,
'sensor_list':sensor_list,
'm_sensor':m_sensor,
'type':int(type),
}
return render(request, 'block_main.html',context)
@login_required(login_url='/accounts/login/?next=')
@never_cache
def sensor_ajax(request):
try:
if request.method == "POST":
sensor_dict = dict()
param = request.POST.dict()
sensor = AcsSensor.objects.filter(id=param['id']).first()
critical_type = sensor.critical_type
connect_time = sensor.connect_time
value = sensor.value
end_date=sensor.connect_time
if param['sensor_type'] == 'sec':
strftime = "%H:%M:%S"
start_date = end_date - timedelta(seconds=30)
elif param['sensor_type'] == 'min':
strftime = "%H:%M"
start_date = end_date - timedelta(minutes=30)
else:
strftime = "%H:00"
start_date = end_date - timedelta(hours=30)
sensor_links = AcsIndicators.objects.filter(sensor=sensor).filter(date_time__range=[start_date,end_date]).order_by('date_time').order_by('id')
strftimeend = "%d.%m.%Y %H"
m_sensor = []
value_old = 0
for i in range(31):
if param['sensor_type'] == 'sec':
strftimeend = "%d.%m.%Y %H:%M:%S"
date_time = start_date + timedelta(seconds=i)
start_date_day = date_time
end_date_day = date_time+ timedelta(milliseconds=1000)
elif param['sensor_type'] == 'min':
strftimeend = "%d.%m.%Y %H:%M"
date_time = start_date + timedelta(minutes=i)
start_date_day = datetime(date_time.year, date_time.month, date_time.day,date_time.hour,date_time.minute,0)
end_date_day = datetime(date_time.year, date_time.month, date_time.day,date_time.hour,date_time.minute,59,9999)
else:
strftimeend = "%d.%m.%Y %H"
date_time = start_date + timedelta(hours=i)
start_date_day = datetime(date_time.year, date_time.month, date_time.day,date_time.hour,0,0)
end_date_day = datetime(date_time.year, date_time.month, date_time.day,date_time.hour,59,59,9999)
sensor_dict = dict()
sensor_dict.update(date_max=str(connect_time))
if critical_type =="max":
value_date =0
else:
value_date =9999999
result = sensor_links.filter(date_time__range=[start_date_day,end_date_day]).aggregate(Max('value'))
sensor_dict.update(date_time = date_time.strftime(strftime))
if result['value__max'] == None:
sensor_dict.update(value = value_old)
else:
value_old = result['value__max']/sensor.ratio
sensor_dict.update(value = result['value__max']/sensor.ratio)
m_sensor.append(sensor_dict)
return generalmodule.ReturnJson(200,m_sensor)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def report_error(request):
try:
if request.method == "GET":
sensor_list = AcsSensor.objects.all()
context = {
'sensor_list':sensor_list,
}
return render(request, 'report/repor_error.html',context)
if request.method == "POST":
dict_param=request.POST.dict()
if dict_param['metod']=='create':
return show_report_error_ToHTML(request)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def report_value(request):
try:
if request.method == "GET":
sensor_list = AcsSensor.objects.all()
context = {
'sensor_list':sensor_list,
}
return render(request, 'report/repor_value.html',context)
if request.method == "POST":
dict_param=request.POST.dict()
if dict_param['metod']=='create':
return show_report_value_ToHTML(request)
#elif dictParametr['metod']=='download':
# return ReportTableWorksToXLS(request)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def report_alarm(request):
try:
if request.method == "GET":
sensor_list = AcsSensor.objects.all()
alarm_element = AcsAlarm.objects.order_by('-date_time').first()
context = {
'sensor_list':sensor_list,
'alarm_element':alarm_element,
}
return render(request, 'report/repor_alarm.html',context)
if request.method == "POST":
dict_param=request.POST.dict()
if dict_param['metod']=='create':
return show_report_alarm_ToHTML(request)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def report_list(request):
try:
param=request.GET.dict()
if 'name' in param:
name = param['name']
if name == 'reporterror':
return report_error(request)
if name == 'reportvalue':
return report_value(request)
if name == 'reportalarm':
return report_alarm(request)
context = {
}
return render(request, 'gto_report_list.html',context)
except Exception as err:
logging.error(traceback.format_exc())

View File

@ -0,0 +1,402 @@
import traceback
import requests
from datetime import datetime,timedelta
from requests.auth import HTTPBasicAuth
from django.conf import settings
from django.db.models import Q
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.db.models import Avg, Max, Min
from django.db.models.functions import (
TruncDate, TruncDay, TruncHour, TruncMinute, TruncSecond,Greatest,
)
from apps.gto.models.model_alarm import GtoAlarm
from apps.util import generalmodule
from sabron.util import logging
def float_range(A, L=None, D=None):
#Use float number in range() function
# if L and D argument is null set A=0.0 and D = 1.0
if L == None:
L = A + 0.0
A = 0.0
if D == None:
D = 1.0
while True:
if D > 0 and A >= L:
break
elif D < 0 and A <= L:
break
yield ("%g" % A) # return float number
A = A + D
#end of function float_range()
@login_required(login_url='/accounts/login/?next=')
@never_cache
def show_report_error_ToHTML(request):
try:
dict_param=request.POST.dict()
data_start=datetime.strptime(dict_param['DataStart']+' 00:00:00', "%d.%m.%Y %H:%M:%S")
data_stop=datetime.strptime(dict_param['DataStop']+' 23:59:59', "%d.%m.%Y %H:%M:%S")
sensor = AcsSensor.objects.filter(id = dict_param['id_sensor']).first()
myquery =Q(sensor = sensor)
myquery &= Q(date_time__range=[data_start,data_stop])
myquery &= Q(value__range=[sensor.critical_value_from*sensor.ratio,99999999.0])
indicators_list = AcsIndicators.objects.filter(myquery).order_by('date_time').all()
html="""
<table id = 'id_table' class='table table-bordered table-striped'>
<thead>
<tr>
<th style='width: 15px'>№</th>
<th>Датчик</th>
<th>Дата</th>
<th style='width: 40px'>Показание</th>
</tr>
</thead>
<tbody>
"""
nom = 0
for indicators in indicators_list:
nom = nom +1
html = html+"""
<tr>
<td>"""+str(nom)+"""</td>
<td>"""+str(indicators.sensor)+"""</td>
<td>"""+indicators.date_time.strftime('%d.%m.%Y %H:%M')+"""</td>
"""
html = html+"""<td>"""+str(indicators.value/indicators.sensor.ratio)+""" """+str(indicators.sensor.unit)+"""</td></tr>"""
html = html+"""
</tbody>
</table>
"""
return HttpResponse(html, content_type='application/text')
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def show_report_value_ToHTML(request):
try:
dict_param=request.POST.dict()
data_start=datetime.strptime(dict_param['DataStart']+' 00:00:00', "%d.%m.%Y %H:%M:%S")
data_stop=datetime.strptime(dict_param['DataStop']+' 23:59:59', "%d.%m.%Y %H:%M:%S")
sensor = AcsSensor.objects.filter(id = dict_param['id_sensor']).first()
myquery =Q(sensor = sensor)
myquery &= Q(date_time__range=[data_start,data_stop])
#myquery &= Q(value__range=[sensor.critical_value_from,sensor.critical_value_to])
indicators_list = AcsIndicators.objects.filter(myquery).order_by('date_time').all()
html="""
<table id = 'id_table' class='table table-bordered'>
<thead>
<tr>
<th style='width: 15px'>№</th>
<th>Датчик</th>
<th>Дата</th>
<th style='width: 40px'>Показание</th>
</tr>
</thead>
<tbody>
"""
nom = 0
for indicators in indicators_list:
nom = nom +1
style = 'color:black;'
if float(indicators.value) >= float(sensor.critical_value_from*sensor.ratio) :
style = 'color:red;'
html = html+"""
<tr>
<td style="""+style+"""'>"""+str(nom)+"""</td>
<td style="""+style+"""'>"""+str(indicators.sensor)+"""</td>
<td style="""+style+"""'>"""+indicators.date_time.strftime('%d.%m.%Y %H:%M')+"""</td>
"""
html = html+"""<td style="""+style+"""'>"""+str(indicators.value/indicators.sensor.ratio)+""" """+str(indicators.sensor.unit)+"""</td></tr>"""
html = html+"""
</tbody>
</table>
"""
return HttpResponse(html, content_type='application/text')
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def show_report_alarm_ToHTML(request):
try:
dict_param=request.POST.dict()
print(dict_param)
#data_start=datetime.strptime(dict_param['DataStart']+' 00:00:00', "%d.%m.%Y %H:%M:%S")
#data_stop=datetime.strptime(dict_param['DataStop']+' 23:59:59', "%d.%m.%Y %H:%M:%S")
data_start=datetime.strptime(dict_param['DataStart']+' 00:00:00', "%Y-%m-%d %H:%M:%S")
data_stop=datetime.strptime(dict_param['DataStop']+' 23:59:59', "%Y-%m-%d %H:%M:%S")
myquery =Q()
myquery &= Q(time__range=[data_start,data_stop])
indicators_list = GtoAlarm.objects.filter(myquery).order_by('time').all().prefetch_related("equipment")
html="""
<table id = 'id_table' class='table table-bordered'>
<thead>
<tr>
<th style='width: 15px'>№</th>
<th>Дата</th>
<th>Объект</th>
<th>Тип события</th>
</tr>
</thead>
<tbody>
"""
nom = 0
for indicators in indicators_list:
nom = nom +1
style = 'color:black;'
html = html+"""
<tr>
<td style="""+style+"""'>"""+str(nom)+"""</td>
<td style="""+style+"""'>"""+indicators.time.strftime('%d.%m.%Y %H:%M')+"""</td>
<td style="""+style+"""'>"""+str(indicators.equipment)+"""</td>
<td style="""+style+"""'>"""+str(indicators.alarm_type)+"""</td>
</tr>
"""
html = html+"""
</tbody>
</table>
<br>
<br>
<br>
"""
return HttpResponse(html, content_type='application/text')
except Exception as err:
logging.error(traceback.format_exc())
def get_ajax(request):
try:
if request.method == "POST":
param=request.GET.dict()
type = 0
myquery =Q(active=True)
if 'type' in param:
type = param['type']
myquery &= Q(type=type)
sensor_list = AcsSensor.objects.filter(myquery).all().order_by('name')
m_sensor = []
for sensor in sensor_list:
sensor_dict = dict()
sensor_dict.update(sensor_id=sensor.id)
sensor_dict.update(value=sensor.value / sensor.ratio)
sensor_dict.update(critical_value=sensor.critical_value)
sensor_dict.update(unit=sensor.unit)
pecent = ((sensor.value / sensor.ratio) * 100) / sensor.critical_value
sensor_dict.update(pecent_value=pecent)
#sensor.critical_value
#color=0 зеленый
#color=1 желтый
#color=2 красный
color = 'bg-success'
if sensor.critical_type == 'max':
if sensor.value / sensor.ratio >= sensor.critical_value:
color = 'bg-danger'
else:
if sensor.value / sensor.ratio <= sensor.critical_value:
color = 'bg-danger'
sensor_dict.update(color=color)
m_sensor.append(sensor_dict)
return generalmodule.ReturnJson(200,m_sensor)
except Exception as err:
logging.error(traceback.format_exc())
data = dict()
data.update(status=-1)
return generalmodule.ReturnJson(200,data)
def MainIndexDefault(request):
if request.method == "GET":
position_list = BlockSensor.objects.values('position').order_by('position').distinct()
i = 0
for position in position_list:
i =i+1
position_dict = dict()
position_dict.update(id = i)
position_dict.update(name = position['position'])
param=request.GET.dict()
type = 0
sensor_list = BlockSensor.objects.all().order_by('value').order_by('name')
m_sensor = []
for sensor in sensor_list:
str_value=str(sensor.value)
sensor_dict = dict()
sensor_dict.update(position=sensor.position)
sensor_dict.update(sensor=sensor)
sensor_dict.update(name=sensor.name)
sensor_dict.update(value=sensor.value)
sensor_dict.update(connect_time=sensor.connect_time)
sensor_dict.update(str_value=str_value)
m_sensor.append(sensor_dict)
context = {
'updatepage':True,
'sensor_list':sensor_list,
'm_sensor':m_sensor,
'type':int(type),
}
return render(request, 'block_main.html',context)
@login_required(login_url='/accounts/login/?next=')
@never_cache
def sensor_ajax(request):
try:
if request.method == "POST":
sensor_dict = dict()
param = request.POST.dict()
sensor = AcsSensor.objects.filter(id=param['id']).first()
critical_type = sensor.critical_type
connect_time = sensor.connect_time
value = sensor.value
end_date=sensor.connect_time
if param['sensor_type'] == 'sec':
strftime = "%H:%M:%S"
start_date = end_date - timedelta(seconds=30)
elif param['sensor_type'] == 'min':
strftime = "%H:%M"
start_date = end_date - timedelta(minutes=30)
else:
strftime = "%H:00"
start_date = end_date - timedelta(hours=30)
sensor_links = AcsIndicators.objects.filter(sensor=sensor).filter(date_time__range=[start_date,end_date]).order_by('date_time').order_by('id')
strftimeend = "%d.%m.%Y %H"
m_sensor = []
value_old = 0
for i in range(31):
if param['sensor_type'] == 'sec':
strftimeend = "%d.%m.%Y %H:%M:%S"
date_time = start_date + timedelta(seconds=i)
start_date_day = date_time
end_date_day = date_time+ timedelta(milliseconds=1000)
elif param['sensor_type'] == 'min':
strftimeend = "%d.%m.%Y %H:%M"
date_time = start_date + timedelta(minutes=i)
start_date_day = datetime(date_time.year, date_time.month, date_time.day,date_time.hour,date_time.minute,0)
end_date_day = datetime(date_time.year, date_time.month, date_time.day,date_time.hour,date_time.minute,59,9999)
else:
strftimeend = "%d.%m.%Y %H"
date_time = start_date + timedelta(hours=i)
start_date_day = datetime(date_time.year, date_time.month, date_time.day,date_time.hour,0,0)
end_date_day = datetime(date_time.year, date_time.month, date_time.day,date_time.hour,59,59,9999)
sensor_dict = dict()
sensor_dict.update(date_max=str(connect_time))
if critical_type =="max":
value_date =0
else:
value_date =9999999
result = sensor_links.filter(date_time__range=[start_date_day,end_date_day]).aggregate(Max('value'))
sensor_dict.update(date_time = date_time.strftime(strftime))
if result['value__max'] == None:
sensor_dict.update(value = value_old)
else:
value_old = result['value__max']/sensor.ratio
sensor_dict.update(value = result['value__max']/sensor.ratio)
m_sensor.append(sensor_dict)
return generalmodule.ReturnJson(200,m_sensor)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def report_error(request):
try:
if request.method == "GET":
sensor_list = AcsSensor.objects.all()
context = {
'sensor_list':sensor_list,
}
return render(request, 'report/repor_error.html',context)
if request.method == "POST":
dict_param=request.POST.dict()
if dict_param['metod']=='create':
return show_report_error_ToHTML(request)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def report_value(request):
try:
if request.method == "GET":
sensor_list = AcsSensor.objects.all()
context = {
'sensor_list':sensor_list,
}
return render(request, 'report/repor_value.html',context)
if request.method == "POST":
dict_param=request.POST.dict()
if dict_param['metod']=='create':
return show_report_value_ToHTML(request)
#elif dictParametr['metod']=='download':
# return ReportTableWorksToXLS(request)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def report_alarm(request):
try:
if request.method == "GET":
context = generalmodule.get_context_template()
return render(request, 'report/repor_alarm.html',context)
if request.method == "POST":
dict_param=request.POST.dict()
if dict_param['metod']=='create':
return show_report_alarm_ToHTML(request)
except Exception as err:
logging.error(traceback.format_exc())
@login_required(login_url='/accounts/login/?next=')
@never_cache
def report_list(request):
try:
param=request.GET.dict()
if 'name' in param:
name = param['name']
if name == 'reporterror':
return report_error(request)
if name == 'reportvalue':
return report_value(request)
if name == 'reportskuv':
return report_alarm(request)
context = generalmodule.get_context_template()
return render(request, 'gto_report_list.html',context)
except Exception as err:
logging.error(traceback.format_exc())