##// END OF EJS Templates
Actualizacion campos y correccion app abs 1sem Sep
gonzalesluisfrancisco -
r337:0cdf785c9933
parent child
Show More
@@ -1,7 +1,8
1 1 from django.contrib import admin
2 from .models import ABSConfiguration, ABSBeam
2 from .models import ABSConfiguration, ABSBeam, ABSActive
3 3
4 4 # Register your models here.
5 5
6 6 admin.site.register(ABSConfiguration)
7 7 admin.site.register(ABSBeam)
8 admin.site.register(ABSActive) No newline at end of file
@@ -1,996 +1,1005
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 antenna_default = json.dumps({
14 14 "antenna_up": [[0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
15 15 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
16 16 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
17 17 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
18 18 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0],
19 19 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0],
20 20 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0],
21 21 [0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0]
22 22 ]
23 23 ,
24 24 "antenna_down": [[0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
25 25 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
26 26 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
27 27 [0.0,0.0,0.0,0.0,0.5,0.5,0.5,0.5],
28 28 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0],
29 29 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0],
30 30 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0],
31 31 [0.5,0.5,0.5,0.5,3.0,3.0,3.0,3.0]],
32 32 })
33 33
34 34
35 35 tx_default = json.dumps({
36 36 "up": [[1,1,1,1,0,0,0,0],
37 37 [1,1,1,1,0,0,0,0],
38 38 [1,1,1,1,0,0,0,0],
39 39 [1,1,1,1,0,0,0,0],
40 40 [0,0,0,0,1,1,1,1],
41 41 [0,0,0,0,1,1,1,1],
42 42 [0,0,0,0,1,1,1,1],
43 43 [0,0,0,0,1,1,1,1]],
44 44
45 45 "down": [[1,1,1,1,0,0,0,0],
46 46 [1,1,1,1,0,0,0,0],
47 47 [1,1,1,1,0,0,0,0],
48 48 [1,1,1,1,0,0,0,0],
49 49 [0,0,0,0,1,1,1,1],
50 50 [0,0,0,0,1,1,1,1],
51 51 [0,0,0,0,1,1,1,1],
52 52 [0,0,0,0,1,1,1,1]],
53 53 })
54 54
55 55 rx_default = json.dumps({
56 56 "up": [[1,1,1,1,0,0,0,0],
57 57 [1,1,1,1,0,0,0,0],
58 58 [1,1,1,1,0,0,0,0],
59 59 [1,1,1,1,0,0,0,0],
60 60 [0,0,0,0,1,1,1,1],
61 61 [0,0,0,0,1,1,1,1],
62 62 [0,0,0,0,1,1,1,1],
63 63 [0,0,0,0,1,1,1,1]],
64 64
65 65 "down": [[1,1,1,1,0,0,0,0],
66 66 [1,1,1,1,0,0,0,0],
67 67 [1,1,1,1,0,0,0,0],
68 68 [1,1,1,1,0,0,0,0],
69 69 [0,0,0,0,1,1,1,1],
70 70 [0,0,0,0,1,1,1,1],
71 71 [0,0,0,0,1,1,1,1],
72 72 [0,0,0,0,1,1,1,1]],
73 73 })
74 74
75 75 status_default = '0000000000000000000000000000000000000000000000000000000000000000'
76 76 default_messages = {}
77 77
78 78 for i in range(1,65):
79 79 default_messages[str(i)] = "Module "+str(i)
80 80
81 81
82 82 ues_default = json.dumps({
83 83 "up": [0.533333,0.00000,1.06667,0.00000],
84 84 "down": [0.533333,0.00000,1.06667,0.00000]
85 85 })
86 86
87 87 onlyrx_default = json.dumps({
88 88 "up": False,
89 89 "down": False
90 90 })
91 91
92 92 def up_convertion(cadena):
93 93 valores = []
94 94 for c in cadena:
95 95 if c == 1.0: valores=valores+['000']
96 96 if c == 2.0: valores=valores+['001']
97 97 if c == 3.0: valores=valores+['010']
98 98 if c == 0.0: valores=valores+['011']
99 99 if c == 0.5: valores=valores+['100']
100 100 if c == 1.5: valores=valores+['101']
101 101 if c == 2.5: valores=valores+['110']
102 102 if c == 3.5: valores=valores+['111']
103 103
104 104 return valores
105 105
106 106 def up_conv_bits(value):
107 107
108 108 if value == 1.0: bits="000"
109 109 if value == 2.0: bits="001"
110 110 if value == 3.0: bits="010"
111 111 if value == 0.0: bits="011"
112 112 if value == 0.5: bits="100"
113 113 if value == 1.5: bits="101"
114 114 if value == 2.5: bits="110"
115 115 if value == 3.5: bits="111"
116 116
117 117 return bits
118 118
119 119 def down_convertion(cadena):
120 120 valores = []
121 121 for c in cadena:
122 122 if c == 1.0: valores=valores+['000']
123 123 if c == 2.0: valores=valores+['001']
124 124 if c == 3.0: valores=valores+['010']
125 125 if c == 0.0: valores=valores+['011']
126 126 if c == 0.5: valores=valores+['100']
127 127 if c == 1.5: valores=valores+['101']
128 128 if c == 2.5: valores=valores+['110']
129 129 if c == 3.5: valores=valores+['111']
130 130
131 131 return valores
132 132
133 133 def down_conv_bits(value):
134 134
135 135 if value == 1.0: bits="000"
136 136 if value == 2.0: bits="001"
137 137 if value == 3.0: bits="010"
138 138 if value == 0.0: bits="011"
139 139 if value == 0.5: bits="100"
140 140 if value == 1.5: bits="101"
141 141 if value == 2.5: bits="110"
142 142 if value == 3.5: bits="111"
143 143
144 144 return bits
145 145
146 146 def up_conv_value(bits):
147 147
148 148 if bits == "000": value=1.0
149 149 if bits == "001": value=2.0
150 150 if bits == "010": value=3.0
151 151 if bits == "011": value=0.0
152 152 if bits == "100": value=0.5
153 153 if bits == "101": value=1.5
154 154 if bits == "110": value=2.5
155 155 if bits == "111": value=3.5
156 156
157 157 return value
158 158
159 159 def down_conv_value(bits):
160 160
161 161 if bits == "000": value=1.0
162 162 if bits == "001": value=2.0
163 163 if bits == "010": value=3.0
164 164 if bits == "011": value=0.0
165 165 if bits == "100": value=0.5
166 166 if bits == "101": value=1.5
167 167 if bits == "110": value=2.5
168 168 if bits == "111": value=3.5
169 169
170 170 return value
171 171
172 172 def ip2position(module_number):
173 173 j=0
174 174 i=0
175 175 for x in range(0,module_number-1):
176 176 j=j+1
177 177 if j==8:
178 178 i=i+1
179 179 j=0
180 180
181 181 pos = [i,j]
182 182 return pos
183 183
184 184
185 185 def fromBinary2Char(binary_string):
186 186 number = int(binary_string, 2)
187 187 #Plus 33 to avoid more than 1 characters values such as: '\x01'-'\x1f'
188 188 number = number + 33
189 189 char = chr(number)
190 190 return char
191 191
192 192 def fromChar2Binary(char):
193 193 number = ord(char) - 33
194 194 #Minus 33 to get the real value
195 195 bits = bin(number)[2:]
196 196 #To ensure we have a string with 6bits
197 197 if len(bits) < 6:
198 198 bits = bits.zfill(6)
199 199 return bits
200 200
201 201 OPERATION_MODES = (
202 202 (0, 'Manual'),
203 203 (1, 'Automatic'),
204 204 )
205 205
206 206 class ABSConfiguration(Configuration):
207 207 active_beam = models.PositiveSmallIntegerField(verbose_name='Active Beam', default=0)
208 208 module_status = models.CharField(verbose_name='Module Status', max_length=10000, default=status_default)
209 209 operation_mode = models.PositiveSmallIntegerField(verbose_name='Operation Mode', choices=OPERATION_MODES, default = 0)
210 210 operation_value = models.FloatField(verbose_name='Periodic (seconds)', default="10", null=True, blank=True)
211 211 module_messages = models.CharField(verbose_name='Modules Messages', max_length=10000, default=json.dumps(default_messages))
212 212
213 213 class Meta:
214 214 db_table = 'abs_configurations'
215 215
216 216 def get_absolute_url_plot(self):
217 217 return reverse('url_plot_abs_patterns', args=[str(self.id)])
218 218
219 219
220 220 def parms_to_dict(self):
221 221
222 222 parameters = {}
223 223
224 224 parameters['device_id'] = self.device.id
225 225 parameters['label'] = self.label
226 226 parameters['device_type'] = self.device.device_type.name
227 227 parameters['beams'] = {}
228 228
229 229 beams = ABSBeam.objects.filter(abs_conf=self)
230 230 b=1
231 231 for beam in beams:
232 232 #absbeam = ABSBeam.objects.get(pk=beams[beam])
233 233 parameters['beams']['beam'+str(b)] = beam.parms_to_dict()#absbeam.parms_to_dict()
234 234 b+=1
235 235
236 236 return parameters
237 237
238 238
239 239 def dict_to_parms(self, parameters):
240 240
241 241 self.label = parameters['label']
242 242
243 243 absbeams = ABSBeam.objects.filter(abs_conf=self)
244 244 beams = parameters['beams']
245 245
246 246 if absbeams:
247 247 beams_number = len(beams)
248 248 absbeams_number = len(absbeams)
249 249 if beams_number==absbeams_number:
250 250 i = 1
251 251 for absbeam in absbeams:
252 252 absbeam.dict_to_parms(beams['beam'+str(i)])
253 253 i = i+1
254 254 elif beams_number > absbeams_number:
255 255 i = 1
256 256 for absbeam in absbeams:
257 257 absbeam.dict_to_parms(beams['beam'+str(i)])
258 258 i=i+1
259 259 for x in range(i,beams_number+1):
260 260 new_beam = ABSBeam(
261 261 name =beams['beam'+str(i)]['name'],
262 262 antenna =json.dumps(beams['beam'+str(i)]['antenna']),
263 263 abs_conf = self,
264 264 tx =json.dumps(beams['beam'+str(i)]['tx']),
265 265 rx =json.dumps(beams['beam'+str(i)]['rx']),
266 266 ues =json.dumps(beams['beam'+str(i)]['ues']),
267 267 only_rx =json.dumps(beams['beam'+str(i)]['only_rx'])
268 268 )
269 269 new_beam.save()
270 270 i=i+1
271 271 else: #beams_number < absbeams_number:
272 272 i = 1
273 273 for absbeam in absbeams:
274 274 if i <= beams_number:
275 275 absbeam.dict_to_parms(beams['beam'+str(i)])
276 276 i=i+1
277 277 else:
278 278 absbeam.delete()
279 279 else:
280 280 for beam in beams:
281 281 new_beam = ABSBeam(
282 282 name =beams[beam]['name'],
283 283 antenna =json.dumps(beams[beam]['antenna']),
284 284 abs_conf = self,
285 285 tx =json.dumps(beams[beam]['tx']),
286 286 rx =json.dumps(beams[beam]['rx']),
287 287 ues =json.dumps(beams[beam]['ues']),
288 288 only_rx =json.dumps(beams[beam]['only_rx'])
289 289 )
290 290 new_beam.save()
291 291
292 292
293 293
294 294 def update_from_file(self, parameters):
295 295
296 296 self.dict_to_parms(parameters)
297 297 self.save()
298 298
299 299
300 300 def get_beams(self, **kwargs):
301 301 '''
302 302 This function returns ABS Configuration beams
303 303 '''
304 304 return ABSBeam.objects.filter(abs_conf=self.pk, **kwargs)
305 305
306 306 def clone(self, **kwargs):
307 307
308 308 beams = self.get_beams()
309 309 self.pk = None
310 310 self.id = None
311 311 for attr, value in kwargs.items():
312 312 setattr(self, attr, value)
313 313 self.save()
314 314
315 315 for beam in beams:
316 316 beam.clone(abs_conf=self)
317 317
318 318 #-----For Active Beam-----
319 319 new_beams = ABSBeam.objects.filter(abs_conf=self)
320 320 self.active_beam = new_beams[0].id
321 321 self.save()
322 322 #-----For Active Beam-----
323 323 #-----For Device Status---
324 324 self.device.status = 3
325 325 self.device.save()
326 326 #-----For Device Status---
327 327
328 328 return self
329 329
330 330
331 331 def start_device(self):
332 332
333 333 if self.device.status == 3:
334 334
335 335 try:
336 336 #self.write_device()
337 337 send_task('task_change_beam', [self.id],)
338 338 self.message = 'ABS running'
339 339
340 340 except Exception as e:
341 341 self.message = str(e)
342 342 return False
343 343
344 344 return True
345 345
346 346 else:
347 347 self.message = 'Please, select Write ABS Device first.'
348 348 return False
349 349
350 350
351 351 def stop_device(self):
352 352
353 353 self.device.status = 2
354 354 self.device.save()
355 355 self.message = 'ABS has been stopped.'
356 356 self.save()
357 357
358 358 return True
359 359
360 360
361 361 def write_device(self):
362 362
363 363 """
364 364 This function sends the beams list to every abs module.
365 365 It needs 'module_conf' function
366 366 """
367 367 print("Write")
368 368 beams = ABSBeam.objects.filter(abs_conf=self)
369 369 nbeams = len(beams)
370 370
371 371 # Se manda a cero RC para poder realizar cambio de beam
372 372 if self.experiment is None:
373 373 confs = []
374 374 else:
375 375 confs = Configuration.objects.filter(experiment = self.experiment).filter(type=0)
376 376 confdds = ''
377 377 confjars = ''
378 378 confrc = ''
379 379 #TO STOP DEVICES: DDS-JARS-RC
380 380 for i in range(0,len(confs)):
381 381 if i==0:
382 382 for conf in confs:
383 383 if conf.device.device_type.name == 'dds':
384 384 confdds = conf
385 385 confdds.stop_device()
386 386 break
387 387 if i==1:
388 388 for conf in confs:
389 389 if conf.device.device_type.name == 'jars':
390 390 confjars = conf
391 391 confjars.stop_device()
392 392 break
393 393 if i==2:
394 394 for conf in confs:
395 395 if conf.device.device_type.name == 'rc':
396 396 confrc = conf
397 397 confrc.stop_device()
398 398 break
399 399
400 400 '''
401 401 if self.connected_modules() == 0 :
402 402 print("No encuentra modulos")
403 403 self.message = "No ABS Module detected."
404 404 return False
405 405 '''
406 406 #-------------Write each abs module-----------
407 407
408 408 if beams:
409 409 block_id = 0
410 410 message = 'SNDF{:03d}{:02d}{:02d}'.format(nbeams, nbeams, block_id)
411 411 for i, status in enumerate(self.module_status):
412 412 message += ''.join([fromBinary2Char(beam.module_6bits(i)) for beam in beams])
413 413 status = ['0'] * 64
414 414 n = 0
415 415 print("Llega una antes entrar a multicast")
416 416 sock = self.send_multicast(message)
417 417
418 418 while True:
419 419 #for i in range(32):
420 420 try:
421 421 data, address = sock.recvfrom(1024)
422 422 print (address, data)
423 423
424 424 if data == '1':
425 425 status[int(address[0][10:])-1] = '3'
426 426 elif data == '0':
427 427 status[int(address[0][10:])-1] = '1'
428 428 except socket.timeout:
429 429 print('Timeout')
430 430 break
431 431 except Exception as e:
432 432 print ('Error {}'.format(e))
433 433 n += 1
434 434 sock.close()
435 435 else:
436 436 self.message = "ABS Configuration does not have beams"
437 print('No beams')
437 438 #Start DDS-RC-JARS
438 439 if confdds:
439 440 confdds.start_device()
440 441 if confrc:
441 442 #print confrc
442 443 confrc.start_device()
443 444 if confjars:
444 445 confjars.start_device()
445 446 return False
446 447
447 448 if n == 64:
448 449 self.message = "Could not write ABS Modules"
449 450 self.device.status = 0
450 451 self.module_status = ''.join(status)
451 452 self.save()
453 print('Could not write ABS')
452 454 #Start DDS-RC-JARS
453 455 if confdds:
454 456 confdds.start_device()
455 457 if confrc:
456 458 #print confrc
457 459 confrc.start_device()
458 460 if confjars:
459 461 confjars.start_device()
460 462 return False
461 463 else:
462 464 self.message = "ABS Beams List have been sent to ABS Modules"
465 print('ABS beams list sent')
463 466 self.active_beam = beams[0].pk
464 467
465 468 #Start DDS-RC-JARS
466 469 if confdds:
467 470 confdds.start_device()
468 471 if confrc:
469 472 #print confrc
470 473 confrc.start_device()
471 474 if confjars:
472 475 confjars.start_device()
473 476
477 print('Inicia intento de salvar device.status')
474 478 self.device.status = 3
475 479 self.module_status = ''.join(status)
476 480 self.save()
477 conf_active = ABSActive.objects.get(pk=1)
481 print('Estatus salvado')
482 conf_active = ABSActive.objects.get_or_create(pk=1)
478 483 conf_active.conf = self
479 484 conf_active.save()
480 485 return True
481 486
482 487
483 488 def read_module(self, module):
484 489
485 490 """
486 491 Read out-bits (up-down) of 1 abs module NOT for Configuration
487 492 """
488 493
489 494 ip_address = self.device.ip_address
490 495 ip_address = ip_address.split('.')
491 496 module_seq = (ip_address[0],ip_address[1],ip_address[2])
492 497 dot = '.'
493 498 module_ip = dot.join(module_seq)+'.'+str(module)
494 499 module_port = self.device.port_address
495 500 read_route = 'http://'+module_ip+':'+str(module_port)+'/read'
496 501
497 502 module_status = json.loads(self.module_status)
498 503 print(read_route)
499 504
500 505 module_bits = ''
501 506
502 507 try:
503 508 r_read = requests.get(read_route, timeout=0.5)
504 509 answer = r_read.json()
505 510 module_bits = answer['allbits']
506 511 except:
507 512 return {}
508 513
509 514 return module_bits
510 515
511 516 def read_device(self):
512 517
513 518 parms = {}
514 519 # Reads active modules.
515 520 module_status = json.loads(self.module_status)
516 521 total = 0
517 522 for status in module_status:
518 523 if module_status[status] != 0:
519 524 module_bits = self.read_module(int(status))
520 525 bits={}
521 526 if module_bits:
522 527 bits = (str(module_bits['um2']) + str(module_bits['um1']) + str(module_bits['um0']) +
523 528 str(module_bits['dm2']) + str(module_bits['dm1']) + str(module_bits['dm0']) )
524 529 parms[str(status)] = bits
525 530
526 531 total +=1
527 532
528 533 if total==0:
529 534 self.message = "No ABS Module detected. Please select 'Status'."
530 535 return False
531 536
532 537
533 538
534 539 self.message = "ABS Modules have been read"
535 540 #monitoreo_tx = JROABSClnt_01CeCnMod000000MNTR10
536 541 return parms
537 542
538 543
539 544 def connected_modules(self):
540 545 """
541 546 This function returns the number of connected abs-modules without updating.
542 547 """
543 548 num = 0
544 549 print(self.module_status)
545 550 for i, status in enumerate(self.module_status):
546 551 if status != '0':
547 552 num += 1
548 553 #print('status {}:{}'.format(i+1, status))
549 554 return num
550 555
551 556 def send_multicast(self, message):
552 557 #print("Send multicast")
553 558 multicast_group = ('224.3.29.71', 10000)
554 559 # Create the datagram socket
555 560 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
556 561 sock.settimeout(1)
557 562 local_ip = os.environ.get('LOCAL_IP', '192.168.2.128')
558 563 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(local_ip))
559 564 sock.sendto(message.encode(), multicast_group)
560 565 print('Sending ' + message)
561 566 return sock
562 567
563 568 def status_device(self):
564 569 """
565 570 This function returns the status of all abs-modules as one.
566 571 If at least one module is connected, its answer is "1"
567 572 """
568 573 print ('Status device')
569 574 print (self.active_beam)
570 575 beams = ABSBeam.objects.filter(abs_conf=self)
571 576 #print beams[self.active_beam-1].module_6bits(0)
572 577 active = ABSActive.objects.get(pk=1)
573 578 if active.conf != self:
574 579 self.message = 'La configuracion actual es la del siguiente enlace %s.' % active.conf.get_absolute_url()
575 580 self.message += "\n"
576 581 self.message += 'Se debe realizar un write en esta configuracion para luego obtener un status valido.'
577 582
578 583 return False
579 584
580 585 sock = self.send_multicast('MNTR')
581 586
582 587 n = 0
583 588 status = ['0'] * 64
584 589
585 590 while True:
586 591 #for i in range(32):
587 592 #if True:
588 593 try:
589 594 print("Recibiendo")
590 595 address = None
591 596 data, address = sock.recvfrom(2)
592 597 print (address, data)
593 598 print("!!!!")
594 599 data = data.decode()
595 600 aux_mon = "1"
596 601 aux_expected = aux_mon
597 602 if(len(data)==2):
598 603 print ("data[1]: ")
599 604 print (data[1])
600 605 aux_mon = fromChar2Binary(data[1])
601 606 print (aux_mon)
602 607 aux_i = (str(address[0]).split('.'))[3]
603 608 print (aux_i)
604 609 print ('Active beam')
605 610 beam_active = ABSBeam.objects.get(pk=self.active_beam)
606 611 print (beam_active)
607 612 aux_expected = beam_active.module_6bits(int(aux_i)-1)
608 613 print (aux_expected)
609 614
610 615 print ("data[0]: ")
611 616 print (data[0])
612 617
613 618 if data[0] == '1':
614 619 status[int(address[0][10:])-1] = '3'
615 620 if aux_mon == aux_expected:
616 621 print ('Es igual')
617 622 else:
618 623 print ('Es diferente')
619 624 status[int(address[0][10:])-1] = '2'
620 625
621 626 elif data[0] == '0':
622 627 status[int(address[0][10:])-1] = '1'
623 628 n += 1
624 629 print('Module: {} connected'.format(address))
625 630 except socket.timeout:
626 631 print('Timeout')
627 632 break
628 633 except:
629 634 print('Module: {} error'.format(address))
630 635 pass
631 636
632 637 sock.close()
633 638
634 639 if n > 0:
635 640 self.message = 'ABS modules Status have been updated.'
636 641 self.device.status = 1
637 642 else:
638 643 self.device.status = 0
639 644 self.message = 'No ABS module is connected.'
640 645 self.module_status = ''.join(status)
641 646 self.save()
642 647
643 648 return self.device.status
644 649
645 650
646 651 def send_beam(self, beam_pos):
647 652 """
648 653 This function connects to a multicast group and sends the beam number
649 654 to all abs modules.
650 655 """
651 656 print ('Send beam')
652 657 print (self.active_beam)
653 658 beams = ABSBeam.objects.filter(abs_conf=self)
654 659 #print beams[self.active_beam-1].module_6bits(0)
655 660 active = ABSActive.objects.get(pk=1)
656 661 if active.conf != self:
657 662 self.message = 'La configuracion actual es la del siguiente enlace %s.' % active.conf.get_absolute_url()
658 663 self.message += "\n"
659 664 self.message += 'Se debe realizar un write en esta configuracion para luego obtener un status valido.'
660 665
661 666 return False
662 667
663 668 # Se manda a cero RC para poder realizar cambio de beam
664 669 if self.experiment is None:
665 670 confs = []
666 671 else:
667 672 confs = Configuration.objects.filter(experiment = self.experiment).filter(type=0)
668 673 confdds = ''
669 674 confjars = ''
670 675 confrc = ''
671 676 #TO STOP DEVICES: DDS-JARS-RC
672 677 for i in range(0,len(confs)):
673 678 if i==0:
674 679 for conf in confs:
675 680 if conf.device.device_type.name == 'dds':
676 681 confdds = conf
677 682 confdds.stop_device()
678 683 break
679 684 if i==1:
680 685 for conf in confs:
681 686 if conf.device.device_type.name == 'jars':
682 687 confjars = conf
683 688 confjars.stop_device()
684 689 break
685 690 if i==2:
686 691 for conf in confs:
687 692 if conf.device.device_type.name == 'rc':
688 693 confrc = conf
689 694 confrc.stop_device()
690 695 break
691 696 if beam_pos > 0:
692 697 beam_pos = beam_pos - 1
693 698 else:
694 699 beam_pos = 0
695 700
696 701 #El indice del apunte debe ser menor que el numero total de apuntes
697 702 #El servidor tcp en el embebido comienza a contar desde 0
698 703 status = ['0'] * 64
699 704 message = 'CHGB{}'.format(beam_pos)
700 705 sock = self.send_multicast(message)
701 706 while True:
702 707 #for i in range(32):
703 708 try:
704 709 data, address = sock.recvfrom(1024)
705 710 print (address, data)
706 711 data = data.decode()
707 712 if data == '1':
708 713 status[int(address[0][10:])-1] = '3'
709 714 elif data == '0':
710 715 status[int(address[0][10:])-1] = '1'
711 716 except socket.timeout:
712 717 print('Timeout')
713 718 break
714 719 except Exception as e:
715 720 print ('Error {}'.format(e))
716 721 pass
717 722
718 723 sock.close()
719 724
720 725 #Start DDS-RC-JARS
721 726 if confdds:
722 727 confdds.start_device()
723 728 if confrc:
724 729 #print confrc
725 730 confrc.start_device()
726 731 if confjars:
727 732 confjars.start_device()
728 733
729 734 self.message = "ABS Beam has been changed"
730 735 self.module_status = ''.join(status)
731 736 self.save()
732 737 return True
733 738
734 739
735 740 def get_absolute_url_import(self):
736 741 return reverse('url_import_abs_conf', args=[str(self.id)])
742
737 743 class ABSActive(models.Model):
738 744 conf = models.ForeignKey(ABSConfiguration, null=True, verbose_name='ABS Configuration', on_delete=models.CASCADE)
739 745
746 class Meta:
747 db_table = 'abs_absactive'
748
740 749 class ABSBeam(models.Model):
741 750
742 751 name = models.CharField(max_length=60, default='Beam')
743 752 antenna = models.CharField(verbose_name='Antenna', max_length=1000, default=antenna_default)
744 753 abs_conf = models.ForeignKey('ABSConfiguration', null=True,
745 754 verbose_name='ABS Configuration', on_delete=models.CASCADE)
746 755 tx = models.CharField(verbose_name='Tx', max_length=1000, default=tx_default)
747 756 rx = models.CharField(verbose_name='Rx', max_length=1000, default=rx_default)
748 757 s_time = models.TimeField(verbose_name='Star Time', default='00:00:00')
749 758 e_time = models.TimeField(verbose_name='End Time', default='23:59:59')
750 759 ues = models.CharField(verbose_name='Ues', max_length=100, default=ues_default)
751 760 only_rx = models.CharField(verbose_name='Only RX', max_length=40, default=onlyrx_default)
752 761
753 762 class Meta:
754 763 db_table = 'abs_beams'
755 764
756 765 def __unicode__(self):
757 766 return u'%s' % (self.name)
758 767
759 768 def parms_to_dict(self):
760 769
761 770 parameters = {}
762 771 parameters['name'] = self.name
763 772 parameters['antenna'] = ast.literal_eval(self.antenna)
764 773 parameters['abs_conf'] = self.abs_conf.name
765 774 parameters['tx'] = ast.literal_eval(self.tx)
766 775 parameters['rx'] = ast.literal_eval(self.rx)
767 776 parameters['s_time'] = self.s_time.strftime("%H:%M:%S")
768 777 parameters['e_time'] = self.e_time.strftime("%H:%M:%S")
769 778 parameters['ues'] = ast.literal_eval(self.ues)
770 779 parameters['only_rx'] = json.loads(self.only_rx)
771 780
772 781 return parameters
773 782
774 783 def dict_to_parms(self, parameters):
775 784
776 785 self.name = parameters['name']
777 786 self.antenna = json.dumps(parameters['antenna'])
778 787 #self.abs_conf = parameters['abs_conf']
779 788 self.tx = json.dumps(parameters['tx'])
780 789 self.rx = json.dumps(parameters['rx'])
781 790 #self.s_time = parameters['s_time']
782 791 #self.e_time = parameters['e_time']
783 792 self.ues = json.dumps(parameters['ues'])
784 793 self.only_rx = json.dumps(parameters['only_rx'])
785 794 self.save()
786 795
787 796
788 797 def clone(self, **kwargs):
789 798
790 799 self.pk = None
791 800 self.id = None
792 801 for attr, value in kwargs.items():
793 802 setattr(self, attr, value)
794 803
795 804 self.save()
796 805
797 806 return self
798 807
799 808
800 809 def module_6bits(self, module):
801 810 """
802 811 This function reads antenna pattern and choose 6bits (upbits-downbits) for one abs module
803 812 """
804 813 module += 1
805 814 if module > 64:
806 815 beam_bits = ""
807 816 return beam_bits
808 817
809 818 data = ast.literal_eval(self.antenna)
810 819 up_data = data['antenna_up']
811 820 down_data = data['antenna_down']
812 821
813 822 pos = ip2position(module)
814 823 up_value = up_data[pos[0]][pos[1]]
815 824 down_value = down_data[pos[0]][pos[1]]
816 825
817 826 up_bits = up_conv_bits(up_value)
818 827 down_bits = down_conv_bits(down_value)
819 828 beam_bits = up_bits+down_bits
820 829
821 830 return beam_bits
822 831
823 832
824 833 @property
825 834 def get_upvalues(self):
826 835 """
827 836 This function reads antenna pattern and show the up-value of one abs module
828 837 """
829 838
830 839 data = ast.literal_eval(self.antenna)
831 840 up_data = data['antenna_up']
832 841
833 842 up_values = []
834 843 for data in up_data:
835 844 for i in range(0,8):
836 845 up_values.append(data[i])
837 846
838 847 return up_values
839 848
840 849 @property
841 850 def antenna_upvalues(self):
842 851 """
843 852 This function reads antenna pattern and show the up - values of one abs beam
844 853 in a particular order
845 854 """
846 855 data = ast.literal_eval(self.antenna)
847 856 up_data = data['antenna_up']
848 857
849 858 return up_data
850 859
851 860 @property
852 861 def antenna_downvalues(self):
853 862 """
854 863 This function reads antenna pattern and show the down - values of one abs beam
855 864 in a particular order
856 865 """
857 866 data = ast.literal_eval(self.antenna)
858 867 down_data = data['antenna_down']
859 868
860 869 return down_data
861 870
862 871 @property
863 872 def get_downvalues(self):
864 873 """
865 874 This function reads antenna pattern and show the down-value of one abs module
866 875 """
867 876
868 877 data = ast.literal_eval(self.antenna)
869 878 down_data = data['antenna_down']
870 879
871 880 down_values = []
872 881 for data in down_data:
873 882 for i in range(0,8):
874 883 down_values.append(data[i])
875 884
876 885 return down_values
877 886
878 887 @property
879 888 def get_up_ues(self):
880 889 """
881 890 This function shows the up-ues-value of one beam
882 891 """
883 892 data = ast.literal_eval(self.ues)
884 893 up_ues = data['up']
885 894
886 895 return up_ues
887 896
888 897 @property
889 898 def get_down_ues(self):
890 899 """
891 900 This function shows the down-ues-value of one beam
892 901 """
893 902 data = ast.literal_eval(self.ues)
894 903 down_ues = data['down']
895 904
896 905 return down_ues
897 906
898 907 @property
899 908 def get_up_onlyrx(self):
900 909 """
901 910 This function shows the up-onlyrx-value of one beam
902 911 """
903 912 data = json.loads(self.only_rx)
904 913 up_onlyrx = data['up']
905 914
906 915 return up_onlyrx
907 916
908 917 @property
909 918 def get_down_onlyrx(self):
910 919 """
911 920 This function shows the down-onlyrx-value of one beam
912 921 """
913 922 data = json.loads(self.only_rx)
914 923 down_onlyrx = data['down']
915 924
916 925 return down_onlyrx
917 926
918 927 @property
919 928 def get_tx(self):
920 929 """
921 930 This function shows the tx-values of one beam
922 931 """
923 932 data = json.loads(self.tx)
924 933
925 934 return data
926 935
927 936 @property
928 937 def get_uptx(self):
929 938 """
930 939 This function shows the up-tx-values of one beam
931 940 """
932 941 data = json.loads(self.tx)
933 942 up_data = data['up']
934 943
935 944 up_values = []
936 945 for data in up_data:
937 946 for i in range(0,8):
938 947 up_values.append(data[i])
939 948
940 949 return up_values
941 950
942 951 @property
943 952 def get_downtx(self):
944 953 """
945 954 This function shows the down-tx-values of one beam
946 955 """
947 956 data = json.loads(self.tx)
948 957 down_data = data['down']
949 958
950 959 down_values = []
951 960 for data in down_data:
952 961 for i in range(0,8):
953 962 down_values.append(data[i])
954 963
955 964 return down_values
956 965
957 966
958 967
959 968 @property
960 969 def get_rx(self):
961 970 """
962 971 This function shows the rx-values of one beam
963 972 """
964 973 data = json.loads(self.rx)
965 974
966 975 return data
967 976
968 977 @property
969 978 def get_uprx(self):
970 979 """
971 980 This function shows the up-rx-values of one beam
972 981 """
973 982 data = json.loads(self.rx)
974 983 up_data = data['up']
975 984
976 985 up_values = []
977 986 for data in up_data:
978 987 for i in range(0,8):
979 988 up_values.append(data[i])
980 989
981 990 return up_values
982 991
983 992 @property
984 993 def get_downrx(self):
985 994 """
986 995 This function shows the down-rx-values of one beam
987 996 """
988 997 data = json.loads(self.rx)
989 998 down_data = data['down']
990 999
991 1000 down_values = []
992 1001 for data in down_data:
993 1002 for i in range(0,8):
994 1003 down_values.append(data[i])
995 1004
996 1005 return down_values
@@ -1,37 +1,44
1 1 function freq2Binary(mclock, frequency) {
2 2
3 3 var freq_bin = parseInt(frequency * (Math.pow(2,48)/mclock));
4 4 return freq_bin;
5 5
6 6 }
7 7
8 8 function binary2Freq(mclock, binary) {
9 9
10 10 var frequency = (1.0*binary) / (Math.pow(2,48)/mclock);
11 11 return frequency;
12 12 }
13 13
14 14
15 15 function binary2FreqDelta(mclock, binary) {
16 16
17 17 var frequency = (1.0*binary) / (Math.pow(2,48)/mclock);
18 18 return frequency;
19 19 }
20 20
21 21 function freqDelta2Binary(mclock, frequency) {
22 22
23 23 var freq_bin = parseInt(frequency * (Math.pow(2,48)/mclock));
24 24 return freq_bin;
25 25 }
26 26
27 27 function binary2Ramp(mclock, binary) {
28 28
29 29 var frequency = (1.0*mclock) / (binary+1);
30 30 return frequency;
31 31 }
32 32
33 33 function freqRamp2Binary(mclock, frequency) {
34 34
35 35 var freq_bin = parseInt(mclock/frequency-1);
36 36 return freq_bin;
37 } No newline at end of file
37 }
38
39 function us2Ramp(step_us) {
40 //periodo_delpaso = sysclockperiod x (N+1)
41 // freqsys/(N+1)=freq_ddelpaso=1/step
42 var freq = (1.0/(step_us));
43 return freq;
44 } No newline at end of file
@@ -1,255 +1,274
1 1 import ast
2 2 import json
3 3 import requests
4 4 import numpy as np
5 5 from base64 import b64encode
6 6 from struct import pack
7 7
8 8 from django.urls import reverse
9 9 from django.db import models
10 10 from apps.main.models import Configuration
11 11 from apps.main.utils import Params
12 12 # Create your models here.
13 13
14 14 from django.core.validators import MinValueValidator, MaxValueValidator
15 15 from django.core.exceptions import ValidationError
16 16
17 17 from devices.dds_rest import api, data
18 18
19 19 ENABLE_TYPE = (
20 20 (False, 'Disabled'),
21 21 (True, 'Enabled'),
22 22 )
23 23 MOD_TYPES = (
24 24 (0, 'Single Tone'),
25 25 (1, 'FSK'),
26 26 (2, 'Ramped FSK'),
27 27 (3, 'Chirp'),
28 28 (4, 'BPSK'),
29 29 )
30 30
31 31 class DDSRestConfiguration(Configuration):
32 32
33 33 DDS_NBITS = 48
34 34
35 clock = models.FloatField(verbose_name='Clock In (MHz)',validators=[MinValueValidator(5), MaxValueValidator(75)], null=True, default=60)
35 clock = models.FloatField(verbose_name='Clock In (MHz)',validators=[MinValueValidator(5), MaxValueValidator(75)], null=True, default=60)
36 36 multiplier = models.PositiveIntegerField(verbose_name='Multiplier',validators=[MinValueValidator(1), MaxValueValidator(20)], default=4)
37 37
38 38 frequencyA_Mhz = models.DecimalField(verbose_name='Frequency A (MHz)', validators=[MinValueValidator(0), MaxValueValidator(150)], max_digits=19, decimal_places=16, null=True, default=49.9200)
39 frequencyA = models.BigIntegerField(verbose_name='Frequency A (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**DDS_NBITS-1)], blank=True, null=True)
39 frequencyA = models.BigIntegerField(verbose_name='Frequency A (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**DDS_NBITS-1)], blank=True, null=True)
40 40
41 41 frequencyB_Mhz = models.DecimalField(verbose_name='Frequency B (MHz)', validators=[MinValueValidator(0), MaxValueValidator(150)], max_digits=19, decimal_places=16, blank=True, null=True)
42 frequencyB = models.BigIntegerField(verbose_name='Frequency B (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**DDS_NBITS-1)], blank=True, null=True)
42 frequencyB = models.BigIntegerField(verbose_name='Frequency B (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**DDS_NBITS-1)], blank=True, null=True)
43 43
44 44 delta_frequency_Mhz = models.DecimalField(verbose_name='Delta frequency (MHz)', validators=[MinValueValidator(0), MaxValueValidator(150)], max_digits=19, decimal_places=16, blank=True, null=True)
45 delta_frequency = models.BigIntegerField(verbose_name='Delta frequency (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**DDS_NBITS-1)], blank=True, null=True)
45 delta_frequency = models.BigIntegerField(verbose_name='Delta frequency (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**DDS_NBITS-1)], blank=True, null=True)
46 46
47 47 update_clock_Mhz = models.DecimalField(verbose_name='Update clock (MHz)', validators=[MinValueValidator(0), MaxValueValidator(150)], max_digits=19, decimal_places=16, blank=True, null=True)
48 update_clock = models.BigIntegerField(verbose_name='Update clock (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**32-1)], blank=True, null=True)
48 update_clock = models.BigIntegerField(verbose_name='Update clock (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**32-1)], blank=True, null=True)
49 49
50 50 ramp_rate_clock_Mhz = models.DecimalField(verbose_name='Ramp rate clock (MHz)', validators=[MinValueValidator(0), MaxValueValidator(150)], max_digits=19, decimal_places=16, blank=True, null=True)
51 ramp_rate_clock = models.BigIntegerField(verbose_name='Ramp rate clock (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**18-1)], blank=True, null=True)
51 ramp_rate_clock = models.BigIntegerField(verbose_name='Ramp rate clock (Decimal)',validators=[MinValueValidator(0), MaxValueValidator(2**18-1)], blank=True, null=True)
52 52
53 53 phaseA_degrees = models.FloatField(verbose_name='Phase A (Degrees)', validators=[MinValueValidator(0), MaxValueValidator(360)], default=0)
54 54
55 55 phaseB_degrees = models.FloatField(verbose_name='Phase B (Degrees)', validators=[MinValueValidator(0), MaxValueValidator(360)], blank=True, null=True)
56 56
57 57 modulation = models.PositiveIntegerField(verbose_name='Modulation Type', choices = MOD_TYPES, default = 0)
58 58
59 59 amplitude_enabled = models.BooleanField(verbose_name='Amplitude Control', choices=ENABLE_TYPE, default=False)
60 60
61 61 amplitudeI = models.PositiveIntegerField(verbose_name='Amplitude CH1',validators=[MinValueValidator(0), MaxValueValidator(2**12-1)], blank=True, null=True)
62 62 amplitudeQ = models.PositiveIntegerField(verbose_name='Amplitude CH2',validators=[MinValueValidator(0), MaxValueValidator(2**12-1)], blank=True, null=True)
63 63
64 64
65 65 def get_nbits(self):
66 66
67 67 return self.DDS_NBITS
68 68
69 69 def clean(self):
70 70
71 71 if self.modulation in [1,2,3]:
72 72 if self.frequencyB is None or self.frequencyB_Mhz is None:
73 73 raise ValidationError({
74 74 'frequencyB': 'Frequency modulation has to be defined when FSK or Chirp modulation is selected'
75 75 })
76 76
77 77 if self.modulation in [4,]:
78 78 if self.phaseB_degrees is None:
79 79 raise ValidationError({
80 80 'phaseB': 'Phase modulation has to be defined when BPSK modulation is selected'
81 81 })
82 82
83 83 self.frequencyA_Mhz = data.binary_to_freq(self.frequencyA, self.clock*self.multiplier)
84 84 self.frequencyB_Mhz = data.binary_to_freq(self.frequencyB, self.clock*self.multiplier)
85 85
86 86 def verify_frequencies(self):
87 87
88 88 return True
89 89
90 90 def parms_to_text(self):
91 91
92 92 my_dict = self.parms_to_dict()['configurations']['byId'][str(self.id)]
93 93
94 94 text = data.dict_to_text(my_dict)
95 95
96 96 return text
97 97
98 98 def status_device(self):
99 99 print("Status ")
100 100 try:
101 101 self.device.status = 0
102 102 payload = self.request('status')
103 103 if payload['status']=='generating RF':
104 104 self.device.status = 3
105 105 elif payload['status']=='no generating RF':
106 106 self.device.status = 2
107 107 else:
108 108 self.device.status = 1
109 109 self.device.save()
110 110 self.message = 'DDS REST status: {}'.format(payload['status'])
111 111 return False
112 112 except Exception as e:
113 113 if 'No route to host' not in str(e):
114 114 self.device.status = 4
115 115 self.device.save()
116 116 self.message = 'DDS REST status: {}'.format(str(e))
117 117 return False
118 118
119 119 self.device.save()
120 120 return True
121 121
122 122 def reset_device(self):
123 123
124 124 answer = api.reset(ip = self.device.ip_address,
125 125 port = self.device.port_address)
126 126
127 127 if answer[0] != "1":
128 128 self.message = 'DDS - {}'.format(answer[2:])
129 129 return 0
130 130
131 131 self.message = 'DDS - {}'.format(answer[2:])
132 132 return 1
133 133
134 134 def stop_device(self):
135 135
136 136 try:
137 137 answer = api.disable_rf(ip = self.device.ip_address,
138 138 port = self.device.port_address)
139 139
140 140 return self.status_device()
141 141
142 142 except Exception as e:
143 143 self.message = str(e)
144 144 return False
145 145
146 146 def start_device(self):
147 147
148 148 try:
149 149 answer = api.enable_rf(ip = self.device.ip_address,
150 150 port = self.device.port_address)
151 151
152 152 return self.status_device()
153 153
154 154 except Exception as e:
155 155 self.message = str(e)
156 156 return False
157 157
158 158 def read_device(self):
159 159
160 160 parms = api.read_config(ip = self.device.ip_address,
161 161 port = self.device.port_address)
162 162 if not parms:
163 163 self.message = "Could not read DDS parameters from this device"
164 164 return parms
165 165
166 166 self.message = ""
167 167 return parms
168 168
169 def arma_control(self,l_clock,l_multiplier,l_modulation):
170 sysclock = l_clock*l_multiplier
171 pll_range = 0
172 if(sysclock>=200):
173 pll_range = 1
174 l_control = ((l_modulation<<9)+(pll_range<<22)+(l_multiplier<<16)).to_bytes(4,'little')
175 return l_control
176
177 def conv_phase(self,l_phase):
178
179 l_phase_2B = int((l_phase*(2**14)/360)).to_bytes(2,'little')
180 return l_phase_2B
181
169 182 def arma_data_write(self):
170 183 #clock = RCClock.objects.get(rc_configuration=self)
171 184 clock = self.clock
172 185 print(clock)
173 186 multiplier = self.multiplier
174 187 print(multiplier)
175 188 frequencyA_Mhz = self.frequencyA_Mhz
176 189 print(frequencyA_Mhz)
177 190 frequencyA = self.frequencyA
178 191 print(frequencyA)
179 192 frequencyB_Mhz = self.frequencyB_Mhz
180 193 print(frequencyB_Mhz)
181 194 frequencyB = self.frequencyB
182 195 print(frequencyB)
183 phaseA_degrees = self.phaseA_degrees
196 phaseA_degrees = self.phaseA_degrees or 0
184 197 print(phaseA_degrees)
185 phaseB_degrees = self.phaseB_degrees
198 phaseB_degrees = self.phaseB_degrees or 0
186 199 print(phaseB_degrees)
187 modulation = self.modulation
200 modulation = self.modulation or 0
188 201 print(modulation)
189 amplitude_enabled = self.amplitude_enabled
202 amplitude_enabled = self.amplitude_enabled or 0
190 203 print(amplitude_enabled)
191 amplitudeI = self.amplitudeI
204 amplitudeI = self.amplitudeI or 0
192 205 print(amplitudeI)
193 amplitudeQ = self.amplitudeQ
206 amplitudeQ = self.amplitudeQ or 0
194 207 print(amplitudeQ)
195 delta_frequency = self.delta_frequency
208 delta_frequency = self.delta_frequency or 0
196 209 print(delta_frequency)
197 update_clock = self.update_clock
210 update_clock = self.update_clock or 0
198 211 print(update_clock)
199 ramp_rate_clock = self.ramp_rate_clock
212 ramp_rate_clock = self.ramp_rate_clock or 0
200 213 print(ramp_rate_clock)
201 214
215 control = self.arma_control(clock,multiplier,modulation)
216 phase1 = self.conv_phase(phaseA_degrees)
217 phase2 = self.conv_phase(phaseB_degrees)
218
202 219 cadena_json = {'clock': (b64encode(pack('<f',clock))).decode("UTF-8"),\
203 220 'multiplier': (b64encode(pack('<B',multiplier))).decode("UTF-8"),\
204 221 'frequencyA': (b64encode((frequencyA).to_bytes(6,'little'))).decode("UTF-8"),\
205 222 'frequencyB': (b64encode((frequencyB).to_bytes(6,'little'))).decode("UTF-8"),\
206 223 'delta_frequency': (b64encode((delta_frequency).to_bytes(6,'little'))).decode("UTF-8"),\
207 224 'update_clock': (b64encode((update_clock).to_bytes(4,'little'))).decode("UTF-8"),\
208 225 'ramp_rate_clock': (b64encode((ramp_rate_clock).to_bytes(3,'little'))).decode("UTF-8"),\
209 'control': (b64encode((ramp_rate_clock).to_bytes(4,'little'))).decode("UTF-8"),\
226 'control': (b64encode(control)).decode("UTF-8"),\
210 227 'amplitudeI': (b64encode((amplitudeI).to_bytes(2,'little'))).decode("UTF-8"),\
211 'amplitudeQ': (b64encode((amplitudeQ).to_bytes(3,'little'))).decode("UTF-8")
228 'amplitudeQ': (b64encode((amplitudeQ).to_bytes(2,'little'))).decode("UTF-8"),\
229 '_phase1': (b64encode((phase1))).decode("UTF-8"),\
230 '_phase2': (b64encode((phase2))).decode("UTF-8")
212 231 }
213 232 return cadena_json
214 233
215 234 def write_device(self, raw=False):
216 235 print("Ingreso a write")
217 236 try:
218 237
219 238 if not raw:
220 239 data = self.arma_data_write()
221 240 print(data)
222 241 payload = self.request('write', 'post', data=json.dumps(data))
223 242 print(payload)
224 243 if payload['write'] == 'ok':
225 244 self.device.status = 3
226 245 self.device.save()
227 246 self.message = 'DDS Rest write configured and started'
228 247 else:
229 248 self.message = payload['programming']
230 249 if payload['programming'] == 'fail':
231 250 self.message = 'DDS Rest write: error programming DDS chip'
232 251 if raw:
233 252 return b64encode(data)
234 253
235 254
236 255 except Exception as e:
237 256 if 'No route to host' not in str(e):
238 257 self.device.status = 4
239 258 else:
240 259 self.device.status = 0
241 260 self.message = 'DDS Rest write: {}'.format(str(e))
242 261 self.device.save()
243 262 return False
244 263
245 264 return True
246 265
247 266 def request(self, cmd, method='get', **kwargs):
248 267 print("Ingreso a request")
249 268 req = getattr(requests, method)(self.device.url(cmd), **kwargs)
250 269 payload = req.json()
251 270
252 271 return payload
253 272
254 273 class Meta:
255 274 db_table = 'ddsrest_configurations'
@@ -1,38 +1,51
1 1
2 2 function freq2Binary(mclock, frequency) {
3 3
4 4 var freq_bin = parseInt(frequency * (Math.pow(2,48)/mclock));
5 5 return freq_bin;
6 6
7 7 }
8 8
9 9 function binary2Freq(mclock, binary) {
10 10
11 11 var frequency = (1.0*binary) / (Math.pow(2,48)/mclock);
12 12 return frequency;
13 13 }
14 14
15 15
16 16 function binary2FreqDelta(mclock, binary) {
17 17
18 18 var frequency = (1.0*binary) / (Math.pow(2,48)/mclock);
19 19 return frequency;
20 20 }
21 21
22 22 function freqDelta2Binary(mclock, frequency) {
23 23
24 24 var freq_bin = parseInt(frequency * (Math.pow(2,48)/mclock));
25 25 return freq_bin;
26 26 }
27 27
28 28 function binary2Ramp(mclock, binary) {
29 29
30 30 var frequency = (1.0*mclock) / (binary+1);
31 31 return frequency;
32 32 }
33 33
34 34 function freqRamp2Binary(mclock, frequency) {
35 35
36 36 var freq_bin = parseInt(mclock/frequency-1);
37 37 return freq_bin;
38 }
39
40 function us2Ramp(step_us) {
41 //periodo_delpaso = sysclockperiod x (N+1)
42 // freqsys/(N+1)=freq_ddelpaso=1/step
43 var freq = (1.0/(step_us));
44 return freq;
45 }
46
47 function phase2Binary(phase) {
48
49 var phase_bin = parseInt(phase*(Math.pow(2,48))/360);
50 return phase_bin;
38 51 } No newline at end of file
@@ -1,158 +1,463
1 1 {% extends "dev_conf_edit.html" %}
2 2 {% load bootstrap4 %}
3 3 {% load static %}
4 4 {% load main_tags %}
5 5
6 {% block dds_rest%}
7
8 {% bootstrap_field form.template layout='horizontal' size='medium' %}
9 {% bootstrap_field form.device layout='horizontal' size='medium' %}
10 {% bootstrap_field form.label layout='horizontal' size='medium' %}
11 {% bootstrap_field form.experiment layout='horizontal' size='medium' %}
12
13 {% bootstrap_field form.clock layout='horizontal' size='medium' %}
14 {% bootstrap_field form.multiplier layout='horizontal' size='medium' %}
15
16 <div style="display: flex; justify-content: flex-end">
17 <div class="form-check">
18 <label class="form-check-label" ><input type="checkbox" class="form-check-input" id="id_chkbin_fA" value="" >Mostrar Decimal</label>
19 </div>
20 </div>
21 {% bootstrap_field form.frequencyA_Mhz layout='horizontal' size='medium' %}
22 <div id='id_row_fAbin'>
23 {% bootstrap_field form.frequencyA layout='horizontal' size='medium' %}
24 <div style="display: flex; justify-content: flex-end">
25 <small type="text" id="id_aux_fAbin" class="form-text text-muted">1000 0000 </small>
26 </div>
27 <br>
28 </div>
29
30 <div style="display: flex; justify-content: flex-end">
31 <div class="form-check">
32 <label class="form-check-label" ><input type="checkbox" class="form-check-input" id="id_chkbin_fB" value="" >Mostrar Decimal</label>
33 </div>
34 </div>
35 {% bootstrap_field form.frequencyB_Mhz layout='horizontal' size='medium' %}
36 <div id='id_row_fBbin'>
37 {% bootstrap_field form.frequencyB layout='horizontal' size='medium' %}
38 <div style="display: flex; justify-content: flex-end">
39 <small type="text" id="id_aux_fBbin" class="form-text text-muted">1000 0000 </small>
40 </div>
41 <br>
42 </div>
43
44 <div style="display: flex; justify-content: flex-end">
45 <div class="form-check">
46 <label class="form-check-label" ><input type="checkbox" class="form-check-input" id="id_chkbin_df" value="" >Mostrar Decimal</label>
47 </div>
48 </div>
49 {% bootstrap_field form.delta_frequency_Mhz layout='horizontal' size='medium' %}
50 <div id='id_row_dfbin'>
51 {% bootstrap_field form.delta_frequency layout='horizontal' size='medium' %}
52 <div style="display: flex; justify-content: flex-end">
53 <small type="text" id="id_aux_deltabin" class="form-text text-muted">1000 0000 </small>
54 </div>
55 <br>
56 </div>
57
58 <div style="display: flex; justify-content: flex-end">
59 <div class="form-check">
60 <label class="form-check-label" ><input type="checkbox" class="form-check-input" id="id_chkbin_ramp" value="" >Mostrar Decimal</label>
61 </div>
62 </div>
63 <div class="form-group row">
64 <label class="col-md-3 col-form-label" for="id_ramp_rate_clock_us">Ramp rate clock(us)</label>
65 <div class="col-md-9">
66 <input type="number" name="ramp_rate_clock_us" step="1e-16" class="form-control" placeHolder="Ramp rate clock(us)" title id="id_ramp_rate_clock_us">
67 </div>
68 </div>
69 <div id='id_row_rampbin'>
70 {% bootstrap_field form.ramp_rate_clock_Mhz layout='horizontal' size='medium' %}
71 {% bootstrap_field form.ramp_rate_clock layout='horizontal' size='medium' %}
72 <div style="display: flex; justify-content: flex-end">
73 <small type="text" id="id_aux_rampbin" class="form-text text-muted">1000 0000 </small>
74 </div>
75 <br>
76 </div>
77
78 <div style="display: flex; justify-content: flex-end">
79 <div class="form-check">
80 <label class="form-check-label" ><input type="checkbox" class="form-check-input" id="id_chkbin_phaseA" value="" >Mostrar Decimal</label>
81 </div>
82 </div>
83 {% bootstrap_field form.phaseA_degrees layout='horizontal' size='medium' %}
84 <div id='id_row_phaseA'>
85 <div style="display: flex; justify-content: flex-end">
86 <small type="text" id="id_aux_phaseAdec" class="form-text text-muted">9282 </small>
87 </div>
88 <div style="display: flex; justify-content: flex-end">
89 <small type="text" id="id_aux_phaseAbin" class="form-text text-muted">1000 0000 </small>
90 </div>
91 <br>
92 </div>
93
94 <div style="display: flex; justify-content: flex-end">
95 <div class="form-check">
96 <label class="form-check-label" ><input type="checkbox" class="form-check-input" id="id_chkbin_phaseB" value="" >Mostrar Decimal</label>
97 </div>
98 </div>
99 {% bootstrap_field form.phaseB_degrees layout='horizontal' size='medium' %}
100 <div id='id_row_phaseB'>
101 <div style="display: flex; justify-content: flex-end">
102 <small type="text" id="id_aux_phaseBdec" class="form-text text-muted">9876 </small>
103 </div>
104 <div style="display: flex; justify-content: flex-end">
105 <small type="text" id="id_aux_phaseBbin" class="form-text text-muted">1000 0000 </small>
106 </div>
107 <br>
108 </div>
109
110 {% bootstrap_field form.modulation layout='horizontal' size='medium' %}
111 {% bootstrap_field form.amplitude_enabled layout='horizontal' size='medium' %}
112
113 {% bootstrap_field form.amplitudeI layout='horizontal' size='medium' %}
114 {% bootstrap_field form.amplitudeQ layout='horizontal' size='medium' %}
115
116
117 {% endblock %}
118
6 119 {% block extra-js%}
7 120 <script src="{% static 'js/dds_conversion.js' %}"></script>
8 121 <script type="text/javascript">
122 $("#id_row_fAbin").hide();
123 $("#id_chkbin_fA").on('change', function() {
124 hidefA();
125 });
126
127 $("#id_row_fBbin").hide();
128 $("#id_chkbin_fB").on('change', function() {
129 hidefB();
130 });
131
132 $("#id_row_dfbin").hide();
133 $("#id_chkbin_df").on('change', function() {
134 hidedf();
135 });
136
137 $("#id_row_rampbin").hide();
138 $("#id_chkbin_ramp").on('change', function() {
139 hideramp();
140 });
9 141
142 $("#id_row_phaseA").hide();
143 $("#id_chkbin_phaseA").on('change', function() {
144 hidephaseA();
145 });
146
147 $("#id_row_phaseB").hide();
148 $("#id_chkbin_phaseB").on('change', function() {
149 hidephaseB();
150 });
151
10 152 $("#id_clock").on('change', function() {
11 153 updateFrequencies();
12 154 });
13 155
14 156 $("#id_multiplier").on('change', function() {
15 157 updateFrequencies();
16 158 });
17 159
18 160 $("#id_frequencyA_Mhz").on('change', function() {
19 161 updateBinaryFrequencies();
20 162 });
21 163
22 164 $("#id_frequencyA").on('change', function() {
23 165 updateFrequencies();
24 166 });
25 167
26 168 $("#id_frequencyB_Mhz").on('change', function() {
27 169 updateBinaryFrequencies();
28 170 });
29 171
30 172 $("#id_frequencyB").on('change', function() {
31 173 updateFrequencies();
32 174 });
33 175
34 176 $("#id_delta_frequency").on('change', function() {
35 177 updateFrequencyDelta();
36 178 });
37 179
38 180 $("#id_delta_frequency_Mhz").on('change', function() {
39 181 updateBinaryFrequencyDelta();
40 182 });
41 183
42 184 $("#id_ramp_rate_clock").on('change', function() {
43 185 updateFrequencyRamp();
44 186 });
45 187
188 $("#id_ramp_rate_clock_us").on('change', function() {
189 updateFrequencyMhzRamp();
190 });
191
46 192 $("#id_ramp_rate_clock_Mhz").on('change', function() {
47 193 updateBinaryFrequencyRamp();
48 194 });
49
195
196 $("#id_phaseA_degrees").on('change', function() {
197 updatephaseAbindec();
198 });
199
200 $("#id_phaseB_degrees").on('change', function() {
201 updatephaseBbindec();
202 });
203
50 204 function updateBinaryFrequencies() {
51 205
52 206 var clock = $("#id_clock").val();
53 207 var multiplier = $("#id_multiplier").val();
54 208 var freq = $("#id_frequencyA_Mhz").val();
55 209 var freq_mod = $("#id_frequencyB_Mhz").val();
56 //var freq_delta = $("#id_delta_frequency_Mhz").val();
57 //var freq_ramp = $("#id_ramp_rate_clock_Mhz").val();
58 210
59 211 var mclock = clock*multiplier;
60 212
61 213 var freq_bin = freq2Binary(mclock, freq);
62 214 var freq_mod_bin = freq2Binary(mclock, freq_mod);
63 //var freqdelta_bin = freqDelta2Binary(mclock, freq_delta);
64 //var freqramp_bin = freqRamp2Binary(mclock, freq_ramp);
65 215
66 216 $("#id_frequencyA").val(freq_bin);
67 217 $("#id_frequencyB").val(freq_mod_bin);
68 //$("#id_delta_frequency").val(freqdelta_bin);
69 //$("#id_ramp_rate_clock").val(freqramp_bin);
70 218
71 219 freq = binary2Freq(mclock, freq_bin);
72 220 freq_mod = binary2Freq(mclock, freq_mod_bin);
73 //freqdelta = binary2FreqDelta(mclock, freqdelta_bin);
74 //freq_ramp = binary2Ramp(mclock, freqramp_bin);
75 221
76 222 $("#id_frequencyA_Mhz").val(freq);
77 223 $("#id_frequencyB_Mhz").val(freq_mod);
78 //$("#id_delta_frequency_Mhz").val(freqdelta);
79 //$("#id_ramp_rate_clock_Mhz").val(freq_ramp);
80 224
81 225 }
82 226
83 227 function updateFrequencies() {
84 228 console.log("Ingreso a updateFrequencies");
85 229 var clock = $("#id_clock").val();
86 230 var multiplier = $("#id_multiplier").val();
87 231 var freq_bin = $("#id_frequencyA").val();
88 232 var freq_mod_bin = $("#id_frequencyB").val();
89 233 var freqdelta_bin = $("#id_delta_frequency").val();
90 234 var freqramp_bin = $("#id_ramp_rate_clock").val();
91 235
92 236 var mclock = clock*multiplier;
93 237
94 238 var freq = binary2Freq(mclock, freq_bin);
95 239 var freq_mod = binary2Freq(mclock, freq_mod_bin);
96 240 var freqdelta = binary2FreqDelta(mclock, freqdelta_bin);
97 241 var freq_ramp = binary2Ramp(mclock, freqramp_bin);
98 242
99 243 $("#id_frequencyA_Mhz").val(freq);
100 244 $("#id_frequencyB_Mhz").val(freq_mod);
101 245 $("#id_delta_frequency_Mhz").val(freqdelta);
102 246 $("#id_ramp_rate_clock_Mhz").val(freq_ramp);
103 247 }
104 248
105 249 function updateFrequencyDelta() {
106 250 console.log("Ingreso a updateFrequencyDelta");
107 251 var clock = $("#id_clock").val();
108 252 var multiplier = $("#id_multiplier").val();
109 253 var freq_bin = $("#id_delta_frequency").val();
110 254
111 255 var mclock = clock*multiplier;
112 256
113 257 var freq = binary2FreqDelta(mclock, freq_bin);
114 258 console.log(freq);
115 259 $("#id_delta_frequency_Mhz").val(freq);
116 260 }
117 261
118 262 function updateBinaryFrequencyDelta() {
119 263 console.log("Ingreso a updateBInaryFrequencyDelta");
120 264 var clock = $("#id_clock").val();
121 265 var multiplier = $("#id_multiplier").val();
122 var freq = $("#id_delta_frequency_MHz").val();
266 var freq = $("#id_delta_frequency_Mhz").val();
267 console.log(clock);
268 console.log(multiplier);
269 console.log(freq);
123 270
124 271 var mclock = clock*multiplier;
125
272 console.log(mclock);
273
126 274 var freq_bin = freqDelta2Binary(mclock, freq);
275
127 276 console.log(freq_bin);
128 277 $("#id_delta_frequency").val(freq_bin);
278
279 document.getElementById("id_aux_deltabin").innerHTML = numToString(parseInt(freq_bin, 10), 2, 48).match(/.{1,4}/g).join(' ');
129 280 }
130 281
131 282 function updateFrequencyRamp() {
132 283 console.log("Ingreso a updateFrequencyRamp");
133 284 var clock = $("#id_clock").val();
134 285 var multiplier = $("#id_multiplier").val();
135 286 var freq_bin = $("#id_ramp_rate_clock").val();
136 287
137 288 var mclock = clock*multiplier;
138 289
139 290 var freq = binary2Ramp(mclock, freq_bin);
140 291 console.log(freq);
141 292 $("#id_ramp_rate_clock_Mhz").val(freq);
142 293 }
143 294
144 295 function updateBinaryFrequencyRamp() {
145 296 console.log("Ingreso a updateBInaryFrequencyRamp");
146 297 var clock = $("#id_clock").val();
147 298 var multiplier = $("#id_multiplier").val();
148 var freq = $("#id_ramp_rate_clock_MHz").val();
299 var freq = $("#id_ramp_rate_clock_Mhz").val();
149 300
150 301 var mclock = clock*multiplier;
151 302
152 303 var freq_bin = freqRamp2Binary(mclock, freq);
153 304 console.log(freq_bin);
154 305 $("#id_ramp_rate_clock").val(freq_bin);
155 306 }
156 307
308 function updateFrequencyMhzRamp() {
309 console.log("Ingreso a updateFrequencyMhzRamp");
310 var step_us = $("#id_ramp_rate_clock_us").val();
311
312 var freq = us2Ramp(step_us);
313 console.log(freq);
314 $("#id_ramp_rate_clock_Mhz").val(freq);
315 updateBinaryFrequencyRamp();
316 }
317
318 function hidefA() {
319 var checkbox = $("#id_chkbin_fA");
320 var freq_bin = $("#id_row_fAbin");
321 var val_freq = $("#id_frequencyA");
322
323 console.log("Ingreso a hidefA");
324 if (checkbox.is(':checked')) {
325 freq_bin.show();
326 console.log(val_freq.val());
327 document.getElementById("id_aux_fAbin").innerHTML = numToString(parseInt(val_freq.val(), 10), 2, 48).match(/.{1,4}/g).join(' ');
328 }
329 else{
330 freq_bin.hide();
331 }
332 }
333
334 function hidefB() {
335 var checkbox = $("#id_chkbin_fB");
336 var freq_bin = $("#id_row_fBbin");
337 var val_freq = $("#id_frequencyB");
338
339 console.log("Ingreso a hidefB");
340 if (checkbox.is(':checked')) {
341 freq_bin.show();
342 console.log(val_freq.val());
343 document.getElementById("id_aux_fBbin").innerHTML = numToString(parseInt(val_freq.val(), 10), 2, 48).match(/.{1,4}/g).join(' ');
344 }
345 else{
346 freq_bin.hide();
347 }
348 }
349
350 function hidedf() {
351 var checkbox = $("#id_chkbin_df");
352 var freq_bin = $("#id_row_dfbin");
353 var val_freq = $("#id_delta_frequency");
354
355 console.log("Ingreso a hidedf");
356 if (checkbox.is(':checked')) {
357 freq_bin.show();
358 console.log(val_freq.val());
359 document.getElementById("id_aux_deltabin").innerHTML = numToString(parseInt(val_freq.val(), 10), 2, 48).match(/.{1,4}/g).join(' ');
360 }
361 else{
362 freq_bin.hide();
363 }
364 }
365
366 function hideramp() {
367 var checkbox = $("#id_chkbin_ramp");
368 var freq_bin = $("#id_row_rampbin");
369 var val_freq = $("#id_ramp_rate_clock");
370
371 console.log("Ingreso a hideramp");
372 if (checkbox.is(':checked')) {
373 freq_bin.show();
374 console.log(val_freq.val());
375 document.getElementById("id_aux_rampbin").innerHTML = numToString(parseInt(val_freq.val(), 10), 2, 20).match(/.{1,4}/g).join(' ');
376 }
377 else{
378 freq_bin.hide();
379 }
380 }
381
382 function hidephaseA() {
383 var checkbox = $("#id_chkbin_phaseA");
384 var freq_bin = $("#id_row_phaseA");
385 var phase_degree = $("#id_phaseA_degrees");
386
387 console.log("Ingreso a hidephaseA");
388 if (checkbox.is(':checked')) {
389 freq_bin.show();
390 console.log(phase_degree.val());
391 var phase_degree_dec = parseInt(phase_degree.val()*((2**14)/360.0),10);
392 console.log(phase_degree_dec);
393 document.getElementById("id_aux_phaseAdec").innerHTML = numToString(phase_degree_dec, 10, 5).match(/.{1,4}/g).join(' ');
394 document.getElementById("id_aux_phaseAbin").innerHTML = numToString(parseInt(phase_degree_dec, 10), 2, 14).match(/.{1,4}/g).join(' ');
395
396 }
397 else{
398 freq_bin.hide();
399 }
400 }
401
402 function hidephaseB() {
403 var checkbox = $("#id_chkbin_phaseB");
404 var freq_bin = $("#id_row_phaseB");
405 var phase_degree = $("#id_phaseB_degrees");
406
407 console.log("Ingreso a hidephaseB");
408 if (checkbox.is(':checked')) {
409 freq_bin.show();
410 console.log(phase_degree.val());
411 var phase_degree_dec = parseInt(phase_degree.val()*((2**14)/360.0),10);
412 console.log(phase_degree_dec);
413 document.getElementById("id_aux_phaseBdec").innerHTML = numToString(phase_degree_dec, 10, 5).match(/.{1,4}/g).join(' ');
414 document.getElementById("id_aux_phaseBbin").innerHTML = numToString(parseInt(phase_degree_dec, 10), 2, 14).match(/.{1,4}/g).join(' ');
415
416 }
417 else{
418 freq_bin.hide();
419 }
420 }
421
422 function updatephaseAbindec() {
423 var freq_bin = $("#id_row_phaseA");
424 var phase_degree = $("#id_phaseA_degrees");
425
426 console.log("Ingreso a cupdatephaseAbindec");
427 console.log(phase_degree.val());
428 var phase_degree_dec = parseInt(phase_degree.val()*((2**14)/360.0),10);
429 console.log(phase_degree_dec);
430 document.getElementById("id_aux_phaseAdec").innerHTML = numToString(phase_degree_dec, 10, 5).match(/.{1,4}/g).join(' ');
431 document.getElementById("id_aux_phaseAbin").innerHTML = numToString(parseInt(phase_degree_dec, 10), 2, 14).match(/.{1,4}/g).join(' ');
432
433 }
434
435 function updatephaseBbindec() {
436 var freq_bin = $("#id_row_phaseB");
437 var phase_degree = $("#id_phaseB_degrees");
438
439 console.log("Ingreso a cupdatephaseBbindec");
440 console.log(phase_degree.val());
441 var phase_degree_dec = parseInt(phase_degree.val()*((2**14)/360.0),10);
442 console.log(phase_degree_dec);
443 document.getElementById("id_aux_phaseBdec").innerHTML = numToString(phase_degree_dec, 10, 5).match(/.{1,4}/g).join(' ');
444 document.getElementById("id_aux_phaseBbin").innerHTML = numToString(parseInt(phase_degree_dec, 10), 2, 14).match(/.{1,4}/g).join(' ');
445
446 }
447
448 function padStart(string, length, char) {
449 return length > 0 ?
450 padStart(char + string, --length, char) :
451 string;
452 }
453
454 function numToString(num, radix, length = num.length) {
455 const numString = num.toString(radix);
456 return numString.length === length ?
457 numString :
458 padStart(numString, length - numString.length, "0")
459 }
460
461 console.log(numToString(parseInt("37529996894754", 10), 2, 48));
157 462 </script>
158 463 {% endblock %} No newline at end of file
@@ -1,80 +1,80
1 1 # Create your views here.
2 2 from django.shortcuts import redirect, render, get_object_or_404
3 3
4 4 # from apps.main.models import Experiment, Configuration
5 5 from apps.main.views import sidebar
6 6
7 7 from .models import DDSRestConfiguration
8 8 from .forms import DDSRestConfigurationForm
9 9 # Create your views here.
10 10
11 11 def dds_rest_conf(request, id_conf):
12 12
13 13 conf = get_object_or_404(DDSRestConfiguration, pk=id_conf)
14 14
15 15 kwargs = {}
16 16
17 17 kwargs['status'] = conf.device.get_status_display()
18 18
19 19 # if not kwargs['connected']:
20 20 # messages.error(request, message=answer)
21 21
22 22 kwargs['dev_conf'] = conf
23 23 kwargs['dev_conf_keys'] = [
24 'clock',
25 'multiplier',
26 'frequencyA_Mhz',
24 'clock',
25 'multiplier',
26 'frequencyA_Mhz',
27 27 'frequencyA',
28 28 'frequencyB_Mhz',
29 29 'frequencyB',
30 30 'delta_frequency_Mhz',
31 31 'delta_frequency',
32 32 'update_clock_Mhz',
33 33 'update_clock',
34 34 'ramp_rate_clock_Mhz',
35 35 'ramp_rate_clock',
36 36 'phaseA_degrees',
37 37 'phaseB_degrees',
38 38 'modulation',
39 39 'amplitude_enabled',
40 40 'amplitudeI',
41 41 'amplitudeQ']
42 42
43 43 kwargs['title'] = 'DDS Rest Configuration'
44 44 kwargs['suptitle'] = 'Details'
45 45
46 46 kwargs['button'] = 'Edit Configuration'
47 47
48 48 ###### SIDEBAR ######
49 49 kwargs.update(sidebar(conf=conf))
50 50
51 51 return render(request, 'dds_rest_conf.html', kwargs)
52 52
53 53 def dds_rest_conf_edit(request, id_conf):
54 54
55 55 conf = get_object_or_404(DDSRestConfiguration, pk=id_conf)
56 56
57 57 if request.method=='GET':
58 58 form = DDSRestConfigurationForm(instance=conf)
59 59
60 60 if request.method=='POST':
61 61 form = DDSRestConfigurationForm(request.POST, instance=conf)
62 62
63 63 if form.is_valid():
64 64 conf = form.save(commit=False)
65 65
66 66 if conf.verify_frequencies():
67 67
68 68 conf.save()
69 69 return redirect('url_dds_rest_conf', id_conf=conf.id)
70 70
71 71 ##ERRORS
72 72
73 73 kwargs = {}
74 kwargs['id_dev'] = conf.id
75 kwargs['form'] = form
76 kwargs['title'] = 'Device Configuration'
74 kwargs['id_dev'] = conf.id
75 kwargs['form'] = form
76 kwargs['title'] = 'Device Configuration'
77 77 kwargs['suptitle'] = 'Edit'
78 kwargs['button'] = 'Save'
79
78 kwargs['button'] = 'Save'
79 kwargs['device_dds'] = 'dds_rest'
80 80 return render(request, 'dds_rest_conf_edit.html', kwargs)
@@ -1,129 +1,129
1 1 <!DOCTYPE html>
2 {% load static %}{% load bootstrap4 %}
2 {% load static %}
3 {% load bootstrap4 %}
3 4 <html lang="en">
4 5 <head>
5 6 <meta charset="utf-8">
6 7 <title>{% block title %}Jicamarca Integrated Radar System:::::{% endblock %}</title>
7 8 <meta name="description" content="">
8 9 <meta name="author" content="">
9 10 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
10 11 {# bootstrap_css #}
11 12
12 13 <link href="{% static 'css/fontawesome.css' %}" rel="stylesheet">
13 14 <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
14 15 <link href="{% static 'css/style.css' %}" rel="stylesheet">
15 16 <link href="{% static 'css/header.css' %}" rel="stylesheet">
16 17 <link href="{% static 'css/footer.css' %}" rel="stylesheet">
17 18 <link rel="shortcut icon" href="{% static 'images/favicon.ico' %}" />
18 19
19 20
20 21 <!--link href="{% static '' %}css/bootstrap-{{theme}}.min.css" media="all" rel="stylesheet"-->
21 <!-- <link href="{% static 'css/bootcards-desktop.min.css' %}" media="all" rel="stylesheet"> -->
22 <!-- <link href="{% static 'css/bootcards-desktop.min.css' %}" media="all" rel="stylesheet"> -->
22 23 <link href="{% static 'css/font-awesome.min.css' %}" media="all" rel="stylesheet"-->
23 24 <!--link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"-->
24 25
25 26 <!-- Bootcards CSS for iOS: >
26 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootcards/1.0.0/css/bootcards-ios.min.css">
27 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootcards/1.0.0/css/bootcards-ios.min.css"-->
27 28
28 29 <!-- Bootcards CSS for Android: >
29 30 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootcards/1.0.0/css/bootcards-android.min.css"-->
30 31
31 32 <!-- Bootcards CSS for desktop: >
32 33 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootcards/1.0.0/css/bootcards-desktop.min.css"-->
33 34
34 <style type="text/css">
35 .logo {padding-top: 5px; height: 50px}
36 .clickable-row {cursor: pointer;}
37 .col-no-padding { padding-left:0;}
38 .gi-2x{font-size: 2em;}
39 .gi-3x{font-size: 3em;}
40 .gi-4x{font-size: 4em;}
41 .gi-5x{font-size: 5em;}
42 </style>
43 {% block extra-head %}{% endblock %}
35 <style type="text/css">
36 .logo {padding-top: 5px; height: 50px}
37 .clickable-row {cursor: pointer;}
38 .col-no-padding { padding-left:0;}
39 .gi-2x{font-size: 2em;}
40 .gi-3x{font-size: 3em;}
41 .gi-4x{font-size: 4em;}
42 .gi-5x{font-size: 5em;}
43 </style>
44 {% block extra-head %}{% endblock %}
44 45 </head>
45 <body>
46
47 46
47 <body>
48 48
49 49 {% include "header_igp.html" %}
50 50
51 51 <div style="clear: both;"></div>
52 52
53
54 53 <div class="container">
55 54 <div id="page" class="row" style="min-height:600px">
56 55
57 56 {% if no_sidebar %}
58 57 <div class="col-md-0 hidden-xs hidden-sm" role="complementary"></div>
59 58
60 59 {% else %}
61 60 <div class="col-md-3 hidden-xs hidden-sm" role="complementary">
62 61 <br><br>
63 62 <div id="sidebar">
64 63 {% block sidebar%}
65 64 {% include "sidebar_devices.html" %}
66 65 {% endblock %}
67 66 </div>
68 67 </div>
69 68 {% endif %}
70 69
71 70
72 71 {% if no_sidebar %}
73 72 <div class="col-md-12 col-xs-12" role="main">
74 73 {% else %}
75 74 <div class="col-md-9 col-xs-12" role="main">
76 75 {% endif %}
77 <div class="page-header">
78 <h1>{% block content-title %}{% endblock %} <small>{% block content-suptitle %}{% endblock %}</small></h1>
79 </div>
80 {% block messages %}
81 {% if messages %}
82 {% for message in messages %}
83 <div class="alert alert-{% if message.tags %}{% if 'error' in message.tags %}danger{% else %}{{ message.tags }}{% endif %}{% else %}info{% endif %} alert-dismissible" role="alert">
84 <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
85 <strong>{{message.tags|title}}!</strong> {{ message }}
86 </div>
87 {% endfor %}
88 {% endif %}
89 {% endblock %}
76
77 <div class="page-header">
78 <h1>{% block content-title %}{% endblock %} <small>{% block content-suptitle %}{% endblock %}</small></h1>
79 </div>
80 {% block messages %}
81 {% if messages %}
82 {% for message in messages %}
83 <div class="alert alert-{% if message.tags %}{% if 'error' in message.tags %}danger{% else %}{{ message.tags }}{% endif %}{% else %}info{% endif %} alert-dismissible" role="alert">
84 <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
85 <strong>{{message.tags|title}}!</strong> {{ message }}
86 </div>
87 {% endfor %}
88 {% endif %}
89 {% endblock %}
90 90
91 91 {% block content %}
92 92 {% endblock %}
93 93
94 </div>
94 </div>
95 95
96 96
97 97 </div><!--/row-->
98 98 </div> <!-- container -->
99 99
100 100 {% include "footer_igp.html" %}
101 101
102 102
103 103
104 104 <!-- This part put block modal which is used to change parameters of my plot -->
105 105 {% block modal %}{% endblock modal %}
106 106 {% block debug %}<div class="row">{{debug}}</div>{% endblock debug %}
107 107 <!-- Optional JavaScript -->
108 108 <!-- jQuery first, then Popper.js, then Bootstrap JS -->
109 109 {# % bootstrap_javascript jquery='slim' % #}
110 110 <script src="{% static 'js/jquery-3.3.1.slim.min.js' %}"></script>
111 111 <script src="{% static 'js/popper.min.js' %}"></script>
112 112 <script src="{% static 'js/moment.min.js' %}"></script>
113 113 <script src="{% static 'js/bootstrap.min.js' %}"></script>
114 114 <script src="{% static 'js/plotly-latest.min.js' %}"></script>
115 115
116 116 <!-- Here we put the script from the type of plot that we recibe -->
117 117 <script>
118 118 $("#menu-toggle").click(function (e) {
119 119 e.preventDefault();
120 120 $("#wrapper").toggleClass("toggled");
121 121 });
122 122 </script>
123 123 {% block extra-js %}
124 124 {% endblock%}
125 125
126 126
127 127
128 128 </body>
129 129 </html>
@@ -1,35 +1,42
1 1 {% extends "base.html" %}
2 2 {% load bootstrap4 %}
3 3 {% load static %}
4 4 {% load main_tags %}
5 5
6 6 {% block content-title %}{{title}}{% endblock %}
7 7 {% block content-suptitle %}{{suptitle}}{% endblock %}
8 8
9 9 {% block content %}
10 10 {% if form.is_multipart %}
11 11 <form class="form" enctype="multipart/form-data" method="post" action="{{action}}">
12 12 {% else %}
13 13 <form class="form" method="post" action="{{action}}">
14 14 {% endif %}
15 15 {% csrf_token %}
16 {% bootstrap_form form layout='horizontal' size='medium' %}
16
17 {% if device_dds == 'dds_rest' %}
18 {% block dds_rest%}
19 {% endblock %}
20 {% else %}
21 {% bootstrap_form form layout='horizontal' size='medium' %}
22 {% endif %}
23
17 24 <div style="clear: both;"></div>
18 25 <br>
19 26 {% if extra_button %}
20 27 <div class="pull-left">
21 28 <button type="button" class="btn btn-primary" id="bt_{{extra_button}}">{{extra_button}}</button>
22 29 </div>
23 30 {% endif %}
24 31 {% if button %}
25 32 <div class="pull-right">
26 33 <button type="button" class="btn btn-primary" onclick="{% if previous %}window.location.replace('{{ previous }}');{% else %}history.go(-1);{% endif %}">{% if cancel %}{{cancel}}{% else %}Cancel{% endif %}</button>
27 34 <button type="submit" class="btn btn-primary">{{button}}</button>
28 35 </div>
29 36 {% endif %}
30 </form>
37 </form>
31 38 {% endblock %}
32 39
33 40 {% block sidebar%}
34 41 {% include "sidebar_devices.html" %}
35 42 {% endblock %}
@@ -1,37 +1,44
1 1 function freq2Binary(mclock, frequency) {
2 2
3 3 var freq_bin = parseInt(frequency * (Math.pow(2,48)/mclock));
4 4 return freq_bin;
5 5
6 6 }
7 7
8 8 function binary2Freq(mclock, binary) {
9 9
10 10 var frequency = (1.0*binary) / (Math.pow(2,48)/mclock);
11 11 return frequency;
12 12 }
13 13
14 14
15 15 function binary2FreqDelta(mclock, binary) {
16 16
17 17 var frequency = (1.0*binary) / (Math.pow(2,48)/mclock);
18 18 return frequency;
19 19 }
20 20
21 21 function freqDelta2Binary(mclock, frequency) {
22 22
23 23 var freq_bin = parseInt(frequency * (Math.pow(2,48)/mclock));
24 24 return freq_bin;
25 25 }
26 26
27 27 function binary2Ramp(mclock, binary) {
28 28
29 29 var frequency = (1.0*mclock) / (binary+1);
30 30 return frequency;
31 31 }
32 32
33 33 function freqRamp2Binary(mclock, frequency) {
34 34
35 35 var freq_bin = parseInt(mclock/frequency-1);
36 36 return freq_bin;
37 } No newline at end of file
37 }
38
39 function us2Ramp(step_us) {
40 //periodo_delpaso = sysclockperiod x (N+1)
41 // freqsys/(N+1)=freq_ddelpaso=1/step
42 var freq = (1.0/(step_us));
43 return freq;
44 } No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now