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