-
Notifications
You must be signed in to change notification settings - Fork 1
/
gen.py
executable file
·236 lines (190 loc) · 6.74 KB
/
gen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env python3
import sys, os
from protos import load, cformats
from semantic import version
from string import Template
from atp import FORMATS as formats
from settings import DEST, PROTO
import argparse
template_c = """// Generated from version ${VERSION} of semantic
#include "atp.h"
${FUNCTIONS}
int AtpDecode(int id,
unsigned char *ucharv, int ucharc,
unsigned int *ushortv, int ushortc,
unsigned long int *uintv, int uintc,
char *charv, int charc,
int *shortv, int shortc,
long int *intv, int intc,
float *floatv, int floatc)
{${DECODERS}
return 0;
}
"""
template_decoder = """
if (id == ${ID}) {
${FUNCTION}(${ARGV});
return 1;
}"""
template_h = """// Generated from version ${VERSION} of semantic
#ifndef _${PROTO_UPPER}_H_
#define _${PROTO_UPPER}_H_
#define BOARD_ID ${ID}
#define BOARD_NAME ${PROTO}
${PROTOTYPES}
int AtpDecode(int id,
unsigned char *ucharv, int ucharc,
unsigned int *ushortv, int ushortc,
unsigned long int *uintv, int uintc,
char *charv, int charc,
int *shortv, int shortc,
long int *intv, int intc,
float *floatv, int floatc);
#endif // _${PROTO_UPPER}_H_
"""
template_encoder_c = """
void ${FUNCTION}(${ARGS}) {
char bytes[] = {
129,
${ID},${CODE}
128
};
SendBytes(bytes, ${COUNT});
}
"""
template_arg = """
${ARG},"""
template_long_arg = """
((char*)&${ARG})[${I}],"""
template_encoder_h = """
void ${FUNCTION}(${ARGS});
"""
template_decoder_c = """
// You should redefine this function
__attribute__((weak)) void ${FUNCTION}(${ARGS}) {${CODE}}
"""
template_decoder_h = """
void ${FUNCTION}(${ARGS});
"""
class PicGenerator:
arrayname = { 'B': 'ucharv',
'H': 'ushortv',
'I': 'uintv',
'b': 'charv',
'h': 'shortv',
'i': 'intv',
'f': 'floatv' }
def __init__(self, dest):
if not os.path.exists(dest):
print("Creating directory '%s'" %dest)
os.makedirs(dest)
self.dest = dest
self.protos = load()
self.formats = dict((v[1],k) for k, v in formats.items())
def genAll(self):
for proto_name in self.protos:
proto = self.protos[proto_name]
self.genProto(proto_name, proto)
def genProto(self, proto_name, proto):
print("Generating files for '%s'..." %proto_name)
cfile = open("%s/atp-%s.c" %(self.dest, proto_name.lower()), 'w')
hfile = open("%s/atp-%s.h" %(self.dest, proto_name.lower()), 'w')
params = {}
params['VERSION'] = version
params['PROTO'] = proto_name
params['PROTO_UPPER'] = proto_name.upper()
params['ID'] = proto['id']
params['PROTOTYPES'] = ''
params['FUNCTIONS'] = ''
params['DECODERS'] = ''
for packet_name in proto['packets']:
packet = proto['packets'][packet_name]
c, h, d = self.genPacket(packet_name, packet)
params['FUNCTIONS'] += c
params['PROTOTYPES'] += h
params['DECODERS'] += d
cfile.write(Template(template_c).substitute(params))
hfile.write(Template(template_h).substitute(params))
def genPacket(self, packet_name, packet):
c = ''
h = ''
d = ''
if packet['transmitter'] == 'arm' or packet['transmitter'] == 'both':
_c, _h, _d = self.genDecoder(packet_name, packet)
c += _c
h += _h
d += _d
if packet['transmitter'] == 'pic' or packet['transmitter'] == 'both':
_c, _h = self.genEncoder(packet_name, packet)
c += _c
h += _h
return (c, h, d)
def genDecoder(self, packet_name, packet):
params = {}
params['ID'] = packet['id']
params['FUNCTION'] = 'On' + packet_name[0].upper() + packet_name[1:]
params['ARGS'] = ', '.join(map(lambda x: cformats[packet['args'][x]]+' '+x, packet['args']))
params['ARGV'] = ''
counts = dict(zip(self.formats,map(lambda x: 0, self.formats)))
for arg in packet['args']:
type = packet['args'][arg]
params['ARGV'] += self.arrayname[type] + "[%d], " %counts[type]
counts[type] += 1
params['ARGV'] = params['ARGV'][:-2]
if packet_name == 'getId':
params['CODE'] = ' SendBoardId(); '
elif packet_name == 'test':
params['CODE'] = ' SendTest(B, H, I, b, h, i, f); '
else:
params['CODE'] = ' SendUnimplemented(); '
print("\tdecoder '%s'" %params['FUNCTION'])
c = Template(template_decoder_c).substitute(params)
h = Template(template_decoder_h).substitute(params)
d = Template(template_decoder).substitute(params)
return (c, h, d)
def genEncoder(self, packet_name, packet):
params = {}
params['FUNCTION'] = 'Send' + packet_name[0].upper() + packet_name[1:]
params['ARGS'] = ', '.join(map(lambda x: cformats[packet['args'][x]]+' '+x, packet['args']))
params['ID'] = packet['id']
params['COUNT'] = 3
params['CODE'] = ''
for arg in packet['args']:
count, code = self.genArg(arg, packet['args'][arg])
params['COUNT'] += count
params['CODE'] += code
print("\tencoder '%s'" %params['FUNCTION'])
c = Template(template_encoder_c).substitute(params)
h = Template(template_encoder_h).substitute(params)
return (c, h)
def genArg(self, arg, format):
format = self.formats[format]
length = format & 0b1111
code = Template(template_arg).substitute({'ARG': format})
if length == 1:
code += Template(template_arg).substitute({'ARG': arg})
else:
for i in range(0, length):
code += Template(template_long_arg).substitute({'ARG': arg, 'I': i})
return (length+1, code)
if __name__=="__main__":
parser = argparse.ArgumentParser(description='Generate pic source code to encode and decode ATP paquet with semantic.')
parser.add_argument('-d', '--destination', dest='dest', help='Set destination directory.')
parser.add_argument('-p', '--proto', dest='proto', help='Generate source code for a specific protocol/pic.')
args = parser.parse_args()
if args.dest:
dest = args.dest
else:
dest = DEST
if args.proto:
proto = args.proto
else:
proto = PROTO
proto = proto.capitalize()
print("Generating files for %s protocol" %proto)
print("Saving files in '%s'\n" %dest)
generator = PicGenerator(dest)
if proto == "All":
generator.genAll()
else:
generator.genProto(proto, generator.protos[proto])