##// END OF EJS Templates
Se consiguió el scheduler
Renato Huallpa -
r389:b38f3eac9d06
parent child
Show More
@@ -1,1082 +1,1081
1 from django.db import models
1 from django.db import models
2 from apps.main.models import Configuration , User
2 from apps.main.models import Configuration , User
3 from django.urls import reverse
3 from django.urls import reverse
4 from celery.execute import send_task
4 from celery.execute import send_task
5 from datetime import datetime
5 from datetime import datetime
6 import ast
6 import ast
7 import socket
7 import socket
8 import json
8 import json
9 import requests
9 import requests
10 import struct
10 import struct
11 import os, sys, time
11 import os, sys, time
12
12
13 from .mqtt import client as mqtt_client
13 from .mqtt import client as mqtt_client
14 from radarsys.socketconfig import sio as sio
14 from radarsys.socketconfig import sio as sio
15 import json
15 import json
16
16
17 antenna_default = json.dumps({
17 antenna_default = json.dumps({
18 "antenna_up": [[0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
18 "antenna_up": [[0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
19 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
19 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
20 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
20 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
21 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
21 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
22 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0],
22 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0],
23 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0],
23 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0],
24 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0],
24 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0],
25 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0]
25 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0]
26 ]
26 ]
27 ,
27 ,
28 "antenna_down": [[0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
28 "antenna_down": [[0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
29 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
29 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
30 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
30 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
31 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
31 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
32 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0],
32 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0],
33 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0],
33 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0],
34 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0],
34 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0],
35 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0]],
35 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0]],
36 })
36 })
37
37
38
38
39 tx_default = json.dumps({
39 tx_default = json.dumps({
40 "up": [[1,1,1,1,0,0,0,0],
40 "up": [[1,1,1,1,0,0,0,0],
41 [1,1,1,1,0,0,0,0],
41 [1,1,1,1,0,0,0,0],
42 [1,1,1,1,0,0,0,0],
42 [1,1,1,1,0,0,0,0],
43 [1,1,1,1,0,0,0,0],
43 [1,1,1,1,0,0,0,0],
44 [0,0,0,0,1,1,1,1],
44 [0,0,0,0,1,1,1,1],
45 [0,0,0,0,1,1,1,1],
45 [0,0,0,0,1,1,1,1],
46 [0,0,0,0,1,1,1,1],
46 [0,0,0,0,1,1,1,1],
47 [0,0,0,0,1,1,1,1]],
47 [0,0,0,0,1,1,1,1]],
48
48
49 "down": [[1,1,1,1,0,0,0,0],
49 "down": [[1,1,1,1,0,0,0,0],
50 [1,1,1,1,0,0,0,0],
50 [1,1,1,1,0,0,0,0],
51 [1,1,1,1,0,0,0,0],
51 [1,1,1,1,0,0,0,0],
52 [1,1,1,1,0,0,0,0],
52 [1,1,1,1,0,0,0,0],
53 [0,0,0,0,1,1,1,1],
53 [0,0,0,0,1,1,1,1],
54 [0,0,0,0,1,1,1,1],
54 [0,0,0,0,1,1,1,1],
55 [0,0,0,0,1,1,1,1],
55 [0,0,0,0,1,1,1,1],
56 [0,0,0,0,1,1,1,1]],
56 [0,0,0,0,1,1,1,1]],
57 })
57 })
58
58
59 rx_default = json.dumps({
59 rx_default = json.dumps({
60 "up": [[1,1,1,1,0,0,0,0],
60 "up": [[1,1,1,1,0,0,0,0],
61 [1,1,1,1,0,0,0,0],
61 [1,1,1,1,0,0,0,0],
62 [1,1,1,1,0,0,0,0],
62 [1,1,1,1,0,0,0,0],
63 [1,1,1,1,0,0,0,0],
63 [1,1,1,1,0,0,0,0],
64 [0,0,0,0,1,1,1,1],
64 [0,0,0,0,1,1,1,1],
65 [0,0,0,0,1,1,1,1],
65 [0,0,0,0,1,1,1,1],
66 [0,0,0,0,1,1,1,1],
66 [0,0,0,0,1,1,1,1],
67 [0,0,0,0,1,1,1,1]],
67 [0,0,0,0,1,1,1,1]],
68
68
69 "down": [[1,1,1,1,0,0,0,0],
69 "down": [[1,1,1,1,0,0,0,0],
70 [1,1,1,1,0,0,0,0],
70 [1,1,1,1,0,0,0,0],
71 [1,1,1,1,0,0,0,0],
71 [1,1,1,1,0,0,0,0],
72 [1,1,1,1,0,0,0,0],
72 [1,1,1,1,0,0,0,0],
73 [0,0,0,0,1,1,1,1],
73 [0,0,0,0,1,1,1,1],
74 [0,0,0,0,1,1,1,1],
74 [0,0,0,0,1,1,1,1],
75 [0,0,0,0,1,1,1,1],
75 [0,0,0,0,1,1,1,1],
76 [0,0,0,0,1,1,1,1]],
76 [0,0,0,0,1,1,1,1]],
77 })
77 })
78
78
79 status_default = '0000000000000000000000000000000000000000000000000000000000000000'
79 status_default = '0000000000000000000000000000000000000000000000000000000000000000'
80 default_messages = {}
80 default_messages = {}
81
81
82 for i in range(1,65):
82 for i in range(1,65):
83 default_messages[str(i)] = "Module "+str(i)
83 default_messages[str(i)] = "Module "+str(i)
84
84
85
85
86 ues_default = json.dumps({
86 ues_default = json.dumps({
87 "up": [0.533333,0.00000,1.06667,0.00000],
87 "up": [0.533333,0.00000,1.06667,0.00000],
88 "down": [0.533333,0.00000,1.06667,0.00000]
88 "down": [0.533333,0.00000,1.06667,0.00000]
89 })
89 })
90
90
91 onlyrx_default = json.dumps({
91 onlyrx_default = json.dumps({
92 "up": False,
92 "up": False,
93 "down": False
93 "down": False
94 })
94 })
95
95
96 def up_convertion(cadena):
96 def up_convertion(cadena):
97 valores = []
97 valores = []
98 for c in cadena:
98 for c in cadena:
99 if c == 1.0: valores=valores+['000']
99 if c == 1.0: valores=valores+['000']
100 if c == 2.0: valores=valores+['001']
100 if c == 2.0: valores=valores+['001']
101 if c == 3.0: valores=valores+['010']
101 if c == 3.0: valores=valores+['010']
102 if c == 0.0: valores=valores+['011']
102 if c == 0.0: valores=valores+['011']
103 if c == 0.5: valores=valores+['100']
103 if c == 0.5: valores=valores+['100']
104 if c == 1.5: valores=valores+['101']
104 if c == 1.5: valores=valores+['101']
105 if c == 2.5: valores=valores+['110']
105 if c == 2.5: valores=valores+['110']
106 if c == 3.5: valores=valores+['111']
106 if c == 3.5: valores=valores+['111']
107
107
108 return valores
108 return valores
109
109
110 def up_conv_bits(value):
110 def up_conv_bits(value):
111
111
112 if value == 1.0: bits="000"
112 if value == 1.0: bits="000"
113 if value == 2.0: bits="001"
113 if value == 2.0: bits="001"
114 if value == 3.0: bits="010"
114 if value == 3.0: bits="010"
115 if value == 0.0: bits="011"
115 if value == 0.0: bits="011"
116 if value == 0.5: bits="100"
116 if value == 0.5: bits="100"
117 if value == 1.5: bits="101"
117 if value == 1.5: bits="101"
118 if value == 2.5: bits="110"
118 if value == 2.5: bits="110"
119 if value == 3.5: bits="111"
119 if value == 3.5: bits="111"
120
120
121 return bits
121 return bits
122
122
123 def down_convertion(cadena):
123 def down_convertion(cadena):
124 valores = []
124 valores = []
125 for c in cadena:
125 for c in cadena:
126 if c == 1.0: valores=valores+['000']
126 if c == 1.0: valores=valores+['000']
127 if c == 2.0: valores=valores+['001']
127 if c == 2.0: valores=valores+['001']
128 if c == 3.0: valores=valores+['010']
128 if c == 3.0: valores=valores+['010']
129 if c == 0.0: valores=valores+['011']
129 if c == 0.0: valores=valores+['011']
130 if c == 0.5: valores=valores+['100']
130 if c == 0.5: valores=valores+['100']
131 if c == 1.5: valores=valores+['101']
131 if c == 1.5: valores=valores+['101']
132 if c == 2.5: valores=valores+['110']
132 if c == 2.5: valores=valores+['110']
133 if c == 3.5: valores=valores+['111']
133 if c == 3.5: valores=valores+['111']
134
134
135 return valores
135 return valores
136
136
137 def down_conv_bits(value):
137 def down_conv_bits(value):
138
138
139 if value == 1.0: bits="000"
139 if value == 1.0: bits="000"
140 if value == 2.0: bits="001"
140 if value == 2.0: bits="001"
141 if value == 3.0: bits="010"
141 if value == 3.0: bits="010"
142 if value == 0.0: bits="011"
142 if value == 0.0: bits="011"
143 if value == 0.5: bits="100"
143 if value == 0.5: bits="100"
144 if value == 1.5: bits="101"
144 if value == 1.5: bits="101"
145 if value == 2.5: bits="110"
145 if value == 2.5: bits="110"
146 if value == 3.5: bits="111"
146 if value == 3.5: bits="111"
147
147
148 return bits
148 return bits
149
149
150 def up_conv_value(bits):
150 def up_conv_value(bits):
151
151
152 if bits == "000": value=1.0
152 if bits == "000": value=1.0
153 if bits == "001": value=2.0
153 if bits == "001": value=2.0
154 if bits == "010": value=3.0
154 if bits == "010": value=3.0
155 if bits == "011": value=0.0
155 if bits == "011": value=0.0
156 if bits == "100": value=0.5
156 if bits == "100": value=0.5
157 if bits == "101": value=1.5
157 if bits == "101": value=1.5
158 if bits == "110": value=2.5
158 if bits == "110": value=2.5
159 if bits == "111": value=3.5
159 if bits == "111": value=3.5
160
160
161 return value
161 return value
162
162
163 def down_conv_value(bits):
163 def down_conv_value(bits):
164
164
165 if bits == "000": value=1.0
165 if bits == "000": value=1.0
166 if bits == "001": value=2.0
166 if bits == "001": value=2.0
167 if bits == "010": value=3.0
167 if bits == "010": value=3.0
168 if bits == "011": value=0.0
168 if bits == "011": value=0.0
169 if bits == "100": value=0.5
169 if bits == "100": value=0.5
170 if bits == "101": value=1.5
170 if bits == "101": value=1.5
171 if bits == "110": value=2.5
171 if bits == "110": value=2.5
172 if bits == "111": value=3.5
172 if bits == "111": value=3.5
173
173
174 return value
174 return value
175
175
176 def ip2position(module_number):
176 def ip2position(module_number):
177 j=0
177 j=0
178 i=0
178 i=0
179 for x in range(0,module_number-1):
179 for x in range(0,module_number-1):
180 j=j+1
180 j=j+1
181 if j==8:
181 if j==8:
182 i=i+1
182 i=i+1
183 j=0
183 j=0
184
184
185 pos = [i,j]
185 pos = [i,j]
186 return pos
186 return pos
187
187
188
188
189 def fromBinary2Char(binary_string):
189 def fromBinary2Char(binary_string):
190 number = int(binary_string, 2)
190 number = int(binary_string, 2)
191 #Plus 33 to avoid more than 1 characters values such as: '\x01'-'\x1f'
191 #Plus 33 to avoid more than 1 characters values such as: '\x01'-'\x1f'
192 number = number + 33
192 number = number + 33
193 char = chr(number)
193 char = chr(number)
194 return char
194 return char
195
195
196 def fromChar2Binary(char):
196 def fromChar2Binary(char):
197 number = ord(char) - 33
197 number = ord(char) - 33
198 #Minus 33 to get the real value
198 #Minus 33 to get the real value
199 bits = bin(number)[2:]
199 bits = bin(number)[2:]
200 #To ensure we have a string with 6bits
200 #To ensure we have a string with 6bits
201 if len(bits) < 6:
201 if len(bits) < 6:
202 bits = bits.zfill(6)
202 bits = bits.zfill(6)
203 return bits
203 return bits
204
204
205 OPERATION_MODES = (
205 OPERATION_MODES = (
206 (0, 'Manual'),
206 (0, 'Manual'),
207 (1, 'Automatic'),
207 (1, 'Automatic'),
208 )
208 )
209
209
210 class ABSConfiguration(Configuration):
210 class ABSConfiguration(Configuration):
211 active_beam = models.PositiveSmallIntegerField(verbose_name='Active Beam', default=0)
211 active_beam = models.PositiveSmallIntegerField(verbose_name='Active Beam', default=0)
212 module_status = models.CharField(verbose_name='Module Status', max_length=10000, default=status_default)
212 module_status = models.CharField(verbose_name='Module Status', max_length=10000, default=status_default)
213 operation_mode = models.PositiveSmallIntegerField(verbose_name='Operation Mode', choices=OPERATION_MODES, default = 0)
213 operation_mode = models.PositiveSmallIntegerField(verbose_name='Operation Mode', choices=OPERATION_MODES, default = 0)
214 operation_value = models.FloatField(verbose_name='Periodic (seconds)', default="10", null=True, blank=True)
214 operation_value = models.FloatField(verbose_name='Periodic (seconds)', default="10", null=True, blank=True)
215 module_messages = models.CharField(verbose_name='Modules Messages', max_length=10000, default=json.dumps(default_messages))
215 module_messages = models.CharField(verbose_name='Modules Messages', max_length=10000, default=json.dumps(default_messages))
216
216
217 class Meta:
217 class Meta:
218 db_table = 'abs_configurations'
218 db_table = 'abs_configurations'
219
219
220 def get_absolute_url_plot(self):
220 def get_absolute_url_plot(self):
221 return reverse('url_plot_abs_patterns', args=[str(self.id)])
221 return reverse('url_plot_abs_patterns', args=[str(self.id)])
222
222
223
223
224 def parms_to_dict(self):
224 def parms_to_dict(self):
225
225
226 parameters = {}
226 parameters = {}
227
227
228 parameters['device_id'] = self.device.id
228 parameters['device_id'] = self.device.id
229 parameters['label'] = self.label
229 parameters['label'] = self.label
230 parameters['device_type'] = self.device.device_type.name
230 parameters['device_type'] = self.device.device_type.name
231 parameters['beams'] = {}
231 parameters['beams'] = {}
232
232
233 beams = ABSBeam.objects.filter(abs_conf=self)
233 beams = ABSBeam.objects.filter(abs_conf=self)
234 b=1
234 b=1
235 for beam in beams:
235 for beam in beams:
236 #absbeam = ABSBeam.objects.get(pk=beams[beam])
236 #absbeam = ABSBeam.objects.get(pk=beams[beam])
237 parameters['beams']['beam'+str(b)] = beam.parms_to_dict()#absbeam.parms_to_dict()
237 parameters['beams']['beam'+str(b)] = beam.parms_to_dict()#absbeam.parms_to_dict()
238 b+=1
238 b+=1
239
239
240 return parameters
240 return parameters
241
241
242
242
243 def dict_to_parms(self, parameters):
243 def dict_to_parms(self, parameters):
244
244
245 self.label = parameters['label']
245 self.label = parameters['label']
246
246
247 absbeams = ABSBeam.objects.filter(abs_conf=self)
247 absbeams = ABSBeam.objects.filter(abs_conf=self)
248 beams = parameters['beams']
248 beams = parameters['beams']
249
249
250 if absbeams:
250 if absbeams:
251 beams_number = len(beams)
251 beams_number = len(beams)
252 absbeams_number = len(absbeams)
252 absbeams_number = len(absbeams)
253 if beams_number==absbeams_number:
253 if beams_number==absbeams_number:
254 i = 1
254 i = 1
255 for absbeam in absbeams:
255 for absbeam in absbeams:
256 absbeam.dict_to_parms(beams['beam'+str(i)])
256 absbeam.dict_to_parms(beams['beam'+str(i)])
257 i = i+1
257 i = i+1
258 elif beams_number > absbeams_number:
258 elif beams_number > absbeams_number:
259 i = 1
259 i = 1
260 for absbeam in absbeams:
260 for absbeam in absbeams:
261 absbeam.dict_to_parms(beams['beam'+str(i)])
261 absbeam.dict_to_parms(beams['beam'+str(i)])
262 i=i+1
262 i=i+1
263 for x in range(i,beams_number+1):
263 for x in range(i,beams_number+1):
264 new_beam = ABSBeam(
264 new_beam = ABSBeam(
265 name =beams['beam'+str(i)]['name'],
265 name =beams['beam'+str(i)]['name'],
266 antenna =json.dumps(beams['beam'+str(i)]['antenna']),
266 antenna =json.dumps(beams['beam'+str(i)]['antenna']),
267 abs_conf = self,
267 abs_conf = self,
268 tx =json.dumps(beams['beam'+str(i)]['tx']),
268 tx =json.dumps(beams['beam'+str(i)]['tx']),
269 rx =json.dumps(beams['beam'+str(i)]['rx']),
269 rx =json.dumps(beams['beam'+str(i)]['rx']),
270 ues =json.dumps(beams['beam'+str(i)]['ues']),
270 ues =json.dumps(beams['beam'+str(i)]['ues']),
271 only_rx =json.dumps(beams['beam'+str(i)]['only_rx'])
271 only_rx =json.dumps(beams['beam'+str(i)]['only_rx'])
272 )
272 )
273 new_beam.save()
273 new_beam.save()
274 i=i+1
274 i=i+1
275 else: #beams_number < absbeams_number:
275 else: #beams_number < absbeams_number:
276 i = 1
276 i = 1
277 for absbeam in absbeams:
277 for absbeam in absbeams:
278 if i <= beams_number:
278 if i <= beams_number:
279 absbeam.dict_to_parms(beams['beam'+str(i)])
279 absbeam.dict_to_parms(beams['beam'+str(i)])
280 i=i+1
280 i=i+1
281 else:
281 else:
282 absbeam.delete()
282 absbeam.delete()
283 else:
283 else:
284 for beam in beams:
284 for beam in beams:
285 new_beam = ABSBeam(
285 new_beam = ABSBeam(
286 name =beams[beam]['name'],
286 name =beams[beam]['name'],
287 antenna =json.dumps(beams[beam]['antenna']),
287 antenna =json.dumps(beams[beam]['antenna']),
288 abs_conf = self,
288 abs_conf = self,
289 tx =json.dumps(beams[beam]['tx']),
289 tx =json.dumps(beams[beam]['tx']),
290 rx =json.dumps(beams[beam]['rx']),
290 rx =json.dumps(beams[beam]['rx']),
291 ues =json.dumps(beams[beam]['ues']),
291 ues =json.dumps(beams[beam]['ues']),
292 only_rx =json.dumps(beams[beam]['only_rx'])
292 only_rx =json.dumps(beams[beam]['only_rx'])
293 )
293 )
294 new_beam.save()
294 new_beam.save()
295
295
296
296
297
297
298 def update_from_file(self, parameters):
298 def update_from_file(self, parameters):
299
299
300 self.dict_to_parms(parameters)
300 self.dict_to_parms(parameters)
301 self.save()
301 self.save()
302
302
303
303
304 def get_beams(self, **kwargs):
304 def get_beams(self, **kwargs):
305 '''
305 '''
306 This function returns ABS Configuration beams
306 This function returns ABS Configuration beams
307 '''
307 '''
308 return ABSBeam.objects.filter(abs_conf=self.pk, **kwargs)
308 return ABSBeam.objects.filter(abs_conf=self.pk, **kwargs)
309
309
310 def clone(self, **kwargs):
310 def clone(self, **kwargs):
311
311
312 beams = self.get_beams()
312 beams = self.get_beams()
313 self.pk = None
313 self.pk = None
314 self.id = None
314 self.id = None
315 for attr, value in kwargs.items():
315 for attr, value in kwargs.items():
316 setattr(self, attr, value)
316 setattr(self, attr, value)
317 self.save()
317 self.save()
318
318
319 for beam in beams:
319 for beam in beams:
320 beam.clone(abs_conf=self)
320 beam.clone(abs_conf=self)
321
321
322 #-----For Active Beam-----
322 #-----For Active Beam-----
323 new_beams = ABSBeam.objects.filter(abs_conf=self)
323 new_beams = ABSBeam.objects.filter(abs_conf=self)
324 self.active_beam = new_beams[0].id
324 self.active_beam = new_beams[0].id
325 self.save()
325 self.save()
326 #-----For Active Beam-----
326 #-----For Active Beam-----
327 #-----For Device Status---
327 #-----For Device Status---
328 self.device.status = 3
328 self.device.status = 3
329 self.device.save()
329 self.device.save()
330 #-----For Device Status---
330 #-----For Device Status---
331
331
332 return self
332 return self
333
333
334
334
335 def start_device(self):
335 def start_device(self):
336
336
337 if self.device.status == 3:
337 if self.device.status == 3:
338
338
339 try:
339 try:
340 #self.write_device()
340 #self.write_device()
341 send_task('task_change_beam', [self.id],)
341 send_task('task_change_beam', [self.id],)
342 self.message = 'ABS running'
342 self.message = 'ABS running'
343
343
344 except Exception as e:
344 except Exception as e:
345 self.message = str(e)
345 self.message = str(e)
346 return False
346 return False
347
347
348 return True
348 return True
349
349
350 else:
350 else:
351 self.message = 'Please, select Write ABS Device first.'
351 self.message = 'Please, select Write ABS Device first.'
352 return False
352 return False
353
353
354
354
355 def stop_device(self):
355 def stop_device(self):
356 print("estoy en ABS models")
357 self.device.status = 2
356 self.device.status = 2
358 self.device.save()
357 self.device.save()
359 self.message = 'ABS has been stopped.'
358 self.message = 'ABS has been stopped.'
360 self.save()
359 self.save()
361
360
362 return True
361 return True
363
362
364 def stop_device_mqtt(self):
363 def stop_device_mqtt(self):
365
364
366 self.device.status = 2
365 self.device.status = 2
367 self.device.save()
366 self.device.save()
368 self.message = 'ABS has been stopped.'
367 self.message = 'ABS has been stopped.'
369 self.save()
368 self.save()
370
369
371 mqtt_client.publish(os.environ.get('TOPIC_ABS', 'abs/beams'),"STOP")
370 mqtt_client.publish(os.environ.get('TOPIC_ABS', 'abs/beams'),"STOP")
372
371
373 return True
372 return True
374
373
375 def write_device(self):
374 def write_device(self):
376
375
377 """
376 """
378 This function sends the beams list to every abs module.
377 This function sends the beams list to every abs module.
379 It needs 'module_conf' function
378 It needs 'module_conf' function
380 """
379 """
381 print("Write 3")
380 print("Write 3")
382
381
383 beams = ABSBeam.objects.filter(abs_conf=self)
382 beams = ABSBeam.objects.filter(abs_conf=self)
384 nbeams = len(beams)
383 nbeams = len(beams)
385
384
386 # Se manda a cero RC para poder realizar cambio de beam
385 # Se manda a cero RC para poder realizar cambio de beam
387 if self.experiment is None:
386 if self.experiment is None:
388 confs = []
387 confs = []
389 else:
388 else:
390 confs = Configuration.objects.filter(experiment = self.experiment).filter(type=0)
389 confs = Configuration.objects.filter(experiment = self.experiment).filter(type=0)
391 confdds = ''
390 confdds = ''
392 confjars = ''
391 confjars = ''
393 confrc = ''
392 confrc = ''
394 #TO STOP DEVICES: DDS-JARS-RC
393 #TO STOP DEVICES: DDS-JARS-RC
395 for i in range(0,len(confs)):
394 for i in range(0,len(confs)):
396 if i==0:
395 if i==0:
397 for conf in confs:
396 for conf in confs:
398 if conf.device.device_type.name == 'dds':
397 if conf.device.device_type.name == 'dds':
399 confdds = conf
398 confdds = conf
400 confdds.stop_device()
399 confdds.stop_device()
401 break
400 break
402 if i==1:
401 if i==1:
403 for conf in confs:
402 for conf in confs:
404 if conf.device.device_type.name == 'jars':
403 if conf.device.device_type.name == 'jars':
405 confjars = conf
404 confjars = conf
406 confjars.stop_device()
405 confjars.stop_device()
407 break
406 break
408 if i==2:
407 if i==2:
409 for conf in confs:
408 for conf in confs:
410 if conf.device.device_type.name == 'rc':
409 if conf.device.device_type.name == 'rc':
411 confrc = conf
410 confrc = conf
412 confrc.stop_device()
411 confrc.stop_device()
413 break
412 break
414
413
415 '''
414 '''
416 if self.connected_modules() == 0 :
415 if self.connected_modules() == 0 :
417 print("No encuentra modulos")
416 print("No encuentra modulos")
418 self.message = "No ABS Module detected."
417 self.message = "No ABS Module detected."
419 return False
418 return False
420 '''
419 '''
421 #-------------Write each abs module-----------
420 #-------------Write each abs module-----------
422
421
423 if beams:
422 if beams:
424 block_id = 0
423 block_id = 0
425 message = 'SNDF{:03d}{:02d}{:02d}'.format(nbeams, nbeams, block_id)
424 message = 'SNDF{:03d}{:02d}{:02d}'.format(nbeams, nbeams, block_id)
426 for i, status in enumerate(self.module_status):
425 for i, status in enumerate(self.module_status):
427 message += ''.join([fromBinary2Char(beam.module_6bits(i)) for beam in beams])
426 message += ''.join([fromBinary2Char(beam.module_6bits(i)) for beam in beams])
428 status = ['0'] * 64
427 status = ['0'] * 64
429 n = 0
428 n = 0
430
429
431 print("Llega una antes entrar a multicast4")
430 print("Llega una antes entrar a multicast4")
432
431
433 sock = self.send_multicast(message)
432 sock = self.send_multicast(message)
434
433
435 while True:
434 while True:
436 #for i in range(32):
435 #for i in range(32):
437 try:
436 try:
438 data, address = sock.recvfrom(1024)
437 data, address = sock.recvfrom(1024)
439 print (address, data)
438 print (address, data)
440 data = data.decode("utf-8")
439 data = data.decode("utf-8")
441 if data == '1':
440 if data == '1':
442 status[int(address[0][10:])-1] = '3'
441 status[int(address[0][10:])-1] = '3'
443 #print (int(address[0][10:])-1)
442 #print (int(address[0][10:])-1)
444 elif data == '0':
443 elif data == '0':
445 status[int(address[0][10:])-1] = '1'
444 status[int(address[0][10:])-1] = '1'
446 except socket.timeout:
445 except socket.timeout:
447 print('Timeout')
446 print('Timeout')
448 break
447 break
449 except Exception as e:
448 except Exception as e:
450 print ('Error {}'.format(e))
449 print ('Error {}'.format(e))
451 n += 1
450 n += 1
452 sock.close()
451 sock.close()
453 else:
452 else:
454 self.message = "ABS Configuration does not have beams"
453 self.message = "ABS Configuration does not have beams"
455 print('No beams')
454 print('No beams')
456 #Start DDS-RC-JARS
455 #Start DDS-RC-JARS
457 if confdds:
456 if confdds:
458 confdds.start_device()
457 confdds.start_device()
459 if confrc:
458 if confrc:
460 #print confrc
459 #print confrc
461 confrc.start_device()
460 confrc.start_device()
462 if confjars:
461 if confjars:
463 confjars.start_device()
462 confjars.start_device()
464 return False
463 return False
465
464
466 if n == 64:
465 if n == 64:
467 self.message = "Could not write ABS Modules"
466 self.message = "Could not write ABS Modules"
468 self.device.status = 0
467 self.device.status = 0
469 self.module_status = ''.join(status)
468 self.module_status = ''.join(status)
470 self.save()
469 self.save()
471 print('Could not write ABS')
470 print('Could not write ABS')
472 #Start DDS-RC-JARS
471 #Start DDS-RC-JARS
473 if confdds:
472 if confdds:
474 confdds.start_device()
473 confdds.start_device()
475 if confrc:
474 if confrc:
476 #print confrc
475 #print confrc
477 confrc.start_device()
476 confrc.start_device()
478 if confjars:
477 if confjars:
479 confjars.start_device()
478 confjars.start_device()
480 return False
479 return False
481 else:
480 else:
482 self.message = "ABS Beams List have been sent to ABS Modules"
481 self.message = "ABS Beams List have been sent to ABS Modules"
483 print('ABS beams list sent')
482 print('ABS beams list sent')
484 self.active_beam = beams[0].pk
483 self.active_beam = beams[0].pk
485
484
486 #Start DDS-RC-JARS
485 #Start DDS-RC-JARS
487 if confdds:
486 if confdds:
488 confdds.start_device()
487 confdds.start_device()
489 if confrc:
488 if confrc:
490 #print confrc
489 #print confrc
491 confrc.start_device()
490 confrc.start_device()
492 if confjars:
491 if confjars:
493 confjars.start_device()
492 confjars.start_device()
494
493
495 print('Inicia intento de salvar device.status')
494 print('Inicia intento de salvar device.status')
496 self.device.status = 3
495 self.device.status = 3
497 self.module_status = ''.join(status)
496 self.module_status = ''.join(status)
498 #print(status)
497 #print(status)
499 self.save()
498 self.save()
500 print('Estatus salvado')
499 print('Estatus salvado')
501 conf_active, __ = ABSActive.objects.get_or_create(pk=1)
500 conf_active, __ = ABSActive.objects.get_or_create(pk=1)
502 conf_active.conf = self
501 conf_active.conf = self
503 conf_active.save()
502 conf_active.save()
504 return True
503 return True
505
504
506 def write_device_mqtt(self):
505 def write_device_mqtt(self):
507
506
508 if self.experiment is None:
507 if self.experiment is None:
509 confs = []
508 confs = []
510 else:
509 else:
511 confs = Configuration.objects.filter(experiment = self.experiment).filter(type=0)
510 confs = Configuration.objects.filter(experiment = self.experiment).filter(type=0)
512 confdds = ''
511 confdds = ''
513 confjars = ''
512 confjars = ''
514 confrc = ''
513 confrc = ''
515 #TO STOP DEVICES: DDS-JARS-RC
514 #TO STOP DEVICES: DDS-JARS-RC
516 for i in range(0,len(confs)):
515 for i in range(0,len(confs)):
517 if i==0:
516 if i==0:
518 for conf in confs:
517 for conf in confs:
519 if conf.device.device_type.name == 'dds':
518 if conf.device.device_type.name == 'dds':
520 confdds = conf
519 confdds = conf
521 confdds.stop_device()
520 confdds.stop_device()
522 break
521 break
523 if i==1:
522 if i==1:
524 for conf in confs:
523 for conf in confs:
525 if conf.device.device_type.name == 'jars':
524 if conf.device.device_type.name == 'jars':
526 confjars = conf
525 confjars = conf
527 confjars.stop_device()
526 confjars.stop_device()
528 break
527 break
529 if i==2:
528 if i==2:
530 for conf in confs:
529 for conf in confs:
531 if conf.device.device_type.name == 'rc':
530 if conf.device.device_type.name == 'rc':
532 confrc = conf
531 confrc = conf
533 confrc.stop_device()
532 confrc.stop_device()
534 break
533 break
535
534
536 apuntes_up_down=''
535 apuntes_up_down=''
537 beams = ABSBeam.objects.filter(abs_conf=self)
536 beams = ABSBeam.objects.filter(abs_conf=self)
538
537
539 inicializacion="{\"beams\":["
538 inicializacion="{\"beams\":["
540 finalizacion="]}"
539 finalizacion="]}"
541
540
542 for beam in beams:
541 for beam in beams:
543 beam.antenna=beam.antenna[1:]
542 beam.antenna=beam.antenna[1:]
544 info="{\"id\":"+str(beam.id)+","+beam.antenna + ","
543 info="{\"id\":"+str(beam.id)+","+beam.antenna + ","
545 apuntes_up_down=apuntes_up_down+info
544 apuntes_up_down=apuntes_up_down+info
546
545
547 apuntes_up_down=apuntes_up_down[:len(apuntes_up_down)-1]
546 apuntes_up_down=apuntes_up_down[:len(apuntes_up_down)-1]
548 apuntes_up_down=inicializacion+ apuntes_up_down+finalizacion
547 apuntes_up_down=inicializacion+ apuntes_up_down+finalizacion
549 mqtt_client.publish(os.environ.get('TOPIC_ABS', 'abs/beams'),apuntes_up_down)
548 mqtt_client.publish(os.environ.get('TOPIC_ABS', 'abs/beams'),apuntes_up_down)
550
549
551 #Start DDS-RC-JARS
550 #Start DDS-RC-JARS
552 if confdds:
551 if confdds:
553 confdds.start_device()
552 confdds.start_device()
554 if confrc:
553 if confrc:
555 #print confrc
554 #print confrc
556 confrc.start_device()
555 confrc.start_device()
557 if confjars:
556 if confjars:
558 confjars.start_device()
557 confjars.start_device()
559
558
560 return True
559 return True
561
560
562 def read_module(self, module):
561 def read_module(self, module):
563
562
564 """
563 """
565 Read out-bits (up-down) of 1 abs module NOT for Configuration
564 Read out-bits (up-down) of 1 abs module NOT for Configuration
566 """
565 """
567
566
568 ip_address = self.device.ip_address
567 ip_address = self.device.ip_address
569 ip_address = ip_address.split('.')
568 ip_address = ip_address.split('.')
570 module_seq = (ip_address[0],ip_address[1],ip_address[2])
569 module_seq = (ip_address[0],ip_address[1],ip_address[2])
571 dot = '.'
570 dot = '.'
572 module_ip = dot.join(module_seq)+'.'+str(module)
571 module_ip = dot.join(module_seq)+'.'+str(module)
573 module_port = self.device.port_address
572 module_port = self.device.port_address
574 read_route = 'http://'+module_ip+':'+str(module_port)+'/read'
573 read_route = 'http://'+module_ip+':'+str(module_port)+'/read'
575
574
576 module_status = json.loads(self.module_status)
575 module_status = json.loads(self.module_status)
577 print(read_route)
576 print(read_route)
578
577
579 module_bits = ''
578 module_bits = ''
580
579
581 try:
580 try:
582 r_read = requests.get(read_route, timeout=0.5)
581 r_read = requests.get(read_route, timeout=0.5)
583 answer = r_read.json()
582 answer = r_read.json()
584 module_bits = answer['allbits']
583 module_bits = answer['allbits']
585 except:
584 except:
586 return {}
585 return {}
587
586
588 return module_bits
587 return module_bits
589
588
590 def read_device(self):
589 def read_device(self):
591
590
592 parms = {}
591 parms = {}
593 # Reads active modules.
592 # Reads active modules.
594 module_status = json.loads(self.module_status)
593 module_status = json.loads(self.module_status)
595 total = 0
594 total = 0
596 for status in module_status:
595 for status in module_status:
597 if module_status[status] != 0:
596 if module_status[status] != 0:
598 module_bits = self.read_module(int(status))
597 module_bits = self.read_module(int(status))
599 bits={}
598 bits={}
600 if module_bits:
599 if module_bits:
601 bits = (str(module_bits['um2']) + str(module_bits['um1']) + str(module_bits['um0']) +
600 bits = (str(module_bits['um2']) + str(module_bits['um1']) + str(module_bits['um0']) +
602 str(module_bits['dm2']) + str(module_bits['dm1']) + str(module_bits['dm0']) )
601 str(module_bits['dm2']) + str(module_bits['dm1']) + str(module_bits['dm0']) )
603 parms[str(status)] = bits
602 parms[str(status)] = bits
604
603
605 total +=1
604 total +=1
606
605
607 if total==0:
606 if total==0:
608 self.message = "No ABS Module detected. Please select 'Status'."
607 self.message = "No ABS Module detected. Please select 'Status'."
609 return False
608 return False
610
609
611
610
612
611
613 self.message = "ABS Modules have been read"
612 self.message = "ABS Modules have been read"
614 #monitoreo_tx = JROABSClnt_01CeCnMod000000MNTR10
613 #monitoreo_tx = JROABSClnt_01CeCnMod000000MNTR10
615 return parms
614 return parms
616
615
617
616
618 def connected_modules(self):
617 def connected_modules(self):
619 """
618 """
620 This function returns the number of connected abs-modules without updating.
619 This function returns the number of connected abs-modules without updating.
621 """
620 """
622 num = 0
621 num = 0
623 print(self.module_status)
622 print(self.module_status)
624 for i, status in enumerate(self.module_status):
623 for i, status in enumerate(self.module_status):
625 if status != '0':
624 if status != '0':
626 num += 1
625 num += 1
627 #print('status {}:{}'.format(i+1, status))
626 #print('status {}:{}'.format(i+1, status))
628 return num
627 return num
629
628
630 def send_multicast(self, message):
629 def send_multicast(self, message):
631 #print("Send multicast")
630 #print("Send multicast")
632 multicast_group = ('224.3.29.71', 10000)
631 multicast_group = ('224.3.29.71', 10000)
633 # Create the datagram socket
632 # Create the datagram socket
634 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
633 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
635 sock.settimeout(1)
634 sock.settimeout(1)
636 local_ip = os.environ.get('LOCAL_IP', '0.0.0.0')
635 local_ip = os.environ.get('LOCAL_IP', '0.0.0.0')
637 local_ip = '0.0.0.0'
636 local_ip = '0.0.0.0'
638 print("He llegado a IP local")
637 print("He llegado a IP local")
639
638
640 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(local_ip))
639 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(local_ip))
641 sock.sendto(message.encode(), multicast_group)
640 sock.sendto(message.encode(), multicast_group)
642 print('Sending ' + message)
641 print('Sending ' + message)
643 return sock
642 return sock
644
643
645 def status_device(self):
644 def status_device(self):
646 """
645 """
647 This function returns the status of all abs-modules as one.
646 This function returns the status of all abs-modules as one.
648 If at least one module is connected, its answer is "1"
647 If at least one module is connected, its answer is "1"
649 """
648 """
650 print ('Status device')
649 print ('Status device')
651 print (self.active_beam)
650 print (self.active_beam)
652 beams = ABSBeam.objects.filter(abs_conf=self)
651 beams = ABSBeam.objects.filter(abs_conf=self)
653 #print beams[self.active_beam-1].module_6bits(0)
652 #print beams[self.active_beam-1].module_6bits(0)
654 active = ABSActive.objects.get(pk=1)
653 active = ABSActive.objects.get(pk=1)
655 if active.conf != self:
654 if active.conf != self:
656 self.message = 'La configuracion actual es la del siguiente enlace %s.' % active.conf.get_absolute_url()
655 self.message = 'La configuracion actual es la del siguiente enlace %s.' % active.conf.get_absolute_url()
657 self.message += "\n"
656 self.message += "\n"
658 self.message += 'Se debe realizar un write en esta configuracion para luego obtener un status valido.'
657 self.message += 'Se debe realizar un write en esta configuracion para luego obtener un status valido.'
659
658
660 return False
659 return False
661
660
662 sock = self.send_multicast('MNTR')
661 sock = self.send_multicast('MNTR')
663
662
664 n = 0
663 n = 0
665 status = ['0'] * 64
664 status = ['0'] * 64
666
665
667 while True:
666 while True:
668 #for i in range(32):
667 #for i in range(32):
669 #if True:
668 #if True:
670 try:
669 try:
671 print("Recibiendo")
670 print("Recibiendo")
672 address = None
671 address = None
673 data, address = sock.recvfrom(2)
672 data, address = sock.recvfrom(2)
674 print (address, data)
673 print (address, data)
675 print("!!!!")
674 print("!!!!")
676 data = data.decode()
675 data = data.decode()
677 aux_mon = "1"
676 aux_mon = "1"
678 aux_expected = aux_mon
677 aux_expected = aux_mon
679 if(len(data)==2):
678 if(len(data)==2):
680 print ("data[1]: ")
679 print ("data[1]: ")
681 print (data[1])
680 print (data[1])
682 aux_mon = fromChar2Binary(data[1])
681 aux_mon = fromChar2Binary(data[1])
683 print (aux_mon)
682 print (aux_mon)
684 aux_i = (str(address[0]).split('.'))[3]
683 aux_i = (str(address[0]).split('.'))[3]
685 print (aux_i)
684 print (aux_i)
686 print ('Active beam')
685 print ('Active beam')
687 beam_active = ABSBeam.objects.get(pk=self.active_beam)
686 beam_active = ABSBeam.objects.get(pk=self.active_beam)
688 print (beam_active)
687 print (beam_active)
689 aux_expected = beam_active.module_6bits(int(aux_i)-1)
688 aux_expected = beam_active.module_6bits(int(aux_i)-1)
690 print (aux_expected)
689 print (aux_expected)
691
690
692 print ("data[0]: ")
691 print ("data[0]: ")
693 print (data[0])
692 print (data[0])
694
693
695 if data[0] == '1':
694 if data[0] == '1':
696 status[int(address[0][10:])-1] = '3'
695 status[int(address[0][10:])-1] = '3'
697 if aux_mon == aux_expected:
696 if aux_mon == aux_expected:
698 print ('Es igual')
697 print ('Es igual')
699 else:
698 else:
700 print ('Es diferente')
699 print ('Es diferente')
701 status[int(address[0][10:])-1] = '2'
700 status[int(address[0][10:])-1] = '2'
702
701
703 elif data[0] == '0':
702 elif data[0] == '0':
704 status[int(address[0][10:])-1] = '1'
703 status[int(address[0][10:])-1] = '1'
705 n += 1
704 n += 1
706 print('Module: {} connected'.format(address))
705 print('Module: {} connected'.format(address))
707 except socket.timeout:
706 except socket.timeout:
708 print('Timeout')
707 print('Timeout')
709 break
708 break
710 except:
709 except:
711 print('Module: {} error'.format(address))
710 print('Module: {} error'.format(address))
712 pass
711 pass
713
712
714 sock.close()
713 sock.close()
715
714
716 if n > 0:
715 if n > 0:
717 self.message = 'ABS modules Status have been updated.'
716 self.message = 'ABS modules Status have been updated.'
718 self.device.status = 1
717 self.device.status = 1
719 else:
718 else:
720 self.device.status = 0
719 self.device.status = 0
721 self.message = 'No ABS module is connected.'
720 self.message = 'No ABS module is connected.'
722 self.module_status = ''.join(status)
721 self.module_status = ''.join(status)
723 self.save()
722 self.save()
724
723
725 return self.device.status
724 return self.device.status
726
725
727
726
728 def send_beam(self, beam_pos):
727 def send_beam(self, beam_pos):
729 """
728 """
730 This function connects to a multicast group and sends the beam number
729 This function connects to a multicast group and sends the beam number
731 to all abs modules.
730 to all abs modules.
732 """
731 """
733 print ('Send beam')
732 print ('Send beam')
734 print (self.active_beam)
733 print (self.active_beam)
735 beams = ABSBeam.objects.filter(abs_conf=self)
734 beams = ABSBeam.objects.filter(abs_conf=self)
736 #print beams[self.active_beam-1].module_6bits(0)
735 #print beams[self.active_beam-1].module_6bits(0)
737 active = ABSActive.objects.get(pk=1)
736 active = ABSActive.objects.get(pk=1)
738 if active.conf != self:
737 if active.conf != self:
739 self.message = 'La configuracion actual es la del siguiente enlace %s.' % active.conf.get_absolute_url()
738 self.message = 'La configuracion actual es la del siguiente enlace %s.' % active.conf.get_absolute_url()
740 self.message += "\n"
739 self.message += "\n"
741 self.message += 'Se debe realizar un write en esta configuracion para luego obtener un status valido.'
740 self.message += 'Se debe realizar un write en esta configuracion para luego obtener un status valido.'
742
741
743 return False
742 return False
744
743
745 # Se manda a cero RC para poder realizar cambio de beam
744 # Se manda a cero RC para poder realizar cambio de beam
746 if self.experiment is None:
745 if self.experiment is None:
747 confs = []
746 confs = []
748 else:
747 else:
749 confs = Configuration.objects.filter(experiment = self.experiment).filter(type=0)
748 confs = Configuration.objects.filter(experiment = self.experiment).filter(type=0)
750 confdds = ''
749 confdds = ''
751 confjars = ''
750 confjars = ''
752 confrc = ''
751 confrc = ''
753 #TO STOP DEVICES: DDS-JARS-RC
752 #TO STOP DEVICES: DDS-JARS-RC
754 for i in range(0,len(confs)):
753 for i in range(0,len(confs)):
755 if i==0:
754 if i==0:
756 for conf in confs:
755 for conf in confs:
757 if conf.device.device_type.name == 'dds':
756 if conf.device.device_type.name == 'dds':
758 confdds = conf
757 confdds = conf
759 confdds.stop_device()
758 confdds.stop_device()
760 break
759 break
761 if i==1:
760 if i==1:
762 for conf in confs:
761 for conf in confs:
763 if conf.device.device_type.name == 'jars':
762 if conf.device.device_type.name == 'jars':
764 confjars = conf
763 confjars = conf
765 confjars.stop_device()
764 confjars.stop_device()
766 break
765 break
767 if i==2:
766 if i==2:
768 for conf in confs:
767 for conf in confs:
769 if conf.device.device_type.name == 'rc':
768 if conf.device.device_type.name == 'rc':
770 confrc = conf
769 confrc = conf
771 confrc.stop_device()
770 confrc.stop_device()
772 break
771 break
773 if beam_pos > 0:
772 if beam_pos > 0:
774 beam_pos = beam_pos - 1
773 beam_pos = beam_pos - 1
775 else:
774 else:
776 beam_pos = 0
775 beam_pos = 0
777
776
778 #El indice del apunte debe ser menor que el numero total de apuntes
777 #El indice del apunte debe ser menor que el numero total de apuntes
779 #El servidor tcp en el embebido comienza a contar desde 0
778 #El servidor tcp en el embebido comienza a contar desde 0
780 status = ['0'] * 64
779 status = ['0'] * 64
781 message = 'CHGB{}'.format(beam_pos)
780 message = 'CHGB{}'.format(beam_pos)
782 sock = self.send_multicast(message)
781 sock = self.send_multicast(message)
783 while True:
782 while True:
784 #for i in range(32):
783 #for i in range(32):
785 try:
784 try:
786 data, address = sock.recvfrom(1024)
785 data, address = sock.recvfrom(1024)
787 print (address, data)
786 print (address, data)
788 data = data.decode()
787 data = data.decode()
789 if data == '1':
788 if data == '1':
790 status[int(address[0][10:])-1] = '3'
789 status[int(address[0][10:])-1] = '3'
791 elif data == '0':
790 elif data == '0':
792 status[int(address[0][10:])-1] = '1'
791 status[int(address[0][10:])-1] = '1'
793 except socket.timeout:
792 except socket.timeout:
794 print('Timeout')
793 print('Timeout')
795 break
794 break
796 except Exception as e:
795 except Exception as e:
797 print ('Error {}'.format(e))
796 print ('Error {}'.format(e))
798 pass
797 pass
799
798
800 sock.close()
799 sock.close()
801
800
802 #Start DDS-RC-JARS
801 #Start DDS-RC-JARS
803 if confdds:
802 if confdds:
804 confdds.start_device()
803 confdds.start_device()
805 if confrc:
804 if confrc:
806 #print confrc
805 #print confrc
807 confrc.start_device()
806 confrc.start_device()
808 if confjars:
807 if confjars:
809 confjars.start_device()
808 confjars.start_device()
810
809
811 self.message = "ABS Beam has been changed"
810 self.message = "ABS Beam has been changed"
812 self.module_status = ''.join(status)
811 self.module_status = ''.join(status)
813 self.save()
812 self.save()
814 return True
813 return True
815
814
816
815
817 def get_absolute_url_import(self):
816 def get_absolute_url_import(self):
818 return reverse('url_import_abs_conf', args=[str(self.id)])
817 return reverse('url_import_abs_conf', args=[str(self.id)])
819
818
820 class ABSActive(models.Model):
819 class ABSActive(models.Model):
821 conf = models.ForeignKey(ABSConfiguration, null=True, verbose_name='ABS Configuration', on_delete=models.CASCADE)
820 conf = models.ForeignKey(ABSConfiguration, null=True, verbose_name='ABS Configuration', on_delete=models.CASCADE)
822
821
823 class Meta:
822 class Meta:
824 db_table = 'abs_absactive'
823 db_table = 'abs_absactive'
825
824
826 class ABSBeam(models.Model):
825 class ABSBeam(models.Model):
827
826
828 name = models.CharField(max_length=60, default='Beam')
827 name = models.CharField(max_length=60, default='Beam')
829 antenna = models.CharField(verbose_name='Antenna', max_length=1000, default=antenna_default)
828 antenna = models.CharField(verbose_name='Antenna', max_length=1000, default=antenna_default)
830 abs_conf = models.ForeignKey('ABSConfiguration', null=True,
829 abs_conf = models.ForeignKey('ABSConfiguration', null=True,
831 verbose_name='ABS Configuration', on_delete=models.CASCADE)
830 verbose_name='ABS Configuration', on_delete=models.CASCADE)
832 tx = models.CharField(verbose_name='Tx', max_length=1000, default=tx_default)
831 tx = models.CharField(verbose_name='Tx', max_length=1000, default=tx_default)
833 rx = models.CharField(verbose_name='Rx', max_length=1000, default=rx_default)
832 rx = models.CharField(verbose_name='Rx', max_length=1000, default=rx_default)
834 s_time = models.TimeField(verbose_name='Star Time', default='00:00:00')
833 s_time = models.TimeField(verbose_name='Star Time', default='00:00:00')
835 e_time = models.TimeField(verbose_name='End Time', default='23:59:59')
834 e_time = models.TimeField(verbose_name='End Time', default='23:59:59')
836 ues = models.CharField(verbose_name='Ues', max_length=100, default=ues_default)
835 ues = models.CharField(verbose_name='Ues', max_length=100, default=ues_default)
837 only_rx = models.CharField(verbose_name='Only RX', max_length=40, default=onlyrx_default)
836 only_rx = models.CharField(verbose_name='Only RX', max_length=40, default=onlyrx_default)
838
837
839 class Meta:
838 class Meta:
840 db_table = 'abs_beams'
839 db_table = 'abs_beams'
841
840
842 def __unicode__(self):
841 def __unicode__(self):
843 return u'%s' % (self.name)
842 return u'%s' % (self.name)
844
843
845 def parms_to_dict(self):
844 def parms_to_dict(self):
846
845
847 parameters = {}
846 parameters = {}
848 parameters['name'] = self.name
847 parameters['name'] = self.name
849 parameters['antenna'] = ast.literal_eval(self.antenna)
848 parameters['antenna'] = ast.literal_eval(self.antenna)
850 parameters['abs_conf'] = self.abs_conf.name
849 parameters['abs_conf'] = self.abs_conf.name
851 parameters['tx'] = ast.literal_eval(self.tx)
850 parameters['tx'] = ast.literal_eval(self.tx)
852 parameters['rx'] = ast.literal_eval(self.rx)
851 parameters['rx'] = ast.literal_eval(self.rx)
853 parameters['s_time'] = self.s_time.strftime("%H:%M:%S")
852 parameters['s_time'] = self.s_time.strftime("%H:%M:%S")
854 parameters['e_time'] = self.e_time.strftime("%H:%M:%S")
853 parameters['e_time'] = self.e_time.strftime("%H:%M:%S")
855 parameters['ues'] = ast.literal_eval(self.ues)
854 parameters['ues'] = ast.literal_eval(self.ues)
856 parameters['only_rx'] = json.loads(self.only_rx)
855 parameters['only_rx'] = json.loads(self.only_rx)
857
856
858 return parameters
857 return parameters
859
858
860 def dict_to_parms(self, parameters):
859 def dict_to_parms(self, parameters):
861
860
862 self.name = parameters['name']
861 self.name = parameters['name']
863 self.antenna = json.dumps(parameters['antenna'])
862 self.antenna = json.dumps(parameters['antenna'])
864 #self.abs_conf = parameters['abs_conf']
863 #self.abs_conf = parameters['abs_conf']
865 self.tx = json.dumps(parameters['tx'])
864 self.tx = json.dumps(parameters['tx'])
866 self.rx = json.dumps(parameters['rx'])
865 self.rx = json.dumps(parameters['rx'])
867 #self.s_time = parameters['s_time']
866 #self.s_time = parameters['s_time']
868 #self.e_time = parameters['e_time']
867 #self.e_time = parameters['e_time']
869 self.ues = json.dumps(parameters['ues'])
868 self.ues = json.dumps(parameters['ues'])
870 self.only_rx = json.dumps(parameters['only_rx'])
869 self.only_rx = json.dumps(parameters['only_rx'])
871 self.save()
870 self.save()
872
871
873
872
874 def clone(self, **kwargs):
873 def clone(self, **kwargs):
875
874
876 self.pk = None
875 self.pk = None
877 self.id = None
876 self.id = None
878 for attr, value in kwargs.items():
877 for attr, value in kwargs.items():
879 setattr(self, attr, value)
878 setattr(self, attr, value)
880
879
881 self.save()
880 self.save()
882
881
883 return self
882 return self
884
883
885
884
886 def module_6bits(self, module):
885 def module_6bits(self, module):
887 """
886 """
888 This function reads antenna pattern and choose 6bits (upbits-downbits) for one abs module
887 This function reads antenna pattern and choose 6bits (upbits-downbits) for one abs module
889 """
888 """
890 module += 1
889 module += 1
891 if module > 64:
890 if module > 64:
892 beam_bits = ""
891 beam_bits = ""
893 return beam_bits
892 return beam_bits
894
893
895 data = ast.literal_eval(self.antenna)
894 data = ast.literal_eval(self.antenna)
896 up_data = data['antenna_up']
895 up_data = data['antenna_up']
897 down_data = data['antenna_down']
896 down_data = data['antenna_down']
898
897
899 pos = ip2position(module)
898 pos = ip2position(module)
900 up_value = up_data[pos[0]][pos[1]]
899 up_value = up_data[pos[0]][pos[1]]
901 down_value = down_data[pos[0]][pos[1]]
900 down_value = down_data[pos[0]][pos[1]]
902
901
903 up_bits = up_conv_bits(up_value)
902 up_bits = up_conv_bits(up_value)
904 down_bits = down_conv_bits(down_value)
903 down_bits = down_conv_bits(down_value)
905 beam_bits = up_bits+down_bits
904 beam_bits = up_bits+down_bits
906
905
907 return beam_bits
906 return beam_bits
908
907
909
908
910 @property
909 @property
911 def get_upvalues(self):
910 def get_upvalues(self):
912 """
911 """
913 This function reads antenna pattern and show the up-value of one abs module
912 This function reads antenna pattern and show the up-value of one abs module
914 """
913 """
915
914
916 data = ast.literal_eval(self.antenna)
915 data = ast.literal_eval(self.antenna)
917 up_data = data['antenna_up']
916 up_data = data['antenna_up']
918
917
919 up_values = []
918 up_values = []
920 for data in up_data:
919 for data in up_data:
921 for i in range(0,8):
920 for i in range(0,8):
922 up_values.append(data[i])
921 up_values.append(data[i])
923
922
924 return up_values
923 return up_values
925
924
926 @property
925 @property
927 def antenna_upvalues(self):
926 def antenna_upvalues(self):
928 """
927 """
929 This function reads antenna pattern and show the up - values of one abs beam
928 This function reads antenna pattern and show the up - values of one abs beam
930 in a particular order
929 in a particular order
931 """
930 """
932 data = ast.literal_eval(self.antenna)
931 data = ast.literal_eval(self.antenna)
933 up_data = data['antenna_up']
932 up_data = data['antenna_up']
934
933
935 return up_data
934 return up_data
936
935
937 @property
936 @property
938 def antenna_downvalues(self):
937 def antenna_downvalues(self):
939 """
938 """
940 This function reads antenna pattern and show the down - values of one abs beam
939 This function reads antenna pattern and show the down - values of one abs beam
941 in a particular order
940 in a particular order
942 """
941 """
943 data = ast.literal_eval(self.antenna)
942 data = ast.literal_eval(self.antenna)
944 down_data = data['antenna_down']
943 down_data = data['antenna_down']
945
944
946 return down_data
945 return down_data
947
946
948 @property
947 @property
949 def get_downvalues(self):
948 def get_downvalues(self):
950 """
949 """
951 This function reads antenna pattern and show the down-value of one abs module
950 This function reads antenna pattern and show the down-value of one abs module
952 """
951 """
953
952
954 data = ast.literal_eval(self.antenna)
953 data = ast.literal_eval(self.antenna)
955 down_data = data['antenna_down']
954 down_data = data['antenna_down']
956
955
957 down_values = []
956 down_values = []
958 for data in down_data:
957 for data in down_data:
959 for i in range(0,8):
958 for i in range(0,8):
960 down_values.append(data[i])
959 down_values.append(data[i])
961
960
962 return down_values
961 return down_values
963
962
964 @property
963 @property
965 def get_up_ues(self):
964 def get_up_ues(self):
966 """
965 """
967 This function shows the up-ues-value of one beam
966 This function shows the up-ues-value of one beam
968 """
967 """
969 data = ast.literal_eval(self.ues)
968 data = ast.literal_eval(self.ues)
970 up_ues = data['up']
969 up_ues = data['up']
971
970
972 return up_ues
971 return up_ues
973
972
974 @property
973 @property
975 def get_down_ues(self):
974 def get_down_ues(self):
976 """
975 """
977 This function shows the down-ues-value of one beam
976 This function shows the down-ues-value of one beam
978 """
977 """
979 data = ast.literal_eval(self.ues)
978 data = ast.literal_eval(self.ues)
980 down_ues = data['down']
979 down_ues = data['down']
981
980
982 return down_ues
981 return down_ues
983
982
984 @property
983 @property
985 def get_up_onlyrx(self):
984 def get_up_onlyrx(self):
986 """
985 """
987 This function shows the up-onlyrx-value of one beam
986 This function shows the up-onlyrx-value of one beam
988 """
987 """
989 data = json.loads(self.only_rx)
988 data = json.loads(self.only_rx)
990 up_onlyrx = data['up']
989 up_onlyrx = data['up']
991
990
992 return up_onlyrx
991 return up_onlyrx
993
992
994 @property
993 @property
995 def get_down_onlyrx(self):
994 def get_down_onlyrx(self):
996 """
995 """
997 This function shows the down-onlyrx-value of one beam
996 This function shows the down-onlyrx-value of one beam
998 """
997 """
999 data = json.loads(self.only_rx)
998 data = json.loads(self.only_rx)
1000 down_onlyrx = data['down']
999 down_onlyrx = data['down']
1001
1000
1002 return down_onlyrx
1001 return down_onlyrx
1003
1002
1004 @property
1003 @property
1005 def get_tx(self):
1004 def get_tx(self):
1006 """
1005 """
1007 This function shows the tx-values of one beam
1006 This function shows the tx-values of one beam
1008 """
1007 """
1009 data = json.loads(self.tx)
1008 data = json.loads(self.tx)
1010
1009
1011 return data
1010 return data
1012
1011
1013 @property
1012 @property
1014 def get_uptx(self):
1013 def get_uptx(self):
1015 """
1014 """
1016 This function shows the up-tx-values of one beam
1015 This function shows the up-tx-values of one beam
1017 """
1016 """
1018 data = json.loads(self.tx)
1017 data = json.loads(self.tx)
1019 up_data = data['up']
1018 up_data = data['up']
1020
1019
1021 up_values = []
1020 up_values = []
1022 for data in up_data:
1021 for data in up_data:
1023 for i in range(0,8):
1022 for i in range(0,8):
1024 up_values.append(data[i])
1023 up_values.append(data[i])
1025
1024
1026 return up_values
1025 return up_values
1027
1026
1028 @property
1027 @property
1029 def get_downtx(self):
1028 def get_downtx(self):
1030 """
1029 """
1031 This function shows the down-tx-values of one beam
1030 This function shows the down-tx-values of one beam
1032 """
1031 """
1033 data = json.loads(self.tx)
1032 data = json.loads(self.tx)
1034 down_data = data['down']
1033 down_data = data['down']
1035
1034
1036 down_values = []
1035 down_values = []
1037 for data in down_data:
1036 for data in down_data:
1038 for i in range(0,8):
1037 for i in range(0,8):
1039 down_values.append(data[i])
1038 down_values.append(data[i])
1040
1039
1041 return down_values
1040 return down_values
1042
1041
1043
1042
1044
1043
1045 @property
1044 @property
1046 def get_rx(self):
1045 def get_rx(self):
1047 """
1046 """
1048 This function shows the rx-values of one beam
1047 This function shows the rx-values of one beam
1049 """
1048 """
1050 data = json.loads(self.rx)
1049 data = json.loads(self.rx)
1051
1050
1052 return data
1051 return data
1053
1052
1054 @property
1053 @property
1055 def get_uprx(self):
1054 def get_uprx(self):
1056 """
1055 """
1057 This function shows the up-rx-values of one beam
1056 This function shows the up-rx-values of one beam
1058 """
1057 """
1059 data = json.loads(self.rx)
1058 data = json.loads(self.rx)
1060 up_data = data['up']
1059 up_data = data['up']
1061
1060
1062 up_values = []
1061 up_values = []
1063 for data in up_data:
1062 for data in up_data:
1064 for i in range(0,8):
1063 for i in range(0,8):
1065 up_values.append(data[i])
1064 up_values.append(data[i])
1066
1065
1067 return up_values
1066 return up_values
1068
1067
1069 @property
1068 @property
1070 def get_downrx(self):
1069 def get_downrx(self):
1071 """
1070 """
1072 This function shows the down-rx-values of one beam
1071 This function shows the down-rx-values of one beam
1073 """
1072 """
1074 data = json.loads(self.rx)
1073 data = json.loads(self.rx)
1075 down_data = data['down']
1074 down_data = data['down']
1076
1075
1077 down_values = []
1076 down_values = []
1078 for data in down_data:
1077 for data in down_data:
1079 for i in range(0,8):
1078 for i in range(0,8):
1080 down_values.append(data[i])
1079 down_values.append(data[i])
1081
1080
1082 return down_values
1081 return down_values
@@ -1,103 +1,87
1 from django.core.management.base import BaseCommand
1 from django.core.management.base import BaseCommand
2 from apps.main.models import Campaign, Location
2 from apps.main.models import Campaign, Location
3 from datetime import datetime,timedelta
3 from datetime import datetime,timedelta
4 from apps.main.views import radar_start
4 from apps.main.views import radar_start
5 from django.shortcuts import render, redirect,get_object_or_404, HttpResponse
5 from django.shortcuts import render, redirect,get_object_or_404, HttpResponse
6 from django.urls import reverse
6 from django.urls import reverse
7 from django.utils.timezone import is_aware
7 from django.utils.timezone import is_aware
8 from django.contrib import messages
8 from django.contrib import messages
9 from django.http import HttpResponseRedirect
9 from django.http import HttpResponseRedirect
10 from apps.main.views import experiment_start
10 from apps.main.views import experiment_start
11 from apps.main.models import Experiment, Configuration
11 from apps.main.models import Experiment, Configuration
12
12
13 class Command(BaseCommand):
13 class Command(BaseCommand):
14 """
14 """
15 Restart experiment every night at 05:00 am.
15 Restart experiment every night at 05:00 am.
16 Example:
16 Example:
17 manage.py restart_experiment
17 manage.py restart_experiment
18 """
18 """
19 def handle(self, *args, **options):
19 def handle(self, *args, **options):
20 print("")
20 print("\n\n")
21 all_campaigns=Campaign.objects.all()
21 campaigns = Campaign.objects.filter(start_date__lte=datetime.now(),
22 campaigns = Campaign.objects.filter(start_date__lte=datetime.now(),
22 end_date__gte=datetime.now()).order_by('-start_date')
23 end_date__gte=datetime.now()).order_by('-start_date')
23
24
24 if campaigns:
25 for campaign in all_campaigns:
25
26 if campaign.start_date<datetime.now() and campaign.end_date > datetime.now():
26 for campaign in campaigns:
27 print(campaign.name)
28 print(campaign.start_date)
29 print(campaign.end_date)
30 print(campaign.experiments.all()[0].id)
31 print("STATUS: ",campaign.experiments.all()[0].status)
32
27
33 radar=campaign.get_experiments_by_radar(radar=None)
28 radar=campaign.get_experiments_by_radar(radar=None)
34 radar_id=radar[0]["id"]
29 for rad in radar:
35 print(radar_id)
30 # print("RADR", rad)
36
31 radar_id=rad["id"]
37 now = datetime.now()
32 # print("RADR_",radar_id)
38 if now<campaign.end_date and now >campaign.start_date:
39 print("La campaña",campaign.name ,"se ejecuta!",flush=True)
40 radar_start_scheduler(campaign.id,radar_id)
33 radar_start_scheduler(campaign.id,radar_id)
34 print(campaign.name, "\t\t Campaign already running")
41
35
42 else:
36 else:
43 copy_campaigns=Campaign.objects.all()
44 print("-------------Deteniendo procesos-------------")
45 for campaign in copy_campaigns:
46 print(campaign.name)
47 print(campaign.start_date)
48 print(campaign.end_date)
49 print("ID: ",campaign.experiments.all()[0].id)
50 print("STATUS: ",campaign.experiments.all()[0].status)
51 print("----,,,---")
52 radar=campaign.get_experiments_by_radar(radar=None)
37 radar=campaign.get_experiments_by_radar(radar=None)
53 radar_id=radar[0]["id"]
38 radar_id=radar[0]["id"]
54
55 if campaign.experiments.all()[0].status !=1:
39 if campaign.experiments.all()[0].status !=1:
56 print("Estoy en :",campaign.experiments.all()[0].status)
40 print(campaign.name, "\t\t Stopping Campaign...")
57 print("Con ID: ",campaign.experiments.all()[0].id)
58 print("\n\n")
59 a=radar_stop_scheduler(campaign.id,radar_id,campaign.experiments.all()[0].id)
41 a=radar_stop_scheduler(campaign.id,radar_id,campaign.experiments.all()[0].id)
60 print("RETURN", a)
42 print("New Status: ", a)
61
43 else:
44 print(campaign.name,"\t\t\t Campaign already stooped")
62
45
63 def radar_start_scheduler(id_camp,id_radar):
46 def radar_start_scheduler(id_camp,id_radar):
64 print("-------------------")
65 campaign = get_object_or_404(Campaign, pk=id_camp)
47 campaign = get_object_or_404(Campaign, pk=id_camp)
66 experiments = campaign.get_experiments_by_radar(id_radar)[0]['experiments']
48 experiments = campaign.get_experiments_by_radar(id_radar)[0]['experiments']
67 now = datetime.now()
49 now = datetime.now()
68
50 # print(campaign)
51 # print(experiments)
69 for exp in experiments:
52 for exp in experiments:
70 exp = get_object_or_404(Experiment, pk=exp.id)
53 exp = get_object_or_404(Experiment, pk=exp.id)
71
54 # print("---------DEBUGG-------------")
55 # print(exp)
72 if exp.status == 2:
56 if exp.status == 2:
73 print('Experiment {} already runnnig'.format(exp))
57 print('\t\t\t {} \t\t Experiment already runnnig'.format(exp))
74 else:
58 else:
75 exp.status = exp.start()
59 exp.status = exp.start()
76 if exp.status == 0:
60 if exp.status == 0:
77 print('Experiment {} not start'.format(exp))
61 print('\t\t\t {} \t\tExperiment not start'.format(exp))
78 if exp.status == 2:
62 if exp.status == 2:
79 print('Experiment {} started'.format(exp))
63 print('\t\t\t {} \t\tExperiment started'.format(exp))
64 if exp.status == 4:
65 print('\t\t\t {} \t\tExperiment with state uknown, please reset'.format(exp))
80 exp.save()
66 exp.save()
81
67
82 def radar_stop_scheduler(id_camp,id_radar,id_experiment):
68 def radar_stop_scheduler(id_camp,id_radar,id_experiment):
83 print("-------------------")
84 '''
69 '''
85 Stop experiments's devices
70 Stop experiments's devices
86 DDS-JARS-RC-CGS-ABS
71 DDS-JARS-RC-CGS-ABS
87 '''
72 '''
88 exp=get_object_or_404(Experiment,pk=id_experiment)
73 exp=get_object_or_404(Experiment,pk=id_experiment)
89
74
90 if exp.status == 2:
75 if exp.status == 2:
91 confs = Configuration.objects.filter(experiment=id_experiment,type = 0).order_by('device__device_type__sequence')
76 confs = Configuration.objects.filter(experiment=id_experiment,type = 0).order_by('device__device_type__sequence')
92 confs = confs.exclude(device__device_type__name='cgs')
77 confs = confs.exclude(device__device_type__name='cgs')
93 try:
78 try:
94 for conf in confs:
79 for conf in confs:
95 print("Estoy en conf_scheduler")
80 # print(conf)
96 print(conf)
97 conf.stop_device()
81 conf.stop_device()
98 exp.status= 1
82 exp.status= 1
99 except:
83 except:
100 exp.status= 0
84 exp.status= 0
101 exp.save()
85 exp.save()
102
86
103 return exp.status No newline at end of file
87 return exp.status
General Comments 0
You need to be logged in to leave comments. Login now