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