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