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