##// END OF EJS Templates
Update RC model, RC api for testing...
Juan C. Espinoza -
r185:66e7f4294add
parent child
Show More
@@ -1,11 +1,14
1 from django.shortcuts import render, redirect, get_object_or_404, HttpResponse
1
2 2 from datetime import datetime
3 3
4 from django.db import models
4 try:
5 5 from polymorphic.models import PolymorphicModel
6 except:
7 from polymorphic import PolymorphicModel
6 8
9 from django.db import models
7 10 from django.core.urlresolvers import reverse
8
11 from django.shortcuts import get_object_or_404
9 12
10 13 CONF_STATES = (
11 14 (0, 'Disconnected'),
@@ -31,6 +34,7 DEV_STATES = (
31 34 (1, 'Connected'),
32 35 (2, 'Configured'),
33 36 (3, 'Running'),
37 (4, 'Unknown'),
34 38 )
35 39
36 40 DEV_TYPES = (
@@ -124,12 +128,15 class Device(models.Model):
124 128
125 129 return color
126 130
127 @property
128 def url(self):
131 def url(self, path=None):
129 132
133 if path:
134 return 'http://{}:{}/{}/'.format(self.ip_address, self.port_address, path)
135 else:
130 136 return 'http://{}:{}/'.format(self.ip_address, self.port_address)
131 137
132 138 def get_absolute_url(self):
139
133 140 return reverse('url_device', args=[str(self.id)])
134 141
135 142
@@ -570,27 +577,32 class Configuration(PolymorphicModel):
570 577
571 578 def status_device(self):
572 579
573 raise NotImplementedError("This method should be implemented in %s Configuration model" %str(self.device.device_type.name).upper())
580 self.message = 'Function not implemented'
581 return False
574 582
575 583
576 584 def stop_device(self):
577 585
578 raise NotImplementedError("This method should be implemented in %s Configuration model" %str(self.device.device_type.name).upper())
586 self.message = 'Function not implemented'
587 return False
579 588
580 589
581 590 def start_device(self):
582 591
583 raise NotImplementedError("This method should be implemented in %s Configuration model" %str(self.device.device_type.name).upper())
592 self.message = 'Function not implemented'
593 return False
584 594
585 595
586 596 def write_device(self, parms):
587 597
588 raise NotImplementedError("This method should be implemented in %s Configuration model" %str(self.device.device_type.name).upper())
598 self.message = 'Function not implemented'
599 return False
589 600
590 601
591 602 def read_device(self):
592 603
593 raise NotImplementedError("This method should be implemented in %s Configuration model" %str(self.device.device_type.name).upper())
604 self.message = 'Function not implemented'
605 return False
594 606
595 607
596 608 def get_absolute_url(self):
@@ -1141,7 +1141,7 def dev_conf_start(request, id_conf):
1141 1141 else:
1142 1142 messages.error(request, conf.message)
1143 1143
1144 conf.status_device()
1144 #conf.status_device()
1145 1145
1146 1146 return redirect(conf.get_absolute_url())
1147 1147
@@ -1155,7 +1155,7 def dev_conf_stop(request, id_conf):
1155 1155 else:
1156 1156 messages.error(request, conf.message)
1157 1157
1158 conf.status_device()
1158 #conf.status_device()
1159 1159
1160 1160 return redirect(conf.get_absolute_url())
1161 1161
@@ -1176,17 +1176,9 def dev_conf_write(request, id_conf):
1176 1176
1177 1177 conf = get_object_or_404(Configuration, pk=id_conf)
1178 1178
1179 answer = conf.write_device()
1180 conf.status_device()
1181
1182 if answer:
1179 if conf.write_device():
1183 1180 messages.success(request, conf.message)
1184
1185 #Creating a historical configuration
1186 1181 conf.clone(type=1, template=False)
1187
1188 #Original configuration
1189 conf = DevConfModel.objects.get(pk=id_conf)
1190 1182 else:
1191 1183 messages.error(request, conf.message)
1192 1184
@@ -1202,7 +1194,7 def dev_conf_read(request, id_conf):
1202 1194 if request.method=='GET':
1203 1195
1204 1196 parms = conf.read_device()
1205 conf.status_device()
1197 #conf.status_device()
1206 1198
1207 1199 if not parms:
1208 1200 messages.error(request, conf.message)
@@ -4,6 +4,7 import json
4 4 import requests
5 5 import numpy as np
6 6 from base64 import b64encode
7 from struct import pack
7 8
8 9 from django.db import models
9 10 from django.core.urlresolvers import reverse
@@ -455,65 +456,113 class RCConfiguration(Configuration):
455 456 def status_device(self):
456 457
457 458 try:
458 req = requests.get(self.device.url)
459 req = requests.get(self.device.url('status'))
459 460 payload = req.json()
460 461 if payload['status']=='ok':
461 self.device.status = 3
462 else:
463 462 self.device.status = 1
464 except:
463 else:
464 self.device.status = 0
465 except Exception as e:
465 466 self.device.status = 0
467 self.message = str(e)
468 return False
466 469
467 470 self.device.save()
468
469 return self.device.status
471 return True
470 472
471 473
472 474 def reset_device(self):
473 475
474 payload = bytearray()
475 payload.extend(self.add_cmd('RESTART'))
476 data = b64encode(payload)
477 req = requests.put(self.device.url, data)
478
479 if data==req.text.encode('utf8'):
480 return 1
476 try:
477 req = requests.post(self.device.url('reset'))
478 if 'ok' in req.text:
479 self.message = 'RC restarted'
481 480 else:
482 return 0
481 self.message = 'RC restart not ok'
482 self.device.status = 4
483 self.device.save()
484 except Exception as e:
485 self.message = str(e)
486 return False
483 487
484 def stop_device(self):
488 return True
485 489
486 payload = bytearray()
487 payload.extend(self.add_cmd('DISABLE'))
488 data = b64encode(payload)
489 req = requests.put(self.device.url, data)
490 def stop_device(self):
490 491
491 if data==req.text.encode('utf8'):
492 return 1
492 try:
493 req = requests.post(self.device.url('stop'))
494 if 'ok' in req.text:
495 self.device.status = 2
496 self.device.save()
497 self.message = 'RC stopped'
493 498 else:
494 return 0
499 self.message = 'RC stop not ok'
500 self.device.status = 4
501 self.device.save()
502 return False
503 except Exception as e:
504 self.message = str(e)
505 return False
495 506
496 def start_device(self):
507 return True
497 508
498 payload = bytearray()
499 payload.extend(self.add_cmd('ENABLE'))
500 data = b64encode(payload)
501 req = requests.put(self.device.url, data)
509 def start_device(self):
502 510
503 if data==req.text.encode('utf8'):
504 return 1
511 try:
512 req = requests.post(self.device.url('start'))
513 if 'ok' in req.text:
514 self.device.status = 3
515 self.device.save()
516 self.message = 'RC running'
505 517 else:
506 return 0
518 self.message = 'RC start not ok'
519 return False
520 except Exception as e:
521 self.message = str(e)
522 return False
523
524 return True
507 525
508 526 def write_device(self):
509 527
510 data = b64encode(self.parms_to_binary(dat=False))
511 req = requests.put(self.device.url, data)
512 print(req.text)
513 if data==req.text.encode('utf8'):
514 return 1
528 values = zip(self.get_pulses(),
529 [x-1 for x in self.get_delays()])
530 payload = ''
531
532 for tup in values:
533 vals = pack('<HH', *tup)
534 payload += '\x05'+vals[0]+'\x04'+vals[1]+'\x05'+vals[2]+'\x05'+vals[3]
535
536 try:
537 ## reset
538 if not self.reset_device():
539 return False
540 ## stop
541 if not self.stop_device():
542 return False
543 ## write clock divider
544 req = requests.post(self.device.url('divisor'),
545 {'divisor': '{:d}'.format(self.clock_divider-1)})
546 if 'ok' not in req.text:
547 self.message = 'Error configuring RC clock divider'
548 return False
549 ## write pulses & delays
550 req = requests.post(self.device.url('write'), data=b64encode(payload))
551 if 'ok' in req.text:
552 self.device.status = 2
553 self.device.save()
554 self.message = 'RC configured'
515 555 else:
516 return 0
556 self.device.status = 4
557 self.device.save()
558 self.message = 'RC write not ok'
559 return False
560
561 except Exception as e:
562 self.message = str(e)
563 return False
564
565 return True
517 566
518 567
519 568 class RCLineCode(models.Model):
@@ -873,6 +922,6 class RCLine(models.Model):
873 922
874 923 delays = len(delay)
875 924
876 Y = [(ipp*x+before+delay[x%delays], ipp*x+width+before+delay[x%delays]+after) for x in range(ntx)]
925 Y = [(int(ipp*x+before+delay[x%delays]+sync), int(ipp*x+width+before+delay[x%delays]+after+sync)) for x in range(ntx)]
877 926
878 927 return Y
@@ -7,7 +7,7 urlpatterns = (
7 7 url(r'^(?P<conf_id>-?\d+)/import/$', views.import_file, name='url_import_rc_conf'),
8 8 url(r'^(?P<conf_id>-?\d+)/edit/$', views.conf_edit, name='url_edit_rc_conf'),
9 9 url(r'^(?P<conf_id>-?\d+)/plot/$', views.plot_pulses, name='url_plot_rc_pulses'),
10 url(r'^(?P<conf_id>-?\d+)/plot2/$', views.plot_pulses2, name='url_plot_rc_pulses'),
10 url(r'^(?P<conf_id>-?\d+)/plot2/$', views.plot_pulses2, name='url_plot_rc_pulses2'),
11 11 #url(r'^(?P<id_conf>-?\d+)/write/$', 'apps.main.views.dev_conf_write', name='url_write_rc_conf'),
12 12 #url(r'^(?P<id_conf>-?\d+)/read/$', 'apps.main.views.dev_conf_read', name='url_read_rc_conf'),
13 13
@@ -1,134 +1,98
1 1 '''
2 Created on Dec 2, 2014
2 API to configure new Radar controller
3 3
4 @author: Miguel Urco
5
6 eth_device decorator is used to implement an api to ethernet devices.
7 When eth_device decorator is used it adds two parameters to any function (ip and port)
8
9 #Definition
10
11 @eth_device
12 def enable_rf()
13 cmd = "xxxxx"
14 payload = "xxxxxx"
15
16 return cmd, payload
17
18 #How to call this function:
19 answer = enable_rf(ip, port)
20 4
5 @author: Juan C. Espinoza
21 6 '''
22 7
23 from devices.jro_device import eth_device, IdClass
24
25 ID_CLASS = IdClass["rc"]
26
27 CMD_RESET =0X01
28 CMD_ENABLE =0X02
29 CMD_CHANGEIP =0X03
30 CMD_STATUS =0X04
31 CMD_DISABLE =0X02
32 CMD_ECHO =0XFE
8 import os
9 import json
10 import requests
11 from struct import pack
12 from base64 import b64encode
33 13
34 RC_CMD_RESET =0X10
35 RC_CMD_WRITE =0x50
36 RC_CMD_READ =0x8000
14 class RCApi(object):
37 15
38 @eth_device(ID_CLASS)
39 def reset():
16 def __init__(self, ip, port=80):
40 17
41 cmd = CMD_RESET
42 payload = ""
18 self.url = 'http://{}:{}/'.format(ip, port)
19 self.params = None
43 20
44 return cmd, payload
21 def load(self, filename):
45 22
46 @eth_device(ID_CLASS)
47 def change_ip(ip, mask="255.255.255.0", gateway="0.0.0.0"):
23 self.params = json.load(open(filename))
24 print 'RC Configuration: {}'.format(self.params['name'])
48 25
49 cmd = CMD_CHANGEIP
50 payload = ip + '/' + mask + '/' + gateway
26 def status(self):
51 27
52 return cmd, payload
28 url = os.path.join(self.url, 'status')
29 req = requests.get(url)
30 return req.json()
53 31
54 @eth_device(ID_CLASS)
55 def status():
32 def read(self):
56 33
57 cmd = CMD_STATUS
58 payload = ""
34 url = os.path.join(self.url, 'read')
35 req = requests.get(url)
36 return req.json()
59 37
60 return cmd, payload
38 def stop(self):
61 39
62 @eth_device(ID_CLASS)
63 def echo():
40 url = os.path.join(self.url, 'stop')
41 req = requests.post(url)
42 return req.json()
64 43
65 cmd = CMD_ECHO
66 payload = ""
44 def reset(self):
67 45
68 return cmd, payload
46 url = os.path.join(self.url, 'reset')
47 req = requests.post(url)
48 return req.json()
69 49
70 @eth_device(ID_CLASS)
71 def read_all_device():
50 def start(self):
72 51
73 payload = ""
52 url = os.path.join(self.url, 'start')
53 req = requests.post(url)
54 return req.json()
74 55
75 return CR_CMD_READ, payload
56 def write(self):
76 57
77 @eth_device(ID_CLASS)
78 def write_all_device(payload):
58 url_write = os.path.join(self.url, 'write')
59 url_divider = os.path.join(self.url, 'divisor')
79 60
80 return CR_CMD_WRITE, payload
61 values = zip(self.params['pulses'],
62 [x-1 for x in self.params['delays']])
63 payload = ''
81 64
82 def read_config(ip, port):
83 """
84 Output:
85 parms : Dictionary with keys
65 for tup in values:
66 vals = pack('<HH', *tup)
67 payload += '\x05'+vals[0]+'\x04'+vals[1]+'\x05'+vals[2]+'\x04'+vals[3]
86 68
87 """
88 payload = read_all_device(ip, port)
69 req = requests.post(url_divider,
70 data={'divisor':int(self.params['clock_divider'])-1})
89 71
90 return data.rc_str_to_dict(payload)
72 if 'ok' not in req.text:
73 print 'Error sending divider'
74 return False
91 75
92 def write_config(ip, port, parms):
93 """
94 Input:
95 ip :
96 port :
97 parms : Dictionary with keys
76 req = requests.post(url_write,
77 data=b64encode(payload))
78 return req.json()
98 79
99 """
100
101 payload = data.dict_to_rc_str(parms)
102
103 answer = write_all_device(ip, port, payload)
104
105 return answer
106
107 def __get_low_byte(valor):
108
109 return ord(valor & 0x00FF)
80 if __name__ == '__main__':
110 81
111 def __get_high_byte(valor):
82 ip = '10.10.10.100'
83 filename = '/home/jespinoza/Downloads/rc_150EEJ.json'
112 84
113 return ord((valor & 0xFF00) >> 8)
85 rc = RCApi(ip)
86 rc.load(filename)
114 87
115 @eth_device(ID_CLASS)
116 def write_ram_memory(vector_valores, vector_tiempos):
88 print rc.status()
89 print rc.reset()
90 print rc.stop()
91 print rc.write()
92 print rc.start()
117 93
118 l1 = len(vector_valores)
119 l2 = len(vector_tiempos)
120 94
121 cad = ""
122 95
123 for i in range(l1):
124 cad += ord(84) + __get_low_byte(vector_valores[i]) + ord(85) + __get_high_byte(vector_valores[i]) + \
125 ord(84) + __get_low_byte(vector_tiempos[i]) + ord(85) + __get_high_byte(vector_tiempos[i])
126 96
127 return RC_CMD_WRITE, cad
128 97
129 if __name__ == '__main__':
130 ip = "10.10.20.150"
131 port = 2000
132 98
133 print(status(ip, port))
134 print(read_config(ip, port))
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now