summaryrefslogtreecommitdiff
path: root/jsongen.py
blob: 727176fcd76e3c6b3b0de95c14a0a51a4fd80e9c (plain)
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
#!/usr/bin/env python
#
# Never hand-hack what you can generate...
#
# This code generates template declarations for AIS-JSON parsing from a
# declarative specification of a JSON structure - and generates those
# declarative specification from the Python format strings for
# dumping the structures
#
import sys, getopt

#
# Here is the information that makes it all work - attribute, type, and
# defult information for all fields.  We can generate either a JSON
# parser template spec or the C code for the correspondong dump functio
# from this information. Doing it this way guarantees consistency.
#
ais_specs = (
    {
    "initname" : "json_ais1",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type1",
    "fieldmap":(
        # fieldname   type        default
        ('status',   'uinteger', '0'),
        ('turn',     'integer',  'AIS_TURN_NOT_AVAILABLE'),
        ('speed',    'uinteger', 'AIS_SPEED_NOT_AVAILABLE'),
        ('accuracy', 'boolean',  'false'),
        ('lon',      'integer',  'AIS_LON_NOT_AVAILABLE'),
        ('lat',      'integer',  'AIS_LAT_NOT_AVAILABLE'),
        ('course',   'uinteger', 'AIS_COURSE_NOT_AVAILABLE'),
        ('heading',  'uinteger', 'AIS_HEADING_NOT_AVAILABLE'),
        ('second',   'uinteger', 'AIS_SEC_NOT_AVAILABLE'),
        ('maneuver', 'uinteger', 'AIS_SEC_INOPERATIVE'),
        ('raim',     'boolean',  'false'),
        ('radio',    'uinteger', '0'),
        ),
    },
    # Message types 2 and 3 duplicate 1
    {
    "initname" : "json_ais4",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type4",
    "fieldmap":(
        # fieldname   type        default
        ('timestamp', 'string',   None),
        ('accuracy',  'boolean',  "true"),
        ('lon',       'integer',  "AIS_LON_NOT_AVAILABLE"),
        ('lat',       'integer',  "AIS_LAT_NOT_AVAILABLE"),
        ('epfd',      'uinteger', "0"),
        ('raim',      'boolean',  "false"),
        ('radio',     'uinteger', "0"),
        ),
    "stringbuffered":("timestamp",),
    },
    {
    "initname" : "json_ais5",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type5",
    "fieldmap":(
        # fieldname        type            default
        ('imo',           'uinteger',      '0'),
        ('ais_version',   'uinteger',      '0'),
        ('callsign',      'string',        None),
        ('shipname',      'string',        None),
        ('shiptype',      'uinteger',      '0'),
        ('to_bow',        'uinteger',      '0'),
        ('to_stern',      'uinteger',      '0'),
        ('to_port',       'uinteger',      '0'),
        ('to_starboard',  'uinteger',      '0'),
        ('epfd',          'uinteger',      '0'),
        ('eta',           'string',        None),
        ('draught',       'uinteger',      '0'),
        ('destination',   'string',        None),
        ('dte',           'uinteger',      '1'),
        ),
    "stringbuffered":("eta",),
    },
    {
    "initname" : "json_ais6",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type6",
    "fieldmap":(
        # fieldname       type             default
        ('seqno',         'uinteger',      '0'),
        ('dest_mmsi',     'uinteger',      '0'),
        ('retransmit',    'boolean',       'false'),
        ('app_id',        'uinteger',      '0'),
        ('data',          'string',        None),
        ),
    "stringbuffered":("data",),
    },
    {
    "initname" : "json_ais7",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type7",
    "fieldmap":(
        # fieldname       type             default
        ('mmsi1',         'uinteger',      '0'),
        ('mmsi2',         'uinteger',      '0'),
        ('mmsi3',         'uinteger',      '0'),
        ('mmsi4',         'uinteger',      '0'),
        ),
    },
    {
    "initname" : "json_ais8",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type8",
    "fieldmap":(
        # fieldname       type             default
        ('app_id',        'uinteger',      '0'),
        ('data',          'string',        None),
        ),
    "stringbuffered":("data",),
    },
    {
    "initname" : "json_ais9",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type9",
    "fieldmap":(
        # fieldname       type             default
        ('alt',           'uinteger',      'AIS_ALT_NOT_AVAILABLE'),
        ('speed',         'uinteger',      'AIS_SPEED_NOT_AVAILABLE'),
        ('accuracy',      'boolean',       'false'),
        ('lon',           'integer',       'AIS_LON_NOT_AVAILABLE'),
        ('lat',           'integer',       'AIS_LAT_NOT_AVAILABLE'),
        ('course',        'uinteger',      'AIS_COURSE_NOT_AVAILABLE'),
        ('second',        'uinteger',      'AIS_SEC_NOT_AVAILABLE'),
        ('regional',      'uinteger',      '0'),
        ('dte',           'uinteger',      '1'),
        ('raim',          'boolean',       'false'),
        ('radio',         'uinteger',      '0'),
        ),
    },
    {
    "initname" : "json_ais10",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type10",
    "fieldmap":(
        # fieldname       type             default
        ('dest_mmsi',     'uinteger',      '0'),
        ),
    },
    # Message type 11 duplicates 4
    {
    "initname" : "json_ais12",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type12",
    "fieldmap":(
        # fieldname       type             default
        ('seqno',         'uinteger',      '0'),
        ('dest_mmsi',     'uinteger',      '0'),
        ('retransmit',    'boolean',       '0'),
        ('text',          'string',        None),
        ),
    },
    # Message type 13 duplicates 7 
    {
    "initname" : "json_ais14",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type14",
    "fieldmap":(
        # fieldname       type             default
        ('text',          'string',        None),
        ),
    },
    {
    "initname" : "json_ais15",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type15",
    "fieldmap":(
        # fieldname       type             default
        ('mmsi1',         'uinteger',      '0'),
        ('type1_1',       'uinteger',      '0'),
        ('offset1_1',     'uinteger',      '0'),
        ('type1_2',       'uinteger',      '0'),
        ('offset1_2',     'uinteger',      '0'),
        ('mmsi2',         'uinteger',      '0'),
        ('type2_1',       'uinteger',      '0'),
        ('offset2_1',     'uinteger',      '0'),
        ),
    },
    {
    "initname" : "json_ais16",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type16",
    "fieldmap":(
        # fieldname       type             default
        ('mmsi1',         'uinteger',      '0'),
        ('offset1',       'uinteger',      '0'),
        ('increment1',    'uinteger',      '0'),
        ('mmsi2',         'uinteger',      '0'),
        ('offset2',       'uinteger',      '0'),
        ('increment2',    'uinteger',      '0'),
        ),
    },
    {
    "initname" : "json_ais17",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type17",
    "fieldmap":(
        # fieldname       type             default
        ('lon',           'integer',       'AIS_GNS_LON_NOT_AVAILABLE'),
        ('lat',           'integer',       'AIS_GNS_LAT_NOT_AVAILABLE'),
        ('data',          'string',        None),
        ),
    "stringbuffered":("data",),
    },
    {
    "initname" : "json_ais18",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type18",
    "fieldmap":(
        # fieldname       type             default
        ('reserved',      'uinteger',      '0'),
        ('speed',         'uinteger',      'AIS_SPEED_NOT_AVAILABLE'),
        ('accuracy',      'boolean',       'false'),
        ('lon',           'integer',       'AIS_LON_NOT_AVAILABLE'),
        ('lat',           'integer',       'AIS_LAT_NOT_AVAILABLE'),
        ('course',        'uinteger',      'AIS_COURSE_NOT_AVAILABLE'),
        ('heading',       'uinteger',      'AIS_HEADING_NOT_AVAILABLE'),
        ('second',        'uinteger',      'AIS_SEC_NOT_AVAILABLE'),
        ('regional',      'uinteger',      '0'),
        ('cs',            'boolean',       'false'),
        ('display',       'boolean',       'false'),
        ('dsc',           'boolean',       'false'),
        ('band',          'boolean',       'false'),
        ('msg22',         'boolean',       'false'),
        ('raim',          'boolean',       'false'),
        ('radio',         'uinteger',      '0'),
        ),
    },
    {
    "initname" : "json_ais19",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type19",
    "fieldmap":(
        # fieldname       type             default
        ('reserved',      'uinteger',      '0'),
        ('speed',         'uinteger',      'AIS_SPEED_NOT_AVAILABLE'),
        ('accuracy',      'boolean',       'false'),
        ('lon',           'integer',       'AIS_LON_NOT_AVAILABLE'),
        ('lat',           'integer',       'AIS_LAT_NOT_AVAILABLE'),
        ('course',        'uinteger',      'AIS_COURSE_NOT_AVAILABLE'),
        ('heading',       'uinteger',      'AIS_HEADING_NOT_AVAILABLE'),
        ('second',        'uinteger',      'AIS_SEC_NOT_AVAILABLE'),
        ('regional',      'uinteger',      '0'),
        ('shipname',      'string',        None),
        ('shiptype',      'uinteger',      '0'),
        ('to_bow',        'uinteger',      '0'),
        ('to_stern',      'uinteger',      '0'),
        ('to_port',       'uinteger',      '0'),
        ('to_starboard',  'uinteger',      '0'),
        ('epfd',          'uinteger',      '0'),
        ('raim',          'boolean',       'false'),
        ('dte',           'uinteger',      '1'),
        ('assigned',      'boolean',       'false'),
        ),
    },
    {
    "initname" : "json_ais20",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type20",
    "fieldmap":(
        # fieldname       type             default
        ('offset1',       'uinteger',      '0'),
        ('number1',       'uinteger',      '0'),
        ('timeout1',      'uinteger',      '0'),
        ('increment1',    'uinteger',      '0'),
        ('offset2',       'uinteger',      '0'),
        ('number2',       'uinteger',      '0'),
        ('timeout2',      'uinteger',      '0'),
        ('increment2',    'uinteger',      '0'),
        ('offset3',       'uinteger',      '0'),
        ('number3',       'uinteger',      '0'),
        ('timeout3',      'uinteger',      '0'),
        ('increment3',    'uinteger',      '0'),
        ('offset4',       'uinteger',      '0'),
        ('number4',       'uinteger',      '0'),
        ('timeout4',      'uinteger',      '0'),
        ('increment4',    'uinteger',      '0'),
        ),
    },
    {
    "initname" : "json_ais21",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type21",
    "fieldmap":(
        # fieldname       type             default
        ('type',          'uinteger',      '0'),
        ('name',          'string',        None),
        ('accuracy',      'boolean',       'false'),
        ('lon',           'integer',       'AIS_LON_NOT_AVAILABLE'),
        ('lat',           'integer',       'AIS_LAT_NOT_AVAILABLE'),
        ('to_bow',        'uinteger',      '0'),
        ('to_stern',      'uinteger',      '0'),
        ('to_port',       'uinteger',      '0'),
        ('to_starboard',  'uinteger',      '0'),
        ('epfd',          'uinteger',      '0'),
        ('second',        'uinteger',      '0'),
        ('regional',      'uinteger',      '0'),
        ('off_position',  'boolean',       'false'),
        ('raim',          'boolean',       'false'),
        ('virtual_aid',   'boolean',       'false'),
        ),
    },
    {
    "initname" : "json_ais22",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type22",
    "fieldmap":(
        # fieldname       type             default
        ('channel_a',     'uinteger',      '0'),
        ('channel_b',     'uinteger',      '0'),
        ('mode',          'uinteger',      '0'),
        ('power',         'boolean',       'false'),
        ('ne_lon',        'integer',       'AIS_GNS_LON_NOT_AVAILABLE'),
        ('ne_lat',        'integer',       'AIS_GNS_LAT_NOT_AVAILABLE'),
        ('sw_lon',        'integer',       'AIS_GNS_LON_NOT_AVAILABLE'),
        ('sw_lat',        'integer',       'AIS_GNS_LAT_NOT_AVAILABLE'),
        ('addressed',     'boolean',       'false'),
        ('band_a',        'boolean',       'false'),
        ('band_b',        'boolean',       'false'),
        ('zonesize',      'uinteger',      '0'),
        ),
    },
    # Structure of mesage 23 is a mystery
    {
    "initname" : "json_ais24",
    "header": "\tAIS_HEADER,",
    "structname": "ais->type24",
    "fieldmap":(
        # fieldname             type             default
        ('part',                'uinteger',      '0'),
        ('a.shipname',          'string',        None),	# Part A
        ('b.shiptype',          'uinteger',      '0'),	# Part B
        ('b.vendorid',          'string',        None),	# Part B
        ('b.callsign',          'string',        None),	# Part B
        ('b.mothership_mmsi',   'uinteger',      '0'),	# Part B
        ('b.dim.to_bow',        'uinteger',      '0'),	# Part B
        ('b.dim.to_stern',      'uinteger',      '0'),	# Part B
        ('b.dim.to_port',       'uinteger',      '0'),	# Part B
        ('b.dim.to_starboard',  'uinteger',      '0'),	# Part B
        ),
    },
)


# Give this global the string spec you need to convert with -g
# We do it this mildly odd way only because passing Python multiline
# string literals on the command line is inconvenient.
stringspec = ""

# You should not need to modify anything below this line.

def generate(spec):
    global outboard
    for (attr, itype, default) in spec["fieldmap"]:
        if attr in spec.get("stringbuffered", []):
            if attr not in outboard:
                print "    char %s[JSON_VAL_MAX+1];" % attr
                outboard.append(attr)
    print "    const struct json_attr_t %s[] = {" % spec["initname"]
    if "header" in spec:
        print spec["header"]
    for (attr, itype, default) in spec["fieldmap"]:
        structname = spec["structname"]
        if itype == "string":
            deref = ""
        else:
            deref = "&"
        if attr in spec.get("stringbuffered", []):
            target = attr
        else:
            target = structname + "." + attr
        if "." in attr:
            attr = attr[attr.rfind(".")+1:]
        print '\t{"%s",%s%s,%s.addr.%s = %s%s,' % \
               (attr, " "*(12-len(attr)), itype, " "*(10-len(itype)), itype, deref, target)
        leader = " " * 35
        if itype == "string":
            print leader + ".len = sizeof(%s)}," % target
        else:
            print leader + ".dflt.%s = %s}," % (itype, default)

    print """\
	{NULL},
    };
"""

# No code for gernerating dump functions yet.
# When we do this, remembeer that we have to suppress dump function
# generation from any spec with a union dot in the field names;
# those will have to be coded by hand.

def string_to_specifier(strspec):
    "Compile a Python-style format string to an attribute-type fieldmap."
    # Map C and Python-type format letters to JSON parser datatypes 
    fmtmap = {
        "d": "integer",
        "u": "uinteger",
        "f": "real",
        "s": "boolean",	# Only booleans print as unquoted strings
        "\"": "string",
        }
    dftmap = {
        "integer":  "0",
        "uinteger": "0",
        "real":     "0.0",
        "string":   None,
        "boolean":  "false"
        }
    strspec = strspec.strip()
    if strspec[-1] == "}":
        strspec = strspec[:-1]
    else:
        print "Missing terminating }"
        sys.exit(1)
    print '    "fieldmap":('
    for item in strspec.split(","):
        itype = fmtmap[item[-1]]
        attr = item[:item.find(":")]
        if attr[0] == '"':
            attr = attr[1:]
        if attr[-1] == '"':
            attr = attr[:-1]
        dflt = dftmap[itype]
        if dflt is not None:
            dflt = `dflt`
        print "        ('%s',%s'%s',%s%s)," % (attr, " "*(14-len(attr)), itype, " "*(14-len(itype)), dflt)
    print "        )"


if __name__ == '__main__':
    try:
        # The --ais and --target= options are (required) placeho;lders.
        # In the future, this script will generate more different kinds
        # of code.
        (options, arguments) = getopt.getopt(sys.argv[1:], "g", ["ais", "target="])
    except getopt.GetoptError, msg:
        print "jsongen.py: " + str(msg)
        raise SystemExit, 1

    specify = False
    spec = None
    target = None
    for (switch, val) in options:
        if switch == '-g':
            specify = True
        elif switch == '--ais':
            spec = ais_specs
        elif switch == '--target':
            target = val

    if not specify and (not target or not spec):
        print "jsongen.py: must specify type and target."
        sys,exit(1)


    if specify:
        string_to_specifier(stringspec)
    else:
        print """/*
 * This is code generated by jsongen.py. Do not hand-hack it!
 */
"""
        outboard = []
        for description in spec:
            generate(description)
        print "/* Generated code ends. */"