-
Notifications
You must be signed in to change notification settings - Fork 20
/
cfg
executable file
·498 lines (455 loc) · 19.2 KB
/
cfg
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#!/usr/bin/env python3
"""
This program is part of MoaT.
Its job is simply to extract values from a YAML-formatted config file.
"""
from Cfg import Cfg
import sys
import os
import re
### copied from port.h
PO_OFF=0
PO_ON=1
PO_Z=2
PO_PULLUP=3
PFLG_ALERT= (1<<2)
PFLG_ALT = (1<<3)
PFLG_ALT2 = (1<<4)
### copied from adc.h
ADC_VBG=1
ADC_VGND=2
ADC_VTEMP=3
ADC_ALT=(1<<3)
ADC_REF=(1<<4)
ADC_ALERT=(1<<5)
### copied from temp.h
TEMP_ALERT=(1<<5)
### copied from pwm.h
PWM_ALERT=(1<<0)
PWM_FORCE=(1<<1)
### copied from count.h
CF_ALERTING=(1<<0)
CF_FALLING_ONLY=(1<<1)
CF_RISING_ONLY=(1<<2)
follow=True
xstr = re.compile("^x([0-9a-fA-F]{2}){1,}$")
# These need to be in the loader
basetypes = ('console',)
def moat_files(s,k):
for f in s.subtree('codes','types'):
if f.startswith('_'):
f = f[1:]
f = 'moat_'+f
if os.path.exists(f+'.c'):
yield f+'.c'
seen = set()
for i in range(int(s.subtree('devices',k,'types','temp'))):
v = s.subtree('devices',k,'temp',str(i))
driver,dev = v.split('=')
if driver in seen:
continue
yield 'temp_{}.h'.format(driver)
seen.add(driver)
def main(cfg_name,*kk):
s = Cfg(cfg_name)
if kk:
mode = ""
for k in kk:
if mode == "":
if k[0] == '.':
if k == '.devs':
print(" ".join(sorted(k for k in s.subtree("devices") if not k.startswith('_'))))
if k == ".follow":
s.follow = True
elif k == ".nofollow":
s.follow = False
else:
mode = k[1:]
else:
did=[]
ks = k.split('.')
res = s.subtree(*ks)
if isinstance(res,dict):
print(" ".join("{}={}".format(a,v) for a,v in s.keyval(*ks)))
elif isinstance(res,(list,tuple)):
print(" ".join(str(x) for x in res))
elif isinstance(res,str) and xstr.match(res):
print(res[1:])
else:
try:
f = float(res)
except Exception:
print(res)
else:
g = int(f)
if float(g) == f:
print(g)
else:
print(f)
elif mode == "hdr":
BL = s.subtree('devices',k,'defs','use_bootloader')
with open("device/"+k+"/_port.h","w") as f:
print("""\
/*
* This file is auto-generated. It contains the list of input/output ports for
* the device "{}".
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,cfg_name), file=f)
for i in range(1, int(s.subtree('devices',k,'types','port'))+1):
v = s.subtree('devices',k,'port',str(i))
flg=0
p=0
if isinstance(v,int): v = str(v)
assert len(v)>=2 and len(v) <=6, v
for vv in v:
if vv >= 'A' and vv <= 'Z':
assert not p
p |= (ord(vv)-ord("A"))<<3
elif vv >= '0' and vv <= '7':
assert not (p&0x7)
p |= ord(vv)-ord("0")
elif vv == "^": flg|=PO_ON
elif vv == "_": flg|=PO_OFF
elif vv == "+": flg|=PO_PULLUP
elif vv == "~": flg|=PO_Z ## high-impedance
elif vv == "/": flg|=PFLG_ALT ## alt switch 1: low vs. pullup
elif vv == "!": flg|=PFLG_ALT2 ## alt switch 2: lw vs. Z
elif vv == "*": flg|=PFLG_ALERT ## participate in alerting
else: assert 0,vv
print('{'+"{},{}".format(p,flg)+'},',file=f)
with open("device/"+k+"/_adc.h","w") as f:
print("""\
/*
* This file is auto-generated. It contains the list of analog inputs for
* the device "{}".
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,cfg_name), file=f)
for i in range(1, int(s.subtree('devices',k,'types','adc'))+1):
v = s.subtree('devices',k,'adc',str(i))
flg=0
p=0
if isinstance(v,int): v = str(v)
assert len(v)>=1 and len(v) <=3
for vv in v:
if vv >= '0' and vv <= '7':
assert not (flg&0xF)
flg |= ord(vv)-ord("0")
p=1
elif vv == "R":
assert not p
flg|=ADC_ALT|ADC_VBG
p=1
elif vv == "G":
assert not p
flg|=ADC_ALT|ADC_VGND
p=1
elif vv == "T":
assert not p
flg|=ADC_ALT|ADC_VTEMP
p=1
elif vv == "-": flg|=ADC_REF ## use ref voltage as max
elif vv == "*": flg|=ADC_ALERT ## participate in alerting
else: assert 0,vv
assert p
print('{'+"{},".format(flg)+'},',file=f)
temp_dr = {}
temp_nam = []
with open("device/"+k+"/_temp.h","w") as f:
print("""\
/*
* This file is auto-generated. It contains the list of temperature inputs for
* the device "{}".
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,cfg_name), file=f)
for i in range(int(s.subtree('devices',k,'types','temp'))):
v = s.subtree('devices',k,'temp',str(i))
flg=0
p=0
if v[-1] == '*':
flg |= TEMP_ALERT
v = v[:-1]
try:
driver,dev = v.split('=')
except ValueError:
raise SyntaxError("expected driver=number, got "+repr(v))
dev = int(dev)
if driver not in temp_dr:
temp_dr[driver] = len(temp_nam)
temp_nam.append(driver)
flg |= temp_dr[driver]
print('{'+"{},{}".format(flg,dev)+'},',file=f)
with open("device/"+k+"/_temp_defs.h","w") as f:
print("""\
/*
* This file is auto-generated. It contains the list of analog inputs for
* the device "{}".
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,cfg_name), file=f)
for dr in temp_nam:
print("TEMP_TC_DEFINE({})".format(dr), file=f)
with open("device/"+k+"/_pwm.h","w") as f:
print("""\
/*
* This file is auto-generated. It contains the list of ports to do PWM with
* on the device "{}".
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,cfg_name), file=f)
seen = set()
for i in range(1, int(s.subtree('devices',k,'types','pwm'))+1):
v = s.subtree('devices',k,'pwm',str(i))
flg = 0
port = 0
p = False
if isinstance(v,int): v = str(v)
assert len(v)>=1 and len(v) <=3
for vv in v:
if vv >= '0' and vv <= '9':
assert not flg, v
port = 10*port+(ord(vv)-ord('0'))
p = True
elif vv == "*": flg|=PWM_ALERT ## participate in alerting
elif vv == "!": flg|=PWM_FORCE ## immediately switch
else: assert 0,vv
assert p, v
if v in seen:
print("Warning: PWM %d is known"%v,file=sys.stderr)
continue
seen.add(v)
print('{'+"{},{}".format(port,flg)+'},',file=f)
with open("device/"+k+"/_count.h","w") as f:
print("""\
/*
* This file is auto-generated. It contains the list of ports to count
* transitions of, on the device "{}".
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,cfg_name), file=f)
seen = set()
for i in range(1, int(s.subtree('devices',k,'types','count'))+1):
v = s.subtree('devices',k,'count',str(i))
flg=0
p=0
if isinstance(v,str):
pin=""
for vv in v:
if vv == '*': flg |= CF_ALERTING
elif vv == '+': flg |= CF_RISING_ONLY
elif vv == '-': flg |= CF_FALLING_ONLY
elif vv >= '0' and vv <= '7':
pin+=vv
else: assert 0,vv
v = int(pin)
if (flg & CF_RISING_ONLY) and (flg & CF_FALLING_ONLY):
raise Exception("Counter %d must choose between falling OR rising edge. Or remove both flags to trigger on each edge."%i)
if v in seen:
print("Warning: Count %d is known"%v,file=sys.stderr)
continue
seen.add(v)
print('{'+"{},{}".format(v,flg)+'},',file=f)
i = 0
typecode = {}
typecodes = []
for a in s.subtree('codes','types'):
if a.startswith('_'):
a = a[1:]
else:
typecode[a]=i
typecodes.append(a)
i += 1
max_t = 2 # config, alert
typecount = [0]*i
for a,v in s.keyval('devices',k,'types'):
v = int(v)
if v and max_t < typecode[a]:
max_t = typecode[a]
typecount[typecode[a]] = v
i = 0
statuscode = {}
statuscodes = []
for a in s.subtree('codes','status'):
if a.startswith('_'):
a = a[1:]
else:
statuscode[a]=i
statuscodes.append(a)
i += 1
max_s = i
with open("device/"+k+"/_nums.h","w") as f:
print("""\
/*
* This file is auto-generated. It contains the number of devices.
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,cfg_name), file=f)
typecount[0] = len(s.subtree('codes','blocks'))
typecount[1] = max_t
for i in range(max_t+1):
a = typecodes[i]
print("{}, // {}".format(typecount[i],a), file=f)
with open("device/"+k+"/_def.h","w") as f:
print("""\
/*
* This file is auto-generated. It contains the device codes.
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,cfg_name), file=f)
for i in range(max_t+1):
a = typecodes[i]
print("TC_DEFINE({})".format(a), file=f)
with open("device/"+k+"/_status.h","w") as f:
print("""\
/*
* This file is auto-generated. It contains the status codes.
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,cfg_name), file=f)
for n,v in statuscode.items():
print("#define S_{} {}".format(n,v), file=f)
print("#define STATUS_MAX {}".format(max_s), file=f)
with open("device/"+k+"/dev_config.h","w") as f:
print("""\
#ifndef device_{}_config_h
#define device_{}_config_h
/*
* This file is auto-generated. It contains a mix of global and local
* definitions because I am lazy.
*
* Do not edit. Talk to '{}' instead.
*/
""".format(k,k,cfg_name), file=f)
i = 0
print("typedef enum _ConfigID {", file=f)
for a in s.subtree('codes','blocks'):
if a.startswith('_'):
a=a[1:]
else:
typecode[a]=i
print(" CfgID_{} = {},".format(a,i), file=f)
i += 1
print(""" CfgID_MAX
#define CFG_MAX CfgID_MAX
} ConfigID;""", file=f)
for a,v in s.keyval('devices',k,'defs'):
if BL and a == "is_bootloader":
continue
try:
v = int(v)
except ValueError:
v = '"{}"'.format(v.replace('\\','\\\\').replace('"','\\"'))
else:
if not v:
continue
print("#define {} {}".format(a.upper(),v), file=f)
ow = s.subtree('devices',k,'defs','is_onewire')
if ow:
print("#define HAVE_ONEWIRE 1", file=f)
print("#define ONEWIRE_"+ow.upper(), file=f)
for a,v in s.keyval('devices',k,'types'):
if a == "config":
v = len(s.subtree('codes','blocks'))
elif a == "alert":
#v = len(s.subtree('codes','types'))
v = max_t+1 # ignore codes above this
else:
v = int(v)
print("#define TC_{} {}".format(a.upper(),typecode[a]), file=f)
if v > 0:
print("#define N_{} {}".format(a.upper(),v), file=f)
owp = s.subtree('devices',k,'defs','onewire_io')
if owp:
assert len(owp) == 2, owp
print("#define ONEWIRE_PORT PORT{}".format(owp[0]), file=f)
print("#define ONEWIRE_PIN PIN{}".format(owp[0]), file=f)
print("#define ONEWIRE_DDR DDR{}".format(owp[0]), file=f)
print("#define ONEWIRE_PBIT {}".format(1<<(int(owp[1]))), file=f)
try:
own = s.subtree('devices',k,'pin_irq',owp)
except KeyError:
own = s.subtree('devices',k,'pin_irq',owp[0])
print("#define ONEWIRE_IRQNUM ({})".format(own), file=f)
if (own < 0):
print("#define ONEWIRE_IRQ INT{}_vect".format(-own-1), file=f)
print("#define ONEWIRE_IER IMSK", file=f)
print("#define ONEWIRE_IFR IFR", file=f)
print("#define ONEWIRE_IFBIT {}".format(1<<(-own-1)), file=f)
else:
print("#define ONEWIRE_IRQ PCINT{}_vect".format(own+int(owp[1])), file=f)
print("#define ONEWIRE_IFR PCICR", file=f)
print("#define ONEWIRE_IFR PCINT{}".format(own>>3), file=f)
if temp_nam:
print("#define N_TEMP_DRIVER {}".format(len(temp_nam)), file=f)
print("""\
#define TC_MAX {}
#endif /* device_{}_config_h */
""".format(max_t+1,k,k), file=f)
elif mode == "type":
print(" ".join("{} {}".format(a,v) for a,v in s.keyval('devices',k,'types')))
elif mode == "cdefs":
BL = s.subtree('devices',k,'defs','use_bootloader')
types = dict((a,int(v)) for a,v in s.keyval('devices',k,'types') if int(v) > 0)
maxtype = max(())
print(" ".join("-D{}=\"{}\"".format(a.upper(),str(v).replace('"','\"')) for a,v in s.keyval('devices',k,'defs') if a != ("is_bootloader" if BL else "")) + " " + " ".join("-DN_{}={}".format(a.upper(),v) for a,v in s.keyval('devices',k,'types') if int(v) > 0))
elif mode == "cfiles":
files = []
BL = s.subtree('devices',k,'defs','use_bootloader')
BI = False if BL else s.subtree('devices',k,'defs','is_bootloader')
ow = s.subtree('devices',k,'defs','is_onewire')
if BL or not BI:
files.append('moat_backend.c')
## does not work, needs to be in bootloader memory
#if BI:
# files.append('boot.c')
if BI:
files.append('moat_loader.c')
if not BL:
files.append('main.c')
files.append('jmp.S')
files.append('dev_data.c')
files.append('config.o')
for f,v in s.keyval('devices',k,'defs'):
if not v: continue
if not f.startswith('have_'): continue
if os.path.exists(f[5:]+'.c'):
files.append(f[5:]+'.c')
if not ow: pass
else:
files.append(ow+'.c')
files.append('onewire.c')
files.append('crc.c')
for f in s.subtree('devices',k,'code'):
files.append(f+'.c')
for f,v in s.keyval('devices',k,'types'):
if not v: continue
if f[0] == '_': continue
if ow == "moat" and ((f in basetypes) if BL else (f not in basetypes) if BI else False):
continue
if os.path.exists(f+'.c'):
files.append(f+'.c')
if ow == "moat" and not BI:
files.extend(moat_files(s,k))
print(" ".join(files))
else:
print("Unknown mode:",mode, file=sys.stderr)
sys.exit(2)
else:
import pprint
pprint.pprint(s.data)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: {} file [type] [key…]".format(sys.argv[0]), file=sys.stderr)
sys.exit(2)
main(*sys.argv[1:])