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