xref: /btstack/tool/btstack_event_generator.py (revision dd148ddbc5f20d3858b5cbe2f3ae862cc28bcadb)
1#!/usr/bin/env python
2# BlueKitchen GmbH (c) 2014
3
4import glob
5import re
6import sys
7import os
8
9import btstack_parser as parser
10
11meta_events = [
12    'ANCS',
13    'AVDTP',
14    'AVRCP',
15    'GOEP',
16    'HFP',
17    'HSP',
18    'PBAP',
19    'LE',
20    'HID',
21]
22
23supported_event_groups = meta_events + [
24    'BTSTACK',
25    'GAP',
26    'HCI',
27    'SDP',
28    'SM',
29    'L2CAP',
30    'RFCOMM',
31    'GATT',
32    'BNEP',
33    'ATT',
34    'HID',
35]
36
37program_info = '''
38BTstack Event Getter Generator for BTstack
39Copyright 2016, BlueKitchen GmbH
40'''
41
42copyright = """/*
43 * Copyright (C) 2016 BlueKitchen GmbH
44 *
45 * Redistribution and use in source and binary forms, with or without
46 * modification, are permitted provided that the following conditions
47 * are met:
48 *
49 * 1. Redistributions of source code must retain the above copyright
50 *    notice, this list of conditions and the following disclaimer.
51 * 2. Redistributions in binary form must reproduce the above copyright
52 *    notice, this list of conditions and the following disclaimer in the
53 *    documentation and/or other materials provided with the distribution.
54 * 3. Neither the name of the copyright holders nor the names of
55 *    contributors may be used to endorse or promote products derived
56 *    from this software without specific prior written permission.
57 * 4. Any redistribution, use, or modification is done solely for
58 *    personal benefit and not for any commercial purpose or for
59 *    monetary gain.
60 *
61 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
62 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
63 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
64 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
65 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
66 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
67 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
68 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
69 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
70 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
71 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72 * SUCH DAMAGE.
73 *
74 * Please inquire about commercial licensing options at
75 * [email protected]
76 *
77 */
78"""
79
80hfile_header_begin = """
81
82/*
83 *  btstack_event.h
84 *
85 *  @brief BTstack event getter/setter
86 *  @note  Don't edit - generated by tool/btstack_event_generator.py
87 *
88 */
89
90#ifndef __BTSTACK_EVENT_H
91#define __BTSTACK_EVENT_H
92
93#if defined __cplusplus
94extern "C" {
95#endif
96
97#include "btstack_util.h"
98#include <stdint.h>
99
100#ifdef ENABLE_BLE
101#include "ble/gatt_client.h"
102#endif
103
104/* API_START */
105
106/**
107 * @brief Get event type
108 * @param event
109 * @return type of event
110 */
111static inline uint8_t hci_event_packet_get_type(const uint8_t * event){
112    return event[0];
113}
114
115"""
116
117hfile_header_end = """
118
119/* API_END */
120
121#if defined __cplusplus
122}
123#endif
124
125#endif // __BTSTACK_EVENT_H
126"""
127
128c_prototoype_simple_return = '''/**
129 * @brief {description}
130 * @param event packet
131 * @return {result_name}
132 * @note: btstack_type {format}
133 */
134static inline {result_type} {fn_name}(const uint8_t * event){{
135    {code}
136}}
137'''
138
139c_prototoype_struct_return = '''/**
140 * @brief {description}
141 * @param event packet
142 * @param Pointer to storage for {result_name}
143 * @note: btstack_type {format}
144 */
145static inline void {fn_name}(const uint8_t * event, {result_type} {result_name}){{
146    {code}
147}}
148'''
149
150c_prototoype_unsupported = '''/**
151 * @brief {description}
152 * @param event packet
153 * @return {result_name}
154 * @note: btstack_type {format}
155 */
156//  static inline {result_type} {fn_name}(const uint8_t * event){{
157//      not implemented yet
158//  }}
159'''
160
161meta_event_template = '''/***
162 * @brief Get subevent code for {meta_event} event
163 * @param event packet
164 * @return subevent_code
165 */
166static inline uint8_t hci_event_{meta_event}_meta_get_subevent_code(const uint8_t * event){{
167    return event[2];
168}}
169'''
170
171# global variables/defines
172# gen_path = '../src/btstack_event.h'
173
174defines = dict()
175defines_used = set()
176
177param_read = {
178    '1' : 'return event[{offset}];',
179    'J' : 'return event[{offset}];',
180    '2' : 'return little_endian_read_16(event, {offset});',
181    'L' : 'return little_endian_read_16(event, {offset});',
182    '3' : 'return little_endian_read_24(event, {offset});',
183    '4' : 'return little_endian_read_32(event, {offset});',
184    'H' : 'return little_endian_read_16(event, {offset});',
185    'B' : 'reverse_bd_addr(&event[{offset}], {result_name});',
186    'R' : 'return &event[{offset}];',
187    'T' : 'return (const char *) &event[{offset}];',
188    'Q' : 'reverse_bytes(&event[{offset}], {result_name}, 32);',
189    'V' : 'return &event[{offset}];',
190    'X' : 'gatt_client_deserialize_service(event, {offset}, {result_name});',
191    'Y' : 'gatt_client_deserialize_characteristic(event, {offset}, {result_name});',
192    'Z' : 'gatt_client_deserialize_characteristic_descriptor(event, {offset}, {result_name});',
193}
194
195def c_type_for_btstack_type(type):
196    param_types = { '1' : 'uint8_t', '2' : 'uint16_t', '3' : 'uint32_t', '4' : 'uint32_t', 'H' : 'hci_con_handle_t', 'B' : 'bd_addr_t',
197                    'D' : 'const uint8_t *', 'E' : 'const uint8_t * ', 'N' : 'String' , 'P' : 'const uint8_t *', 'A' : 'const uint8_t *',
198                    'R' : 'const uint8_t *', 'S' : 'const uint8_t *',
199                    'J' : 'int', 'L' : 'int', 'V' : 'const uint8_t *', 'U' : 'BT_UUID',
200                    'Q' : 'uint8_t *',
201                    'X' : 'gatt_client_service_t *', 'Y' : 'gatt_client_characteristic_t *', 'Z' : 'gatt_client_characteristic_descriptor_t *',
202                    'T' : 'const char *'}
203    return param_types[type]
204
205def size_for_type(type):
206    param_sizes = { '1' : 1, '2' : 2, '3' : 3, '4' : 4, 'H' : 2, 'B' : 6, 'D' : 8, 'E' : 240, 'N' : 248, 'P' : 16, 'Q':32,
207                    'A' : 31, 'S' : -1, 'V': -1, 'J' : 1, 'L' : 2, 'U' : 16, 'X' : 20, 'Y' : 24, 'Z' : 18, 'T':-1}
208    return param_sizes[type]
209
210def format_function_name(event_name):
211    event_name = event_name.lower()
212    if 'event' in event_name:
213        return event_name;
214    return event_name+'_event'
215
216def template_for_type(field_type):
217    global c_prototoype_simple_return
218    global c_prototoype_struct_return
219    types_with_struct_return = "BQXYZ"
220    if field_type in types_with_struct_return:
221        return c_prototoype_struct_return
222    else:
223        return c_prototoype_simple_return
224
225def all_fields_supported(format):
226    global param_read
227    for f in format:
228        if not f in param_read:
229            return False
230    return True
231
232def create_getter(event_name, field_name, field_type, offset, supported):
233    global c_prototoype_unsupported
234    global param_read
235
236    description = "Get field %s from event %s" % (field_name, event_name.upper())
237    result_name = field_name
238    fn_name     = "%s_get_%s" % (event_name, field_name)
239    result_type = c_type_for_btstack_type(field_type)
240    template = c_prototoype_unsupported
241    code = ''
242    if supported and field_type in param_read:
243        template = template_for_type(field_type)
244        code = param_read[field_type].format(offset=offset, result_name=result_name)
245    return template.format(description=description, fn_name=fn_name, result_name=result_name, result_type=result_type, code=code, format=field_type)
246
247def is_le_event(event_group):
248    return event_group in ['GATT', 'ANCS', 'SM']
249
250def create_events(events):
251    global gen_path
252    global copyright
253    global hfile_header_begin
254    global hfile_header_end
255    global meta_event_template
256
257    with open(gen_path, 'wt') as fout:
258        fout.write(copyright)
259        fout.write(hfile_header_begin)
260
261        for meta_event in meta_events:
262            fout.write(meta_event_template.format(meta_event=meta_event.lower()))
263
264        for event_type, event_name, format, args in events:
265            parts = event_name.split("_")
266            event_group = parts[0]
267            if not event_group in supported_event_groups:
268                print("// %s " % event_name)
269                continue
270            # print(event_name)
271            base_name = format_function_name(event_name)
272            length_name = ''
273            offset = 2
274            offset_is_number = 1
275            offset_unknown = 0
276            supported = all_fields_supported(format)
277            last_variable_length_field_pos = ""
278            if is_le_event(event_group):
279                fout.write("#ifdef ENABLE_BLE\n")
280            if len(format) != len(args):
281                print(event_name.upper())
282                print ("Format %s does not match params %s " % (format, args))
283                print
284            for f, arg in zip(format, args):
285                field_name = arg
286                if field_name.lower() == 'subevent_code':
287                    offset += 1
288                    continue
289                if offset_unknown:
290                    print("Param after variable length field without preceding 'J' lenght field")
291                    break
292                field_type = f
293                text = create_getter(base_name, field_name, field_type, offset, supported)
294                fout.write(text)
295                if field_type in 'RT':
296                    break
297                if field_type in 'J':
298                    if offset_is_number:
299                        last_variable_length_field_pos = '%u' % offset
300                    else:
301                        last_variable_length_field_pos = offset
302                if field_type in 'V':
303                    if last_variable_length_field_pos >= 0:
304                        if offset_is_number:
305                            # convert to string
306                            offset = '%u' % offset
307                            offset_is_number = 0
308                        offset = offset + ' + event[%s]' % last_variable_length_field_pos
309                    else:
310                        offset_unknown = 1
311                else:
312                    if offset_is_number:
313                        offset += size_for_type(field_type)
314                    else:
315                        offset = offset + ' + %u' % size_for_type(field_type)
316            if is_le_event(event_group):
317                fout.write("#endif\n")
318            fout.write("\n")
319
320        fout.write(hfile_header_end)
321
322btstack_root = os.path.abspath(os.path.dirname(sys.argv[0]) + '/..')
323gen_path = btstack_root + '/src/btstack_event.h'
324
325print(program_info)
326
327# parse events
328(events, le_events, event_types) = parser.parse_events()
329
330# create event field accesors
331create_events(events + le_events)
332
333# done
334print('Done!')
335