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