##// END OF EJS Templates
RC files have been updated...
Fiorella Quino -
r264:17ec69be4c00
parent child
Show More
@@ -86,13 +86,13 class RCConfigurationForm(forms.ModelForm):
86 86 if 'clock_divider' in form_data:
87 87 if form_data['clock_divider']<1:
88 88 self.add_error('clock_divider', 'Invalid Value')
89 else:
90 if form_data['ipp']*(20./3*(form_data['clock_in']/form_data['clock_divider']))%10!=0:
91 self.add_error('ipp', 'Invalid IPP units={}'.format(form_data['ipp']*(20./3*(form_data['clock_in']/form_data['clock_divider']))))
89 #else:
90 # if form_data['ipp']*(20./3*(form_data['clock_in']/form_data['clock_divider']))%10!=0:
91 # self.add_error('ipp', 'Invalid IPP units={}'.format(form_data['ipp']*(20./3*(form_data['clock_in']/form_data['clock_divider']))))
92 92
93 93 return form_data
94 94
95 def save(self):
95 def save(self):
96 96 conf = super(RCConfigurationForm, self).save()
97 97 conf.total_units = conf.ipp*conf.ntx*conf.km2unit
98 98 conf.save()
@@ -1,4 +1,5
1 1
2
2 3 import ast
3 4 import json
4 5 import requests
@@ -11,11 +12,10 from django.core.urlresolvers import reverse
11 12 from django.core.validators import MinValueValidator, MaxValueValidator
12 13
13 14 from apps.main.models import Configuration
15 from apps.main.utils import Params
14 16 from devices.rc import api
15 from .utils import RCFile
16 from django.template.defaultfilters import last
17 from apps.rc.utils import RCFile
17 18
18 # Create your models here.
19 19
20 20 LINE_TYPES = (
21 21 ('none', 'Not used'),
@@ -57,6 +57,18 DAT_CMDS = {
57 57 'CLOCK_DIVIDER' : 8,
58 58 }
59 59
60 MAX_BITS = 8
61
62 # Rotate left: 0b1001 --> 0b0011
63 rol = lambda val, r_bits: \
64 (val << r_bits%MAX_BITS) & (2**MAX_BITS-1) | \
65 ((val & (2**MAX_BITS-1)) >> (MAX_BITS-(r_bits%MAX_BITS)))
66
67 # Rotate right: 0b1001 --> 0b1100
68 ror = lambda val, r_bits: \
69 ((val & (2**MAX_BITS-1)) >> r_bits%MAX_BITS) | \
70 (val << (MAX_BITS-(r_bits%MAX_BITS)) & (2**MAX_BITS-1))
71
60 72
61 73 class RCConfiguration(Configuration):
62 74
@@ -80,9 +92,6 class RCConfiguration(Configuration):
80 92 def get_absolute_url_plot(self):
81 93 return reverse('url_plot_rc_pulses', args=[str(self.id)])
82 94
83 def get_absolute_url_import(self):
84 return reverse('url_import_rc_conf', args=[str(self.id)])
85
86 95 @property
87 96 def ipp_unit(self):
88 97
@@ -101,6 +110,8 class RCConfiguration(Configuration):
101 110 def clone(self, **kwargs):
102 111
103 112 lines = self.get_lines()
113 print 'LINES'
114 print lines
104 115 self.pk = None
105 116 self.id = None
106 117 for attr, value in kwargs.items():
@@ -110,6 +121,15 class RCConfiguration(Configuration):
110 121 for line in lines:
111 122 line.clone(rc_configuration=self)
112 123
124 new_lines = self.get_lines()
125 for line in new_lines:
126 line_params = json.loads(line.params)
127 if 'TX_ref' in line_params:
128 ref_line = RCLine.objects.get(pk=line_params['TX_ref'])
129 line_params['TX_ref'] = ['{}'.format(l.pk) for l in new_lines if l.get_name()==ref_line.get_name()][0]
130 line.params = json.dumps(line_params)
131 line.save()
132
113 133 return self
114 134
115 135 def get_lines(self, **kwargs):
@@ -131,49 +151,21 class RCConfiguration(Configuration):
131 151 line.params = '{}'
132 152 line.save()
133 153
134 def parms_to_dict(self):
154 def dict_to_parms(self, params, id=None):
135 155 '''
136 156 '''
137 157
138 ignored = ('parameters', 'type','polymorphic_ctype', 'configuration_ptr',
139 'created_date', 'programmed_date', 'mix')
140
141 data = {}
142 for field in self._meta.fields:
143 if field.name in ignored:
144 continue
145 data[field.name] = '{}'.format(field.value_from_object(self))
146
147 data['device_id'] = data.pop('device')
148 data['device_type'] = self.device.device_type.name
149 data['lines'] = []
150 data['mix'] = self.mix
151
152 for line in self.get_lines():
153 line_data = json.loads(line.params)
154 if 'TX_ref' in line_data and line_data['TX_ref'] not in (0, '0'):
155 line_data['TX_ref'] = RCLine.objects.get(pk=line_data['TX_ref']).get_name()
156 if 'code' in line_data:
157 line_data['code'] = RCLineCode.objects.get(pk=line_data['code']).name
158 line_data['type'] = line.line_type.name
159 line_data['name'] = line.get_name()
160 data['lines'].append(line_data)
161
162 data['delays'] = self.get_delays()
163 data['pulses'] = self.get_pulses()
164
165 return data
166
167 def dict_to_parms(self, data):
168 '''
169 '''
158 if id:
159 data = Params(params).get_conf(id_conf=id)
160 else:
161 data = Params(params).get_conf(dtype='rc')
170 162
171 163 self.name = data['name']
172 self.ipp = float(data['ipp'])
173 self.ntx = int(data['ntx'])
174 self.clock_in = float(data['clock_in'])
175 self.clock_divider = int(data['clock_divider'])
176 self.clock = float(data['clock'])
164 self.ipp = data['ipp']
165 self.ntx = data['ntx']
166 self.clock_in = data['clock_in']
167 self.clock_divider = data['clock_divider']
168 self.clock = data['clock']
177 169 self.time_before = data['time_before']
178 170 self.time_after = data['time_after']
179 171 self.sync = data['sync']
@@ -182,44 +174,44 class RCConfiguration(Configuration):
182 174 self.save()
183 175 self.clean_lines()
184 176
185 lines = []
186 177 positions = {'tx':0, 'tr':0}
187
188 for i, line_data in enumerate(data['lines']):
189 name = line_data.pop('name', '')
190 line_type = RCLineType.objects.get(name=line_data.pop('type'))
191 if line_type.name=='codes':
192 code = RCLineCode.objects.get(name=line_data['code'])
193 line_data['code'] = code.pk
194 line = RCLine.objects.filter(rc_configuration=self, channel=i)
195 if line:
196 line = line[0]
197 line.line_type = line_type
198 line.params = json.dumps(line_data)
199 else:
200 line = RCLine(rc_configuration=self, line_type=line_type,
201 params=json.dumps(line_data),
202 channel=i)
203
204 if line_type.name=='tx':
205 line.position = positions['tx']
178 for i, id in enumerate(data['lines']):
179 line_data = params['lines']['byId'][id]
180 line_type = RCLineType.objects.get(name=line_data['line_type'])
181 if line_type.name == 'codes':
182 code = RCLineCode.objects.get(name=line_data['params']['code'])
183 line_data['params']['code'] = code.pk
184 if line_type.name == 'tx':
185 position = positions['tx']
206 186 positions['tx'] += 1
207
208 if line_type.name=='tr':
209 line.position = positions['tr']
187 elif line_type.name == 'tr':
188 position = positions['tr']
210 189 positions['tr'] += 1
211
212 line.save()
213 lines.append(line)
214
215 for line, line_data in zip(lines, data['lines']):
216 if 'TX_ref' in line_data:
217 params = json.loads(line.params)
218 if line_data['TX_ref'] in (0, '0'):
219 params['TX_ref'] = '0'
190 else:
191 position = 0
192 line, dum = RCLine.objects.update_or_create(
193 rc_configuration=self,
194 channel=i,
195 position=position,
196 defaults={
197 'line_type': line_type,
198 'params': json.dumps(line_data['params'])
199 }
200 )
201
202 for i, line in enumerate(self.get_lines()):
203 line_params = json.loads(line.params)
204 if 'TX_ref' in line_params:
205 if line_params['TX_ref'] in (0, '0'):
206 line_params['TX_ref'] = '0'
220 207 else:
221 params['TX_ref'] = [l.pk for l in lines if l.line_type.name=='tx' and line_data['TX_ref'] in l.get_name()][0]
222 line.params = json.dumps(params)
208 ref_id = '{}'.format(line_params['TX_ref'])
209 ref_line = params['lines']['byId'][ref_id]
210 line_params['TX_ref'] = RCLine.objects.get(
211 rc_configuration=self,
212 params=json.dumps(ref_line['params'])
213 ).pk
214 line.params = json.dumps(line_params)
223 215 line.save()
224 216
225 217
@@ -239,7 +231,6 class RCConfiguration(Configuration):
239 231
240 232 def get_pulses(self, binary=True):
241 233
242
243 234 pulses = [line.pulses_as_points() for line in self.get_lines()]
244 235 tuples = [tup for tups in pulses for tup in tups]
245 236 points = set([x for tup in tuples for x in tup])
@@ -250,7 +241,7 class RCConfiguration(Configuration):
250 241
251 242 for x in points:
252 243 dum = []
253 for i,tups in enumerate(pulses):
244 for i, tups in enumerate(pulses):
254 245 ups = [tup[0] for tup in tups]
255 246 dws = [tup[1] for tup in tups]
256 247 if x in ups:
@@ -353,16 +344,6 class RCConfiguration(Configuration):
353 344
354 345 return '\n'.join(['{}'.format(x) for x in data])
355 346
356
357 def update_from_file(self, filename):
358 '''
359 Update instance from file
360 '''
361
362 f = RCFile(filename)
363 self.dict_to_parms(f.data)
364 self.update_pulses()
365
366 347 def update_pulses(self):
367 348
368 349 for line in self.get_lines():
@@ -398,7 +379,6 class RCConfiguration(Configuration):
398 379 ax.text(x, N, '%s' % n, size=10)
399 380 n += 1
400 381
401
402 382 labels.reverse()
403 383 ax.set_yticks(range(len(labels)))
404 384 ax.set_yticklabels(labels)
@@ -472,26 +452,32 class RCConfiguration(Configuration):
472 452
473 453 return components(plot, CDN)
474 454
455 def request(self, cmd, method='get', **kwargs):
456
457 req = getattr(requests, method)(self.device.url(cmd), **kwargs)
458 payload = req.json()
459
460 return payload
461
475 462 def status_device(self):
476 463
477 464 try:
478 465 self.device.status = 0
479 req = requests.get(self.device.url('status'))
480 payload = req.json()
481 if payload['status']=='enabled':
466 payload = self.request('status')
467 if payload['status']=='enable':
482 468 self.device.status = 3
483 elif payload['status']=='disabled':
469 elif payload['status']=='disable':
484 470 self.device.status = 2
485 471 else:
486 472 self.device.status = 1
487 473 self.device.save()
488 self.message = payload['status']
474 self.message = 'RC status: {}'.format(payload['status'])
489 475 return False
490 476 except Exception as e:
491 477 if 'No route to host' not in str(e):
492 478 self.device.status = 4
493 479 self.device.save()
494 self.message = str(e)
480 self.message = 'RC status: {}'.format(str(e))
495 481 return False
496 482
497 483 self.device.save()
@@ -500,16 +486,17 class RCConfiguration(Configuration):
500 486 def reset_device(self):
501 487
502 488 try:
503 req = requests.post(self.device.url('reset'))
504 payload = req.json()
489 payload = self.request('reset', 'post')
505 490 if payload['reset']=='ok':
506 self.message = 'RC restarted'
491 self.message = 'RC restarted OK'
492 self.device.status = 2
493 self.device.save()
507 494 else:
508 self.message = 'RC restart not ok'
495 self.message = 'RC restart fail'
509 496 self.device.status = 4
510 497 self.device.save()
511 498 except Exception as e:
512 self.message = str(e)
499 self.message = 'RC reset: {}'.format(str(e))
513 500 return False
514 501
515 502 return True
@@ -517,14 +504,12 class RCConfiguration(Configuration):
517 504 def stop_device(self):
518 505
519 506 try:
520 req = requests.post(self.device.url('stop'))
521 payload = req.json()
507 payload = self.request('stop', 'post')
508 self.message = 'RC stop: {}'.format(payload['stop'])
522 509 if payload['stop']=='ok':
523 510 self.device.status = 2
524 511 self.device.save()
525 self.message = 'RC stopped'
526 512 else:
527 self.message = 'RC stop not ok'
528 513 self.device.status = 4
529 514 self.device.save()
530 515 return False
@@ -533,7 +518,7 class RCConfiguration(Configuration):
533 518 self.device.status = 4
534 519 else:
535 520 self.device.status = 0
536 self.message = str(e)
521 self.message = 'RC stop: {}'.format(str(e))
537 522 self.device.save()
538 523 return False
539 524
@@ -542,21 +527,19 class RCConfiguration(Configuration):
542 527 def start_device(self):
543 528
544 529 try:
545 req = requests.post(self.device.url('start'))
546 payload = req.json()
530 payload = self.request('start', 'post')
531 self.message = 'RC start: {}'.format(payload['start'])
547 532 if payload['start']=='ok':
548 533 self.device.status = 3
549 534 self.device.save()
550 self.message = 'RC running'
551 535 else:
552 self.message = 'RC start not ok'
553 536 return False
554 537 except Exception as e:
555 538 if 'No route to host' not in str(e):
556 539 self.device.status = 4
557 540 else:
558 541 self.device.status = 0
559 self.message = str(e)
542 self.message = 'RC start: {}'.format(str(e))
560 543 self.device.save()
561 544 return False
562 545
@@ -587,16 +570,16 class RCConfiguration(Configuration):
587 570 data.extend((129, 1))
588 571
589 572 try:
590 req = requests.post(self.device.url('write'), data=b64encode(data))
591 payload = req.json()
573 payload = self.request('write', 'post', data=b64encode(data))
574
592 575 if payload['write']=='ok':
593 self.device.status = 2
576 self.device.status = 3
594 577 self.device.save()
595 self.message = 'RC configured'
578 self.message = 'RC configured and started'
596 579 else:
597 580 self.device.status = 1
598 581 self.device.save()
599 self.message = 'RC write not ok'
582 self.message = 'RC write: {}'.format(payload['write'])
600 583 return False
601 584
602 585 except Exception as e:
@@ -604,13 +587,17 class RCConfiguration(Configuration):
604 587 self.device.status = 4
605 588 else:
606 589 self.device.status = 0
607 self.message = str(e)
590 self.message = 'RC write: {}'.format(str(e))
608 591 self.device.save()
609 592 return False
610 593
611 594 return True
612 595
613 596
597 def get_absolute_url_import(self):
598 return reverse('url_import_rc_conf', args=[str(self.id)])
599
600
614 601 class RCLineCode(models.Model):
615 602
616 603 name = models.CharField(max_length=40)
@@ -656,9 +643,23 class RCLine(models.Model):
656 643 if self.rc_configuration:
657 644 return u'%s - %s' % (self.rc_configuration, self.get_name())
658 645
646 def jsonify(self):
647
648 data = {}
649 data['params'] = json.loads(self.params)
650 data['id'] = '{}'.format(self.pk)
651 data['line_type'] = self.line_type.name
652 data['name'] = self.get_name()
653 if data['line_type']=='codes':
654 data['params']['code'] = RCLineCode.objects.get(pk=data['params']['code']).name
655
656 return data
657
658
659 659 def clone(self, **kwargs):
660 660
661 661 self.pk = None
662 self.id = None
662 663
663 664 for attr, value in kwargs.items():
664 665 setattr(self, attr, value)
@@ -940,6 +941,9 class RCLine(models.Model):
940 941 @staticmethod
941 942 def array_to_points(X):
942 943
944 if X.size==0:
945 return []
946
943 947 d = X[1:]-X[:-1]
944 948
945 949 up = np.where(d==1)[0]
@@ -330,14 +330,14 def import_file(request, conf_id):
330 330 form = RCImportForm(request.POST, request.FILES)
331 331 if form.is_valid():
332 332 try:
333 #if True:
334 conf.update_from_file(request.FILES['file_name'])
333 data = conf.import_from_file(request.FILES['file_name'])
334 conf.dict_to_parms(data)
335 conf.update_pulses()
335 336 messages.success(request, 'Configuration "%s" loaded succesfully' % request.FILES['file_name'])
336 337 return redirect(conf.get_absolute_url_edit())
337 338
338 339 except Exception as e:
339 messages.error(request, 'Error parsing file: "%s" - %s' % (request.FILES['file_name'], e))
340
340 messages.error(request, 'Error parsing file: "%s" - %s' % (request.FILES['file_name'], repr(e)))
341 341 else:
342 342 messages.warning(request, 'Your current configuration will be replaced')
343 343 form = RCImportForm()
@@ -43,7 +43,7 class KmUnitWidget(forms.widgets.TextInput):
43 43 html = '''<div class="col-md-12 col-no-padding">
44 44 <div class="col-md-5 col-no-padding"><input type="{0}" step="any" {1} class="form-control" id="id_{2}" name="{3}" value="{4}"></div>
45 45 <div class="col-md-1 col-no-padding">Km</div>
46 <div class="col-md-5 col-no-padding"><input type="{0}" {1} class="form-control" id="id_{2}_unit" value="{5}"></div>
46 <div class="col-md-5 col-no-padding"><input type="{0}" step="any" {1} class="form-control" id="id_{2}_unit" value="{5}"></div>
47 47 <div class="col-md-1 col-no-padding">Units</div></div><br>'''.format(input_type, disabled, label, name, value, unit)
48 48
49 49 script = '''<script type="text/javascript">
@@ -92,7 +92,7 class UnitKmWidget(forms.widgets.TextInput):
92 92 label += '_{0}_{1}'.format(attrs['line'].pk, name.split('|')[0])
93 93
94 94 html = '''<div class="col-md-12 col-no-padding">
95 <div class="col-md-5 col-no-padding"><input type="number" {0} class="form-control" id="id_{1}_unit" name="{2}" value="{3}"></div>
95 <div class="col-md-5 col-no-padding"><input type="number" step="any" {0} class="form-control" id="id_{1}_unit" name="{2}" value="{3}"></div>
96 96 <div class="col-md-1 col-no-padding">Units</div>
97 97 <div class="col-md-5 col-no-padding"><input type="number" step="any" {4} class="form-control" id="id_{5}" value="{6}"></div>
98 98 <div class="col-md-1 col-no-padding">Km</div></div>'''.format(disabled, label, name, value, disabled, label, km)
@@ -136,7 +136,7 class KmUnitHzWidget(forms.widgets.TextInput):
136 136 html = '''<div class="col-md-12 col-no-padding">
137 137 <div class="col-md-3 col-no-padding"><input type="number" step="any" {0} class="form-control" id="id_{1}" name="{2}" value="{3}"></div>
138 138 <div class="col-md-1 col-no-padding">Km</div>
139 <div class="col-md-3 col-no-padding"><input type="number" {4} class="form-control" id="id_{1}_unit" value="{5}"></div>
139 <div class="col-md-3 col-no-padding"><input type="number" step="any" {4} class="form-control" id="id_{1}_unit" value="{5}"></div>
140 140 <div class="col-md-1 col-no-padding">Units</div>
141 141 <div class="col-md-3 col-no-padding"><input type="number" step="any" {4} class="form-control" id="id_{1}_hz" value="{6}"></div>
142 142 <div class="col-md-1 col-no-padding">Hz</div>
@@ -188,7 +188,7 class KmUnitDcWidget(forms.widgets.TextInput):
188 188 html = '''<div class="col-md-12 col-no-padding">
189 189 <div class="col-md-3 col-no-padding"><input type="number" step="any" {0} class="form-control" id="id_{1}" name="{2}" value="{3}"></div>
190 190 <div class="col-md-1 col-no-padding">Km</div>
191 <div class="col-md-3 col-no-padding"><input type="number" {4} class="form-control" id="id_{1}_unit" value="{5}"></div>
191 <div class="col-md-3 col-no-padding"><input type="number" step="any" {4} class="form-control" id="id_{1}_unit" value="{5}"></div>
192 192 <div class="col-md-1 col-no-padding">Units</div>
193 193 <div class="col-md-3 col-no-padding"><input type="number" step="any" {4} class="form-control" id="id_{1}_dc" value="{6}"></div>
194 194 <div class="col-md-1 col-no-padding">DC[%]</div>
@@ -231,7 +231,11 class DefaultWidget(forms.widgets.TextInput):
231 231 name = attrs.get('name', label)
232 232 if 'line' in attrs:
233 233 label += '_{0}_{1}'.format(attrs['line'].pk, name.split('|')[0])
234 html = '<div class="col-md-12 col-no-padding"><div class="col-md-5 col-no-padding"><input {0} type="{1}" class="form-control" id="id_{2}" name="{3}" value="{4}"></div></div>'.format(disabled, itype, label, name, value)
234
235 if itype=='number':
236 html = '<div class="col-md-12 col-no-padding"><div class="col-md-5 col-no-padding"><input {0} type="{1}" step="any" class="form-control" id="id_{2}" name="{3}" value="{4}"></div></div>'.format(disabled, itype, label, name, value)
237 else:
238 html = '<div class="col-md-12 col-no-padding"><div class="col-md-5 col-no-padding"><input {0} type="{1}" step="any" class="form-control" id="id_{2}" name="{3}" value="{4}"></div></div>'.format(disabled, itype, label, name, value)
235 239
236 240 if 'last_height' in label or 'number_of_samples' in label:
237 241 script = '''<script type="text/javascript">
General Comments 0
You need to be logged in to leave comments. Login now