diff --git a/.env b/.env
index 9d4911e..696b718 100644
--- a/.env
+++ b/.env
@@ -18,16 +18,18 @@ TZ=America/Lima
DOCKER_DATA=/data/dockers/radarsys/
LOCAL_IP=192.168.1.128
-# MQTT_SERVER=10.10.10.200
-MQTT_SERVER = 192.168.100.5
+MQTT_SERVER=10.10.10.200
+# MQTT_SERVER = 192.168.100.5
MQTT_PORT = 1883
MQTT_KEEPALIVE = 3660
-MQTT_USER_ATRAD=atrad
-MQTT_PASSWORD_ATRAD = atrad
+MQTT_USER_ATRAD=''
+MQTT_PASSWORD_ATRAD = ''
+MQTT_TOPIC_ATRAD_RECIEVE = "atrad/test4"
+
MQTT_USER = abs
MQTT_PASSWORD = abs
-MQTT_CLIENT_ID= abs_id
+
TOPIC_ABS=abs/beams
TOPIC_ABS_ACK=abs/beams_ack
TOPIC_ABS_CHANGE=abs/change_beam
diff --git a/.gitignore b/.gitignore
index c0aaafc..933ad78 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@ pipLibraries/
.env
remove_migrations.py
migrations/
+builder
diff --git a/apps/abs/models.py b/apps/abs/models.py
index a1c17f9..b88d9a0 100644
--- a/apps/abs/models.py
+++ b/apps/abs/models.py
@@ -339,7 +339,7 @@ class ABSConfiguration(Configuration):
try:
#self.write_device()
send_task('task_change_beam', [self.id],)
- print("*************************RUNNING ABS**************************",flush=True)
+ # print("*************************RUNNING ABS**************************",flush=True)
self.message = 'ABS running'
except Exception as e:
@@ -357,7 +357,6 @@ class ABSConfiguration(Configuration):
self.device.status = 2
self.device.save()
self.message = 'ABS has been stopped.'
- print("*************************STOPPED ABS**************************",flush=True)
self.save()
return True
@@ -379,7 +378,6 @@ class ABSConfiguration(Configuration):
This function sends the beams list to every abs module.
It needs 'module_conf' function
"""
- print("Write 3")
beams = ABSBeam.objects.filter(abs_conf=self)
nbeams = len(beams)
@@ -429,8 +427,6 @@ class ABSConfiguration(Configuration):
status = ['0'] * 64
n = 0
- print("Llega una antes entrar a multicast4")
-
sock = self.send_multicast(message)
while True:
@@ -453,7 +449,7 @@ class ABSConfiguration(Configuration):
sock.close()
else:
self.message = "ABS Configuration does not have beams"
- print('No beams')
+ # print('No beams')
#Start DDS-RC-JARS
if confdds:
confdds.start_device()
@@ -469,7 +465,7 @@ class ABSConfiguration(Configuration):
self.device.status = 0
self.module_status = ''.join(status)
self.save()
- print('Could not write ABS')
+ # print('Could not write ABS')
#Start DDS-RC-JARS
if confdds:
confdds.start_device()
@@ -493,12 +489,12 @@ class ABSConfiguration(Configuration):
if confjars:
confjars.start_device()
- print('Inicia intento de salvar device.status')
+ # print('Inicia intento de salvar device.status')
self.device.status = 3
self.module_status = ''.join(status)
#print(status)
self.save()
- print('Estatus salvado')
+ # print('Estatus salvado')
conf_active, __ = ABSActive.objects.get_or_create(pk=1)
conf_active.conf = self
conf_active.save()
diff --git a/apps/atrad/admin.py b/apps/atrad/admin.py
index 4e2323f..953f98f 100644
--- a/apps/atrad/admin.py
+++ b/apps/atrad/admin.py
@@ -1,6 +1,7 @@
from django.contrib import admin
-from .models import ATRADConfiguration
+from .models import ATRADConfiguration, ATRADData
# Register your models here.
admin.site.register(ATRADConfiguration)
+admin.site.register(ATRADData)
\ No newline at end of file
diff --git a/apps/atrad/forms.py b/apps/atrad/forms.py
index 7929874..e3c95eb 100644
--- a/apps/atrad/forms.py
+++ b/apps/atrad/forms.py
@@ -24,4 +24,4 @@ class ATRADConfigurationForm(forms.ModelForm):
class UploadFileForm(forms.Form):
title = forms.CharField(label='Extension Type', widget=forms.TextInput(attrs={'readonly':'readonly'}))
- file = forms.FileField()
+ file = forms.FileField()
\ No newline at end of file
diff --git a/apps/atrad/models.py b/apps/atrad/models.py
index 8157708..8864f76 100644
--- a/apps/atrad/models.py
+++ b/apps/atrad/models.py
@@ -5,16 +5,49 @@ from django.core.validators import MinValueValidator, MaxValueValidator
from .files import read_json_file
import requests
-# Create your models here. validators=[MinValueValidator(62.5e6), MaxValueValidator(450e6)]
-class ATRADConfiguration(Configuration):
+class ATRADData(models.Model):
+ datetime = models.DateTimeField()
+
+ nstx = models.SmallIntegerField()
+ status = models.SmallIntegerField()
+ temp_cll = models.SmallIntegerField()
+ nboards = models.SmallIntegerField()
+
+ tempdvr = models.SmallIntegerField()
+ potincdvr = models.SmallIntegerField()
+ potretdvr = models.SmallIntegerField()
+
+ temp1 = models.SmallIntegerField()
+ potinc1 = models.SmallIntegerField()
+ potret1 = models.SmallIntegerField()
+ temp2 = models.SmallIntegerField()
+ potinc2 = models.SmallIntegerField()
+ potret2 = models.SmallIntegerField()
+ temp3 = models.SmallIntegerField()
+ potinc3 = models.SmallIntegerField()
+ potret3 = models.SmallIntegerField()
+ temp4 = models.SmallIntegerField()
+ potinc4 = models.SmallIntegerField()
+ potret4 = models.SmallIntegerField()
+ temp5 = models.SmallIntegerField()
+ potinc5 = models.SmallIntegerField()
+ potret5 = models.SmallIntegerField()
+ temp6 = models.SmallIntegerField()
+ potinc6 = models.SmallIntegerField()
+ potret6 = models.SmallIntegerField()
- topic = models.PositiveIntegerField(verbose_name='Topic',validators=[MaxValueValidator(10)], default = 0)
- def verify_frequencies(self):
- return True
+ class Meta:
+ db_table = 'atrad_datas'
+
+ def __unicode__(self):
+ return u'%s' % (self.name)
+class ATRADConfiguration(Configuration):
+
+ topic = models.PositiveIntegerField(verbose_name='Topic',validators=[MaxValueValidator(10)], default = 0)
def status_device(self):
diff --git a/apps/atrad/mqtt.py b/apps/atrad/mqtt.py
index 050242e..6d6903c 100644
--- a/apps/atrad/mqtt.py
+++ b/apps/atrad/mqtt.py
@@ -1,39 +1,105 @@
-import os
import paho.mqtt.client as mqtt
from radarsys import settings
from radarsys.socketconfig import sio as sio
import numpy as np
+import psycopg2
+import os
+
+def insert(time,data):
+ sql = """INSERT INTO atrad_datas(
+ datetime,nstx,status,temp_cll,nboards,tempdvr,potincdvr,potretdvr,
+ temp1,potinc1,potret1,temp2,potinc2,potret2,temp3,potinc3,potret3,
+ temp4,potinc4,potret4,temp5,potinc5,potret5,temp6,potinc6,potret6)
+ VALUES(%s,%s,%s,%s,%s,%s,%s,%s,
+ %s,%s,%s,%s,%s,%s,%s,%s,%s,
+ %s,%s,%s,%s,%s,%s,%s,%s,%s);"""
+ try:
+ # connect to the PostgreSQL database
+ conn = psycopg2.connect(database="radarsys", user='docker', password='docker', host='radarsys-postgres', port= '5432')
+ # create a new cursor
+ cur = conn.cursor()
+ # execute the INSERT statement
+ #data_tuple = [tuple(i[:]) for i in a]
+ values = (time,) + tuple(data[0][:25])
+ cur.execute(sql, values)
+
+ # get the generated id back
+ #vendor_id = cur.fetchone()[0]
+
+ # commit the changes to the database
+ conn.commit()
+ # close communication with the database
+ cur.close()
+ except (Exception, psycopg2.DatabaseError) as error:
+ print(error)
+ finally:
+ if conn is not None:
+ conn.close()
+
+def maxTemperature(trs):
+ temps = GetTemperatures(trs)
+ maxT_STX = [max(i) for i in temps]
+ maxT = max(maxT_STX)
+ STXnum = maxT_STX.index(maxT)
+ STXloc = temps[STXnum].index(maxT)
+ maxT_loc = 'Amp ' + str(STXnum+1)
+
+ if STXloc == 0:
+ maxT_loc = maxT_loc + " Controller"
+ elif STXloc<7:
+ maxT_loc = maxT_loc + " PA " + str(STXloc+1)
+ else:
+ maxT_loc = maxT_loc + " Combiners"
+
+ return maxT,maxT_loc,temps
+
+def dataConvert(msg):
+ msgStr = str(msg.payload)
+ msgClean = [i for i in msgStr[21:-1].split("*")]
+ dataSTX = [[],[],[],[]]
+ for trs,i in zip(msgClean,[0,1,2,3]) :
+ dataSTX[i]= [int(i) for i in trs[1:-1].split(",")]
+ # Data to database
+ insert(msgStr[2:21],dataSTX)
+ # Data to send by socket
+ id_STX = dataSTX[0][0] // 4
+ status = ''.join([msgClean[i][3] for i in [0,1,2,3]])
+ powers = [dataSTX[0][34],dataSTX[0][36],dataSTX[2][32],dataSTX[2][34]]
+ tmax,index,tempData = maxTemperature(dataSTX)
+ #Json to send
+ data = {'time':msgStr[2:21],'num':id_STX,'pow':powers,'tmax':[str(tmax),index],'status':status}
+ data_temp = {'time':msgStr[2:21],'temp':tempData}
+ return data, data_temp
+
+def GetTemperatures(data):
+ np_data = [np.array(i) for i in data]
+ temps = [i[i<40] for i in np_data]
+ return [i[i>15].tolist() for i in temps]
def on_connect(mqtt_client, userdata, flags, rc):
if rc == 0:
- # print('Connected successfully')
- mqtt_client.subscribe('atrad/test3')
+ print('Connected successfullyasdss')
+ mqtt_client.subscribe("atrad/test4")
+ print("Exito")
else:
print('Bad connection. Code:', rc)
-def maxima_temp(trs):
- np_array = [np.array(i) for i in trs]
- temps = [max(i[i<40]) for i in np_array]
- return max(temps)
-
def on_message(mqtt_client, userdata, msg):
- # print(f'Received message on topic: {msg.topic} with payload: {msg.payload}', flush=True)
- trsi = [[],[],[],[]]
- mensaje = str(msg.payload)
- datos = [i for i in mensaje[21:-1].split("*")]
- status=''.join([datos[i][3] for i in range(3)])
- for trs,i in zip(datos,[0,1,2,3]) :
- trsi[i]= [int(i) for i in trs[1:-1].split(",")]
- potencias = [trsi[0][34],trsi[0][36],trsi[2][32],trsi[2][34]]
- tmax = maxima_temp(trsi)
- sio.emit('test', data={'time':mensaje[2:21],'num':trsi[0][0],'pow':potencias,'tmax':str(tmax),'status':status})
+ print('Received message on topic: {} with payload: {}'.format(msg.topic,msg.payload), flush=True)
+ mainData, tempData = dataConvert(msg)
+ # print("Recibi : {}".format(msg.payload),flush=True)
+ #socket fot general data
+ sio.emit('test',data = mainData)
+ print(mainData)
+ #socket for temperature details
+ sio.emit('temptx'+str(mainData['num'] + 1),data = tempData)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
-client.username_pw_set(os.environ.get('MQTT_USER_ATRAD', 'atrad'), os.environ.get('MQTT_PASSWORD_ATRAD', 'atrad'))
+client.username_pw_set( '','')
client.connect(
host=os.environ.get('MQTT_SERVER', '10.10.10.200'),
port=int(settings.os.environ.get('MQTT_PORT', 1883)),
- keepalive=int(os.environ.get('MQTT_KEEPALIVE', 36000))
+ keepalive=int(os.environ.get('MQTT_KEEPALIVE', 60))
)
\ No newline at end of file
diff --git a/apps/atrad/templates/atrad_conf.html b/apps/atrad/templates/atrad_conf.html
index 0cb7d14..a5f12f9 100644
--- a/apps/atrad/templates/atrad_conf.html
+++ b/apps/atrad/templates/atrad_conf.html
@@ -1,4 +1,5 @@
{% extends "dev_conf.html" %}
+{% load static %}
{% block extra-head %}
+
{% endblock %}
-{% block extra-content %}
+{% block content-graph %}
-
+
ATRAD Monitoring
-
-
-
-
-
+
+
+
+
+
Control
+
+
+
+ Tx1 |
+
+
+
+ |
+
+
+ Tx2 |
+
+
+
+ |
+
+
+
-
-
-
-
Status
-
-
-
+
+
+
+
+
+
+
+
Status
+
Tx1 |
|
- Sin envio de datos |
+ No data |
Tx2 |
|
- Sin envio de datos |
+ No data |
+
+
+
+
+
+
+
+
High Temperature Alerts
+
+
+
+
Power Alerts
+ Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempora quisquam cupiditate sunt eaque distinctio explicabo aliquam blanditiis illo eligendi eveniet culpa, vel laboriosam! Facilis dolores assumenda autem. Maiores, quibusdam eum.
+
+
-
-
-
-
-
-
Temperatura
-
-
-
-
-
+
+
+
+
+
Power graph
+
+
+
+
+
+
+
+ # Tx |
+ Power (kW) |
+
+
+ 1 |
+ |
+
+
+ 2 |
+ |
+
+
+
+
+
+
+
-
-
-
-
-
-
-
Control
-
-
-
-
-
-
+
+
-
-
-
-
-
- P1 |
- e |
- e |
-
-
- P2 |
- e |
- e |
-
-
- P3 |
- e |
- e |
-
-
- P4 |
- e |
- e |
-
-
-
+
+
+
+
+
+
+ # Amp |
+ Potencia (kW) |
+
+
+ P1 |
+ |
+
+
+ P2 |
+ |
+
+
+ P3 |
+ |
+
+
+ P4 |
+ |
+
+
+
+
-
-
+
+
-
-
+
+
+
+
+
+
+ # Amp |
+ Potencia (kW) |
+
+
+ P1 |
+ |
+
+
+ P2 |
+ |
+
+
+ P3 |
+ |
+
+
+ P4 |
+ |
+
+
+
+
-
+
{% endblock %}
\ No newline at end of file
diff --git a/apps/atrad/templates/atrad_tx.html b/apps/atrad/templates/atrad_tx.html
new file mode 100644
index 0000000..4b6fa99
--- /dev/null
+++ b/apps/atrad/templates/atrad_tx.html
@@ -0,0 +1,136 @@
+{% extends "base.html" %}
+{% load static %}
+{% block title %}ATRAD Tx{{id_tx}} Temperatures{% endblock %}
+{% block content-title %}{{title}}{% endblock %}
+{% block content-suptitle %}Tx {{id_tx}}{% endblock %}
+
+{% block extra-head %}
+
+{% endblock %}
+
+{% block content-graph %}
+
+
+
+
+
+
+
+
+
+
Controllers and combiners
+
+
+
+
+
+
+
+{% endblock %}
\ No newline at end of file
diff --git a/apps/atrad/templates/prueba.html b/apps/atrad/templates/prueba.html
new file mode 100644
index 0000000..19750d5
--- /dev/null
+++ b/apps/atrad/templates/prueba.html
@@ -0,0 +1,28 @@
+{% extends "dev_conf.html" %}
+{% load static %}
+
+
+{% block content-graph %}
+
+
The queryset object:
+{{ mymembers }}
+
+
Last time {{last}}
+
+
+
+
+ {% for key in keys %}
+ {{key}} |
+ {% endfor %}
+
+ {% for data in temps %}
+
+ {% for key in keys %}
+ {{data|attr:key }} |
+ {% endfor %}
+
+ {% endfor %}
+
+{% endblock %}
+
diff --git a/apps/atrad/urls.py b/apps/atrad/urls.py
index 2774385..bc97e12 100644
--- a/apps/atrad/urls.py
+++ b/apps/atrad/urls.py
@@ -3,6 +3,8 @@ from django.urls import path
from . import views
urlpatterns = (
+ path('prueba/', views.atrad_prueba, name='url_prueba'),
path('
/', views.atrad_conf, name='url_atrad_conf'),
path('/edit/', views.atrad_conf_edit, name='url_edit_atrad_conf'),
+ path('//', views.atrad_tx, name='url_tx_atrad'),
)
\ No newline at end of file
diff --git a/apps/atrad/views.py b/apps/atrad/views.py
index 80c6355..a65da20 100644
--- a/apps/atrad/views.py
+++ b/apps/atrad/views.py
@@ -1,9 +1,10 @@
from django.shortcuts import redirect, render, get_object_or_404
from django.contrib import messages
from django.http import HttpResponse
+from django.template.loader import get_template
from apps.main.models import Experiment
-from .models import ATRADConfiguration
+from .models import ATRADConfiguration, ATRADData
from .forms import ATRADConfigurationForm, UploadFileForm
from apps.main.views import sidebar
@@ -15,7 +16,7 @@ import os
from django.http import JsonResponse
from .mqtt import client as mqtt_client
from radarsys.socketconfig import sio as sio
-
+from datetime import timedelta
def atrad_conf(request, id_conf):
@@ -38,12 +39,27 @@ def atrad_conf(request, id_conf):
kwargs['button'] = 'Edit Configuration'
#kwargs['no_play'] = True
-
###### SIDEBAR ######
kwargs.update(sidebar(conf=conf))
return render(request, 'atrad_conf.html', kwargs)
+def atrad_tx(request, id_conf, id_tx):
+ kwargs = {}
+ kwargs['id_tx'] = id_tx[-1]
+ kwargs['keys'] = ['id','temp1','temp2','temp3','temp4','temp5','temp6']
+ kwargs['title'] = 'Temperature Details'
+ kwargs['button'] = 'Edit Configuration'
+ time = ATRADData.objects.last().datetime
+ mydata = ATRADData.objects.filter(datetime__gte = (time-timedelta(minutes=20)),nstx=1).values_list('datetime','temp1','temp2','temp3','temp4','temp5','temp6')
+ kwargs['data'] = QuerytoStr(mydata)
+ return render(request, 'atrad_tx.html', kwargs)
+
+def QuerytoStr(data):
+ time = data[0]
+ strdata = str(time)
+ return strdata
+
def atrad_conf_edit(request, id_conf):
conf = get_object_or_404(ATRADConfiguration, pk=id_conf)
@@ -72,9 +88,6 @@ def atrad_conf_edit(request, id_conf):
return render(request, 'atrad_conf_edit.html', kwargs)
-import os
-from django.http import HttpResponse#
-
def publish_message(request):
rc, mid = mqtt_client.publish('test/data2',1)
return JsonResponse({'code1': 'HIKA', 'code2': 'LUCAS'})
@@ -83,9 +96,17 @@ def monitor(request):
kwargs = {'no_sidebar': True}
return render(request, 'monitor.html', kwargs)
-def prueba(request):
- kwargs = {'no_sidebar': True}
- return render(request, 'prueba.html', kwargs)
+def atrad_prueba(request):
+ keys = ['id','temp1','temp2','temp3','temp4','temp5','temp6']
+ time = ATRADData.objects.last().datetime
+ mydata = ATRADData.objects.filter(datetime__gte = (time-timedelta(hours=1))).values('id','temp1','temp2','temp3','temp4','temp5','temp6')
+ template = get_template('prueba.html')
+ context = {
+ 'last' : time,
+ 'temps': mydata,
+ 'keys' : keys,
+ }
+ return HttpResponse(template.render(context, request))
@sio.on('connection-bind')
def atrad_connection_bind(sid, data):
@@ -97,12 +118,4 @@ def atrad_disconnect(sid):
@sio.event
def atrad_control_event(sid,message):
- mqtt_client.publish('test/data2',message['data'])
-
-def hello(data):
- try:
- rc, mid = mqtt_client.publish('test/data2', 'Hello')
- sio.emit('test', data={'topic':mid, 'status': 'Not Running'})
- except:
- print('ERROR', flush=True)
- return HttpResponse("Hello")
\ No newline at end of file
+ mqtt_client.publish('test/data2', json.dumps(message))
diff --git a/apps/jars/models.py b/apps/jars/models.py
index a253208..663a083 100644
--- a/apps/jars/models.py
+++ b/apps/jars/models.py
@@ -291,7 +291,6 @@ class JARSConfiguration(Configuration):
self.device.status = payload['status']
self.device.save()
self.message = payload['message']
- print("------STOP JARS------",flush=True)
except Exception as e:
self.device.status = 0
self.message = str(e)
@@ -318,11 +317,8 @@ class JARSConfiguration(Configuration):
if self.device.status == 3:
self.message = 'Could not configure device. Software Acquisition is running'
+ print('Could not configure device. Software Acquisition is running')
return False
-
- print("------ JARS WRITING ------",flush=True)
- self.device.status = 5 #Busy
- print("STATUS:", self.device.status,flush=True)
data = self.experiment.parms_to_dict()
#print(data)
@@ -349,14 +345,12 @@ class JARSConfiguration(Configuration):
self.device.save()
if self.device.status == 1:
return False
- print("------ JARS WRITED ------",flush=True)
except Exception as e:
self.device.status = 0
self.message = str(e)
self.device.save()
return False
- print("FINAL STATUS:", self.device.status,flush=True)
return True
def start_device(self):
@@ -375,7 +369,6 @@ class JARSConfiguration(Configuration):
self.message = str(e)
self.device.save()
return False
- print("------START JARS------",flush=True)
return True
def get_log(self):
diff --git a/apps/main/management/commands/hello.py b/apps/main/management/commands/hello.py
index 8c96945..037f444 100644
--- a/apps/main/management/commands/hello.py
+++ b/apps/main/management/commands/hello.py
@@ -12,7 +12,7 @@ from apps.main.models import Experiment, Configuration
class Command(BaseCommand):
"""
- Restart experiment every night at 05:00 am.
+ Restart experiment_number every night at 05:00 am.
Example:
manage.py restart_experiment
"""
@@ -35,13 +35,38 @@ class Command(BaseCommand):
else:
radar=campaign.get_experiments_by_radar(radar=None)
- radar_id=radar[0]["id"]
- if campaign.experiments.all()[0].status !=1:
- print(campaign.name, "\t\t Stopping Campaign...")
- a=radar_stop_scheduler(campaign.id,radar_id,campaign.experiments.all()[0].id)
- print("New Status: ", a)
- else:
- print(campaign.name,"\t\t\t Campaign already stooped")
+ # print(campaign.name)
+ for rad in radar:
+ radar_id=rad["id"]
+ # print(radar_id, " ", rad["name"])
+ for exp in range(len(rad["experiments"])):
+ experiment=rad["experiments"][exp]
+ experiment_id= experiment.id
+ if experiment.status!=1:
+ print("Stopping Campaign {}, located on {}, the experiment {} with ID {}".format(campaign.name,rad["name"],experiment.name,experiment.id))
+ status=radar_stop_scheduler(campaign.id,radar_id,experiment.id)
+ if status == 0:
+ print("ERROR, status= {}".format(status))
+ # print("New Status: ", status)
+ else:
+ print("{} Experiment of the Campaign {} already stooped".format(experiment.name,campaign.name))
+ print("\n")
+
+ # radar_id=radar[0]["id"]
+ # if campaign.experiments.all()[0].status !=1:
+ # print(campaign.name, "\t\t Stopping Campaign...")
+ # a=radar_stop_scheduler(campaign.id,radar_id,campaign.experiments.all()[0].id)
+ # print("New Status: ", a)
+ # else:
+ # print(campaign.name,"\t\t\t Campaign already stooped")
+
+
+# EXP_STATES = (
+# (0,'Error'), #RED
+# (1,'Cancelled'), #YELLOW
+# (2,'Running'), #GREEN
+# (3,'Scheduled'), #BLUE
+# (4,'Unknown'), #WHITE
def radar_write_start_scheduler(id_camp,id_radar):
campaign = get_object_or_404(Campaign, pk=id_camp)
@@ -54,6 +79,8 @@ def radar_write_start_scheduler(id_camp,id_radar):
# print(exp)
if exp.status == 2:
print('\t\t\t {} \t\t Experiment already runnnig'.format(exp))
+ elif exp.status==5:
+ print('Experiment {} busy'.format(exp))
else:
exp.status = exp.start()
if exp.status == 0:
diff --git a/apps/main/models.py b/apps/main/models.py
index 4c8494b..4406b5b 100644
--- a/apps/main/models.py
+++ b/apps/main/models.py
@@ -425,6 +425,9 @@ class Experiment(models.Model):
Configure and start experiments's devices
ABS-CGS-DDS-RC-JARS
'''
+ self.status=5 #Busy
+ self.save()
+ # print("Guardando STATUS: {}".format(self.status))
confs = []
allconfs = Configuration.objects.filter(experiment=self, type = 0).order_by('-device__device_type__sequence')
@@ -437,18 +440,32 @@ class Experiment(models.Model):
else:
confs = allconfs
- print("confs: ",confs)
- #try:
+
for conf in confs:
- print("conf->",conf)
- conf.stop_device()
- conf.write_device()
+ print(conf.device)
+ print(conf.device.status)
+ print("--------------",flush=True)
+ print("Stop ",conf.name,flush=True)
+ if conf.stop_device() ==False:
+ print("Falló Stop ",conf.name)
+ print("Cancelando Campaña...",flush=True)
+ return 0
+ print("Write ",conf.name,flush=True)
+ if conf.write_device() ==False:
+ print("Falló Write ",conf.name)
+ print("Cancelando Campaña...",flush=True)
+ return 0
+ print("Save",conf.name,flush=True)
conf.device.conf_active = conf.pk
conf.device.save()
- conf.start_device()
+ print("Start",conf.name,flush=True)
+ if conf.start_device()==False:
+ print("Falló Start ",conf.name)
+ print("Cancelando Campaña...",flush=True)
+ return 0
+ print("--- CONFIGURACIÓN EXITOSA ---",flush=True)
time.sleep(1)
- #except:
- #return 0
+
return 2
diff --git a/apps/main/static/css/bootstrap.css b/apps/main/static/css/bootstrap.css
index 680e768..b5a2bd4 100644
--- a/apps/main/static/css/bootstrap.css
+++ b/apps/main/static/css/bootstrap.css
@@ -5733,7 +5733,7 @@ button.list-group-item-danger.active:focus {
}
.panel-default > .panel-heading {
color: #333;
- background-color: #f5f5f5;
+ background-color: #ffffff;
border-color: #ddd;
}
.panel-default > .panel-heading + .panel-collapse > .panel-body {
diff --git a/apps/main/static/js/prueba.js b/apps/main/static/js/prueba.js
new file mode 100644
index 0000000..0754a2e
--- /dev/null
+++ b/apps/main/static/js/prueba.js
@@ -0,0 +1,128 @@
+$(document).ready(function() {
+ var socket = io.connect('http://' + document.domain + ':' + location.port);
+
+ socket.on('connect', function(data) {
+ console.log('Connecting... OK');
+ makePlot("plot-temp",2,["T1","T2"],[14, 45])
+ makePlot("plot-pot",2,["T1","T2"],[70,100])
+ makePlot("plot-pot-t1",4,["P1","P2","P3","P4"],[0,26])
+ makePlot("plot-pot-t2",4,["P1","P2","P3","P4"],[0,26])
+ $("#temp-info-1").hide();
+ $("#temp-info-2").hide();
+ })
+
+ socket.on('test', function(data) {
+ let total = data.pow.reduce((a, b) => a + b, 0);
+ var id = (data.num/4)>>0;
+ streamPlot("plot-pot",data.time,total/1000.0,id,81);
+ streamPlot("plot-temp",data.time,data.tmax[0],id,40);
+ if(id == 0){
+ streamPlot2("plot-pot-t1",data.time,data.pow);
+ ligthStatus('status1','status-text1',data.status);
+ PotenciaAmplificador(['#pot1-1','#pot1-2','#pot1-3','#pot1-4'],data.pow);
+ $('#temp-1').text(data.tmax[0]);
+ if(eval(data.tmax[0])>30){
+ $("#temp-info-1").show();
+ $("#temp-info-1").text("TX"+(id+1)+" - Amplificador " + data.tmax[1]);
+ }
+ else{$("#status-temp").hide();}
+ }
+ else if(id == 1){
+ streamPlot2("plot-pot-t2",data.time,data.pow);
+ ligthStatus('status2','status-text2',data.status);
+ PotenciaAmplificador(['#pot2-1','#pot2-2','#pot2-3','#pot2-4'],data.pow);
+ $('#temp-2').text(data.tmax[0]);
+ if(eval(data.tmax[0])>30){
+ $("#temp-info-2").show();
+ $("#temp-info-2").text("TX"+(id+1)+" - Amplificador " + data.tmax[1]);
+ }
+ else{$("#status-temp").hide();}
+ }
+ })
+ $('form#controlON').submit(function(event) {
+ socket.emit('control_event', {data: 1});
+ return false;
+ });
+ $('form#controlOFF').submit(function(event) {
+ socket.emit('control_event', {data: 0});
+ return false;
+ });
+ $('#plot1').on('show.bs.modal', function(){
+ PotenciaAmplificador(['pot1-1','pot1-2','pot1-3','pot1-4']);
+ });
+ $('#plot1').on('show.bs.modal', function(){
+ PotenciaAmplificador(['pot2-1','pot2-2','pot2-3','pot2-4']);
+ });
+ });
+
+ function makePlot(div, n=1, names=["", ""],ranges){
+ var plotDiv = document.getElementById(div);
+ var traces = [];
+ for (let i = 0; i < n; i++) {
+ traces.push({x: [], y: [],mode: 'lines', name: names[i]});
+ }
+ traces.push({x: [], y: [],mode: 'lines',line: {color:'rgb(219, 64, 82)',dash: 'dot',width: 2},name:"nominal",showlegend: false});
+ var yrange = ranges;
+ var layout = {
+ autosize: true,
+ font: {size: 12},
+ margin: { t: 10, b:50 },
+ xaxis: {
+ type: 'date'
+ },
+ yaxis: {
+ range: yrange,
+ },
+ };
+
+ Plotly.plot(plotDiv, traces, layout);
+ };
+
+ function streamPlot(div,x,y,ind,val){
+ var plotDiv = document.getElementById(div);
+ if (plotDiv.data[ind].x.length > 8){
+ plotDiv.data[2].x = plotDiv.data[2].x.slice(-23)
+ plotDiv.data[2].y = plotDiv.data[2].y.slice(-23)
+ plotDiv.data[ind].x = plotDiv.data[ind].x.slice(-11)
+ plotDiv.data[ind].y = plotDiv.data[ind].y.slice(-11)
+ }
+ var tm = [x];
+ var values = [y];
+ var data_update = {x: [tm,tm], y: [values,[val]]}
+ Plotly.extendTraces(plotDiv, data_update,[ind,2])
+ };
+ function streamPlot2(div,x,y){
+ var plotDiv = document.getElementById(div);
+ if (plotDiv.data[0].x.length > 8){
+ for(let i=0;i<4;i++){
+ plotDiv.data[i].x = plotDiv.data[i].x.slice(-11)
+ plotDiv.data[i].y = plotDiv.data[i].y.slice(-11)
+ }
+ }
+ var tm = [x];
+ var values = [];
+ for(let i=0;i<4;i++){
+ values[i]=[y[i]/1000.0];
+ }
+ var data_update = {x: [tm,tm,tm,tm], y: values}
+ Plotly.extendTraces(plotDiv, data_update,[0,1,2,3])
+ };
+ function ligthStatus(div1,div2,status){
+ if(status==='0000'){
+ document.getElementById(div1).style.backgroundColor = "red";
+ document.getElementById(div2).innerHTML = "Desabilitado";
+ }
+ else if(status==='1111'){
+ document.getElementById(div1).style.backgroundColor = "green";
+ document.getElementById(div2).innerHTML = "Habilitado";
+ }
+ else{
+ document.getElementById(div1).style.backgroundColor = "yellow";
+ document.getElementById(div2).innerHTML = "Incompleto";
+ }
+ }
+ function PotenciaAmplificador(div,data){
+ for(let i=0; i<4; i++){
+ $(div[i]).text(data[i]/1000.0);
+ }
+ }
\ No newline at end of file
diff --git a/apps/main/templates/base.html b/apps/main/templates/base.html
index 332ee6d..b1909e1 100644
--- a/apps/main/templates/base.html
+++ b/apps/main/templates/base.html
@@ -60,9 +60,9 @@
{% else %}
-
@@ -88,12 +88,11 @@
{% endfor %}
{% endif %}
{% endblock %}
-
- {% block content %}
- {% endblock %}
-
+ {% block content %}
+ {% endblock %}
-
+ {% block content-graph %}
+ {% endblock %}
diff --git a/apps/main/templates/base_list.html b/apps/main/templates/base_list.html
index a9f3f11..45bd582 100644
--- a/apps/main/templates/base_list.html
+++ b/apps/main/templates/base_list.html
@@ -40,6 +40,8 @@
{% endfor%}
{% for object in objects %}
+
{{ object }}
+
{{ objects }}
{{ forloop.counter|add:offset }} |
{% for key in keys %}
diff --git a/apps/main/templates/dev_conf.html b/apps/main/templates/dev_conf.html
index 921de49..d2bd053 100644
--- a/apps/main/templates/dev_conf.html
+++ b/apps/main/templates/dev_conf.html
@@ -46,7 +46,7 @@
{% else %}
Connected |
{% endif %}
-
+
{% for key in dev_conf_keys %}
diff --git a/apps/rc/models.py b/apps/rc/models.py
index 3543692..a1acb65 100644
--- a/apps/rc/models.py
+++ b/apps/rc/models.py
@@ -199,9 +199,11 @@ class RCConfiguration(Configuration):
'params': json.dumps(line_data['params'])
}
)
+ print(line,flush=True)
for i, line in enumerate(self.get_lines()):
line_params = json.loads(line.params)
+ print("accedimos a dict_to5",flush=True)
if 'TX_ref' in line_params:
if line_params['TX_ref'] in (0, '0'):
line_params['TX_ref'] = '0'
@@ -552,7 +554,7 @@ class RCConfiguration(Configuration):
return True
def write_device(self, raw=False):
- print("write device")
+ print("write device",flush=True)
if not raw:
clock = RCClock.objects.get(rc_configuration=self)
@@ -561,8 +563,10 @@ class RCConfiguration(Configuration):
else:
data = {'manual': [clock.multiplier, clock.divisor, clock.reference]}
payload = self.request('setfreq', 'post', data=json.dumps(data))
+ print(payload)
if payload['command'] != 'ok':
self.message = 'RC write: {}'.format(payload['command'])
+ print('RC write: {}'.format(payload['command']))
else:
self.message = payload['programming']
if payload['programming'] == 'fail':
@@ -616,10 +620,12 @@ class RCConfiguration(Configuration):
self.device.status = 3
self.device.save()
self.message = 'RC configured and started'
+ print('RC configured and started')
else:
self.device.status = 1
self.device.save()
self.message = 'RC write: {}'.format(payload['write'])
+ print('RC write: {}'.format(payload['write']))
return False
#payload = self.request('start', 'post')
@@ -682,8 +688,11 @@ class RCLine(models.Model):
ordering = ['channel']
def __str__(self):
- if self.rc_configuration:
- return u'{}|{} - {}'.format(self.pk, self.get_name(), self.rc_configuration.name)
+ print("AAAA: ",self.rc_configuration,flush=True)
+ ret = u'{}|{} - {}'.format(self.pk, self.get_name(),self.rc_configuration.name)
+ return ret
+ # if self.rc_configuration:
+ # return u'{}|{} - {}'.format(self.pk, self.get_name(), self.rc_configuration.name)
def jsonify(self):
diff --git a/apps/rc/views.py b/apps/rc/views.py
index 35eb710..dc1163c 100644
--- a/apps/rc/views.py
+++ b/apps/rc/views.py
@@ -355,20 +355,27 @@ def update_lines_position(request, conf_id):
def import_file(request, conf_id):
-
+ print("HOLA",flush=True)
conf = get_object_or_404(RCConfiguration, pk=conf_id)
+ print("HOLA2",flush=True)
if request.method=='POST':
form = RCImportForm(request.POST, request.FILES)
+ print("HOLA3",flush=True)
if form.is_valid():
- try:
- data = conf.import_from_file(request.FILES['file_name'])
- conf.dict_to_parms(data)
- conf.update_pulses()
- messages.success(request, 'Configuration "%s" loaded succesfully' % request.FILES['file_name'])
- return redirect(conf.get_absolute_url_edit())
-
- except Exception as e:
- messages.error(request, 'Error parsing file: "%s" - %s' % (request.FILES['file_name'], repr(e)))
+ print("HOLA4",flush=True)
+ # try:
+ print("HOLA5",flush=True)
+ data = conf.import_from_file(request.FILES['file_name'])
+ print("HOLA6",flush=True)
+ conf.dict_to_parms(data)
+ print("1",flush=True)
+ conf.update_pulses()
+ print("2",flush=True)
+ messages.success(request, 'Configuration "%s" loaded succesfully' % request.FILES['file_name'])
+ return redirect(conf.get_absolute_url_edit())
+
+ # except Exception as e:
+ # messages.error(request, 'Error parsing file: "%s" - %s' % (request.FILES['file_name'], repr(e)))
else:
messages.warning(request, 'Your current configuration will be replaced')
form = RCImportForm()
diff --git a/docker-compose.yml b/docker-compose.yml
index ddf7187..d27c93e 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -35,6 +35,8 @@ services:
- pgdata:/var/lib/postgresql/data
ports:
- 5432:5432
+ expose:
+ - 5432
env_file: .env
#Web Server
diff --git a/radarsys/settings.py b/radarsys/settings.py
index aec2409..3b87972 100644
--- a/radarsys/settings.py
+++ b/radarsys/settings.py
@@ -29,7 +29,10 @@ ALLOWED_HOSTS = ['*']
CSRF_TRUSTED_ORIGINS=[
"http://*.localhost:8030",
"http://localhost:8030",
- "http://127.0.0.1:8030"
+ "http://127.0.0.1:8030",
+ "http://*.localhost:8086",
+ "http://localhost:8086",
+ "http://127.0.0.1:8086"
]
#Si se requiere que la aplicación salga de este entorno, para otros usuarios es necesario hacer una API request https://fractalideas.com/blog/making-react-and-django-play-well-together-single-page-app-model/
diff --git a/radarsys/static/css/switch.css b/radarsys/static/css/switch.css
new file mode 100644
index 0000000..015cad7
--- /dev/null
+++ b/radarsys/static/css/switch.css
@@ -0,0 +1,56 @@
+* {
+ margin: 0;
+ padding: 0;
+ font-family: "Montserrat";
+ }
+
+ body {
+ background-color: #fff3f5;
+ }
+ body .switch {
+ display: block;
+ margin: 30px;
+ }
+ body .switch h3 {
+ font-weight: 400;
+ padding-bottom: 6px;
+ }
+ body .switch input[type=checkbox] {
+ display: none;
+ }
+ body .switch input[type=checkbox]:checked + label {
+ background-color: #2f7df9;
+ }
+ body .switch input[type=checkbox]:checked + label:after {
+ left: 33px;
+ }
+ body .switch label {
+ transition: all 200ms ease-in-out;
+ display: inline-block;
+ position: relative;
+ height: 40px;
+ width: 70px;
+ border-radius: 40px;
+ cursor: pointer;
+ background-color: #ddd;
+ color: transparent;
+ }
+ body .switch label:after {
+ transition: all 200ms ease-in-out;
+ content: " ";
+ position: absolute;
+ height: 34px;
+ width: 34px;
+ border-radius: 50%;
+ background-color: white;
+ top: 3px;
+ left: 3px;
+ right: auto;
+ box-shadow: 1px 1px 1px gray;
+ }
+ body .switch.colored input[type=checkbox]:checked + label {
+ background-color: #55c946;
+ }
+ body .switch.colored label {
+ background-color: #ff4949;
+ }
\ No newline at end of file
diff --git a/radarsys/static/js/atrad-conf.js b/radarsys/static/js/atrad-conf.js
new file mode 100644
index 0000000..9547168
--- /dev/null
+++ b/radarsys/static/js/atrad-conf.js
@@ -0,0 +1,127 @@
+$(document).ready(function() {
+ var socket = io.connect('http://' + document.domain + ':' + location.port);
+
+ socket.on('connect', function(data) {
+ console.log('Connecting OK');
+ makePlot("plot-temp",2,["Tx1","Tx2"],[14, 45])
+ makePlot("plot-pot",2,["Tx1","Tx2"],[70,100])
+ makePlot("plot-pot-t1",4,["P1","P2","P3","P4"],[0,25])
+ makePlot("plot-pot-t2",4,["P1","P2","P3","P4"],[0,25])
+ })
+
+ socket.on('test', function(data) {
+ UpdateData(data.num,data);
+ })
+ $('#ONBtn1').click(function() {
+ console.log("holaa")
+ socket.emit('atrad_control_event', '11');
+ });
+ $('#ONBtn2').click(function(){
+ console.log("holaa2")
+ socket.emit('atrad_control_event', '21');
+ });
+ $('#OFFBtn1').click(function() {
+ socket.emit('atrad_control_event','10');
+ });
+ $('#OFFBtn2').click(function(){
+ socket.emit('atrad_control_event', '20');
+ });
+});
+
+function UpdateData(id,data){
+ let total = data.pow.reduce((a, b) => a + b, 0)/1000.0;
+ streamPlot("plot-pot",data.time,total,id,81);
+ streamPlot("plot-temp",data.time,data.tmax[0],id,40);
+ streamPlot2("plot-pot-t"+(id+1),data.time,data.pow);
+ ligthStatus(id,data.status);
+ PotenciaAmplificador(id,data.pow,total);
+ $('#temp'+(id+1)).text(data.tmax[0]);
+ if(eval(data.tmax[0])>20){
+ $('#alert-time'+(id+1)).text(data.time.slice(-8,));
+ $('#alert-temp'+(id+1)).text(data.tmax[0]);
+ $('#alert-loc'+(id+1)).text('Tx'+(id+1)+' '+data.tmax[1]);
+ }
+}
+
+function makePlot(div, n=1, names=["", ""],ranges){
+ var plotDiv = document.getElementById(div);
+ var traces = [];
+ for (let i = 0; i < n; i++) {
+ traces.push({x: [], y: [],mode: 'lines', name: names[i]});
+ }
+ traces.push({x: [], y: [],mode: 'lines',line: {color:'rgb(219, 64, 82)',dash: 'dot',width: 2},name:"nominal",showlegend: false});
+ var yrange = ranges;
+ var layout = {
+ width: 700,
+ height: 350,
+ font: {size: 12},
+ margin: { t: 10, b:40,},
+ xaxis: {
+ type: 'date'
+ },
+ yaxis: {
+ range: yrange,
+ },
+ };
+ var config = {responsive: true}
+ Plotly.newPlot(plotDiv, traces, layout,config);
+};
+
+function streamPlot(div,x,y,ind,val){
+ var plotDiv = document.getElementById(div);
+ if (plotDiv.data[ind].x.length > 8){
+ plotDiv.data[2].x = plotDiv.data[2].x.slice(-23)
+ plotDiv.data[2].y = plotDiv.data[2].y.slice(-23)
+ plotDiv.data[ind].x = plotDiv.data[ind].x.slice(-11)
+ plotDiv.data[ind].y = plotDiv.data[ind].y.slice(-11)
+ }
+ var tm = [x];
+ var values = [y];
+ var data_update = {x: [tm,tm], y: [values,[val]]}
+ Plotly.extendTraces(plotDiv, data_update,[ind,2])
+};
+function streamPlot2(div,x,y){
+ var plotDiv = document.getElementById(div);
+ if (plotDiv.data[0].x.length > 8){
+ for(let i=0;i<4;i++){
+ plotDiv.data[i].x = plotDiv.data[i].x.slice(-11)
+ plotDiv.data[i].y = plotDiv.data[i].y.slice(-11)
+ }
+ }
+ var tm = [x];
+ var values = [];
+ for(let i=0;i<4;i++){
+ values[i]=[y[i]/1000.0];
+ }
+ var data_update = {x: [tm,tm,tm,tm], y: values}
+ Plotly.extendTraces(plotDiv, data_update,[0,1,2,3])
+};
+
+function ligthStatus(id,status){
+ let div1 = 'status'+(id+1);
+ let div2 = 'status-text'+(id+1);
+
+ if(status==='0000'){
+ document.getElementById(div1).style.backgroundColor = "red";
+ document.getElementById(div2).innerHTML = "Disable";
+ }
+ else if(status==='1111'){
+ document.getElementById(div1).style.backgroundColor = "green";
+ document.getElementById(div2).innerHTML = "Fully enable";
+ }
+ else{
+ document.getElementById(div1).style.backgroundColor = "yellow";
+ document.getElementById(div2).innerHTML = "Not fully enable";
+ }
+};
+
+function PotenciaAmplificador(id,data1,data2){
+ let div = '#pot'+(id+1);
+ for(let i=1; i<5; i++){
+ $(div+'-'+i).text(data1[i-1]/1000.0);
+ }
+ $(div).text(data2);
+ }
+ $(".clickable-row").click(function() {
+ window.open($(this).data("href"),);
+});
\ No newline at end of file
diff --git a/radarsys/urls.py b/radarsys/urls.py
index 29801d3..3d92b8b 100644
--- a/radarsys/urls.py
+++ b/radarsys/urls.py
@@ -1,6 +1,5 @@
from django.urls import include, path
from django.contrib import admin
-#from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/',admin.site.urls),
@@ -15,6 +14,4 @@ urlpatterns = [
path('misc/',include('apps.misc.urls')),
path('dds_rest/', include('apps.dds_rest.urls')),
path('atrad/', include('apps.atrad.urls')),
-]
-
-#urlpatterns += staticfiles_urlpatterns()
+]
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index 6d9d896..12c7ad2 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -14,5 +14,5 @@ redis==4.4.2
paho-mqtt==1.6.1
eventlet==0.30.2
-python-engineio
-python-socketio
\ No newline at end of file
+python-engineio==4.3.4
+python-socketio==5.7.2
\ No newline at end of file