xref: /btstack/tool/compile_gatt.py (revision e5ce8e0e9124c5f857c9e7d51d785a7349437589)
1#!/usr/bin/env python3
2#
3# BLE GATT configuration generator for use with BTstack
4# Copyright 2019 BlueKitchen GmbH
5#
6# Format of input file:
7# PRIMARY_SERVICE, SERVICE_UUID
8# CHARACTERISTIC, ATTRIBUTE_TYPE_UUID, [READ | WRITE | DYNAMIC], VALUE
9
10# dependencies:
11# - pip3 install pycryptodomex
12# alternatively, the pycryptodome package can be used instead
13# - pip3 install pycryptodome
14
15import codecs
16import csv
17import io
18import os
19import re
20import string
21import sys
22import argparse
23import tempfile
24
25have_crypto = True
26# try to import PyCryptodome independent from PyCrypto
27try:
28    from Cryptodome.Cipher import AES
29    from Cryptodome.Hash import CMAC
30except ImportError:
31    # fallback: try to import PyCryptodome as (an almost drop-in) replacement for the PyCrypto library
32    try:
33        from Crypto.Cipher import AES
34        from Crypto.Hash import CMAC
35    except ImportError:
36        have_crypto = False
37        print("\n[!] PyCryptodome required to calculate GATT Database Hash but not installed (using random value instead)")
38        print("[!] Please install PyCryptodome, e.g. 'pip3 install pycryptodomex' or 'pip3 install pycryptodome'\n")
39
40header = '''
41// {0} generated from {1} for BTstack
42// it needs to be regenerated when the .gatt file is updated.
43
44// To generate {0}:
45// {2} {1} {0}
46
47// att db format version 1
48
49// binary attribute representation:
50// - size in bytes (16), flags(16), handle (16), uuid (16/128), value(...)
51
52#include <stdint.h>
53
54// Reference: https://en.cppreference.com/w/cpp/feature_test
55#if __cplusplus >= 200704L
56constexpr
57#endif
58const uint8_t profile_data[] =
59'''
60
61print('''
62BLE configuration generator for use with BTstack
63Copyright 2018 BlueKitchen GmbH
64''')
65
66assigned_uuids = {
67    'GAP_SERVICE'          : 0x1800,
68    'GATT_SERVICE'         : 0x1801,
69    'GAP_DEVICE_NAME'      : 0x2a00,
70    'GAP_APPEARANCE'       : 0x2a01,
71    'GAP_PERIPHERAL_PRIVACY_FLAG' : 0x2A02,
72    'GAP_RECONNECTION_ADDRESS'    : 0x2A03,
73    'GAP_PERIPHERAL_PREFERRED_CONNECTION_PARAMETERS' : 0x2A04,
74    'GATT_SERVICE_CHANGED' : 0x2a05,
75    'GATT_DATABASE_HASH' : 0x2b2a
76}
77
78security_permsission = ['ANYBODY','ENCRYPTED', 'AUTHENTICATED', 'AUTHORIZED', 'AUTHENTICATED_SC']
79
80property_flags = {
81    # GATT Characteristic Properties
82    'BROADCAST' :                   0x01,
83    'READ' :                        0x02,
84    'WRITE_WITHOUT_RESPONSE' :      0x04,
85    'WRITE' :                       0x08,
86    'NOTIFY':                       0x10,
87    'INDICATE' :                    0x20,
88    'AUTHENTICATED_SIGNED_WRITE' :  0x40,
89    'EXTENDED_PROPERTIES' :         0x80,
90    # custom BTstack extension
91    'DYNAMIC':                      0x100,
92    'LONG_UUID':                    0x200,
93
94    # read permissions
95    'READ_PERMISSION_BIT_0':        0x400,
96    'READ_PERMISSION_BIT_1':        0x800,
97
98    #
99    'ENCRYPTION_KEY_SIZE_7':       0x6000,
100    'ENCRYPTION_KEY_SIZE_8':       0x7000,
101    'ENCRYPTION_KEY_SIZE_9':       0x8000,
102    'ENCRYPTION_KEY_SIZE_10':      0x9000,
103    'ENCRYPTION_KEY_SIZE_11':      0xa000,
104    'ENCRYPTION_KEY_SIZE_12':      0xb000,
105    'ENCRYPTION_KEY_SIZE_13':      0xc000,
106    'ENCRYPTION_KEY_SIZE_14':      0xd000,
107    'ENCRYPTION_KEY_SIZE_15':      0xe000,
108    'ENCRYPTION_KEY_SIZE_16':      0xf000,
109    'ENCRYPTION_KEY_SIZE_MASK':    0xf000,
110
111    # only used by gatt compiler >= 0xffff
112    # Extended Properties
113    'RELIABLE_WRITE':              0x00010000,
114    'AUTHENTICATION_REQUIRED':     0x00020000,
115    'AUTHORIZATION_REQUIRED':      0x00040000,
116    'READ_ANYBODY':                0x00080000,
117    'READ_ENCRYPTED':              0x00100000,
118    'READ_AUTHENTICATED':          0x00200000,
119    'READ_AUTHENTICATED_SC':       0x00400000,
120    'READ_AUTHORIZED':             0x00800000,
121    'WRITE_ANYBODY':               0x01000000,
122    'WRITE_ENCRYPTED':             0x02000000,
123    'WRITE_AUTHENTICATED':         0x04000000,
124    'WRITE_AUTHENTICATED_SC':      0x08000000,
125    'WRITE_AUTHORIZED':            0x10000000,
126
127    # Broadcast, Notify, Indicate, Extended Properties are only used to describe a GATT Characteristic, but are free to use with att_db
128    # - write permissions
129    'WRITE_PERMISSION_BIT_0':      0x01,
130    'WRITE_PERMISSION_BIT_1':      0x10,
131    # - SC required
132    'READ_PERMISSION_SC':          0x20,
133    'WRITE_PERMISSION_SC':         0x80,
134}
135
136services = dict()
137characteristic_indices = dict()
138presentation_formats = dict()
139current_service_uuid_string = ""
140current_service_start_handle = 0
141current_characteristic_uuid_string = ""
142defines_for_characteristics = []
143defines_for_services = []
144include_paths = []
145database_hash_message = bytearray()
146service_counter = {}
147
148handle = 1
149total_size = 0
150
151def aes_cmac(key, n):
152    if have_crypto:
153        cobj = CMAC.new(key, ciphermod=AES)
154        cobj.update(n)
155        return cobj.digest()
156    else:
157        # return random value
158        return os.urandom(16)
159
160def read_defines(infile):
161    defines = dict()
162    with open (infile, 'rt') as fin:
163        for line in fin:
164            parts = re.match('#define\s+(\w+)\s+(\w+)',line)
165            if parts and len(parts.groups()) == 2:
166                (key, value) = parts.groups()
167                defines[key] = int(value, 16)
168    return defines
169
170def keyForUUID(uuid):
171    keyUUID = ""
172    for i in uuid:
173        keyUUID += "%02x" % i
174    return keyUUID
175
176def c_string_for_uuid(uuid):
177    return uuid.replace('-', '_')
178
179def twoByteLEFor(value):
180    return [ (value & 0xff), (value >> 8)]
181
182def is_128bit_uuid(text):
183    if re.match("[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}", text):
184        return True
185    return False
186
187def parseUUID128(uuid):
188    parts = re.match("([0-9A-Fa-f]{4})([0-9A-Fa-f]{4})-([0-9A-Fa-f]{4})-([0-9A-Fa-f]{4})-([0-9A-Fa-f]{4})-([0-9A-Fa-f]{4})([0-9A-Fa-f]{4})([0-9A-Fa-f]{4})", uuid)
189    uuid_bytes = []
190    for i in range(8, 0, -1):
191        uuid_bytes = uuid_bytes + twoByteLEFor(int(parts.group(i),16))
192    return uuid_bytes
193
194def parseUUID(uuid):
195    if uuid in assigned_uuids:
196        return twoByteLEFor(assigned_uuids[uuid])
197    uuid_upper = uuid.upper().replace('.','_')
198    if uuid_upper in bluetooth_gatt:
199        return twoByteLEFor(bluetooth_gatt[uuid_upper])
200    if is_128bit_uuid(uuid):
201        return parseUUID128(uuid)
202    uuidInt = int(uuid, 16)
203    return twoByteLEFor(uuidInt)
204
205def parseProperties(properties):
206    value = 0
207    parts = properties.split("|")
208    for property in parts:
209        property = property.strip()
210        if property in property_flags:
211            value |= property_flags[property]
212        else:
213            print("WARNING: property %s undefined" % (property))
214
215    return value
216
217def prettyPrintProperties(properties):
218    value = ""
219    parts = properties.split("|")
220    for property in parts:
221        property = property.strip()
222        if property in property_flags:
223            if value != "":
224                value += " | "
225            value += property
226        else:
227            print("WARNING: property %s undefined" % (property))
228
229    return value
230
231
232def gatt_characteristic_properties(properties):
233    return properties & 0xff
234
235def att_flags(properties):
236    # drop Broadcast (0x01), Notify (0x10), Indicate (0x20), Extended Properties (0x80) - not used for flags
237    properties &= 0xffffff4e
238
239    # rw permissions distinct
240    distinct_permissions_used = properties & (
241        property_flags['READ_AUTHORIZED'] |
242        property_flags['READ_AUTHENTICATED_SC'] |
243        property_flags['READ_AUTHENTICATED'] |
244        property_flags['READ_ENCRYPTED'] |
245        property_flags['READ_ANYBODY'] |
246        property_flags['WRITE_AUTHORIZED'] |
247        property_flags['WRITE_AUTHENTICATED'] |
248        property_flags['WRITE_AUTHENTICATED_SC'] |
249        property_flags['WRITE_ENCRYPTED'] |
250        property_flags['WRITE_ANYBODY']
251    ) != 0
252
253    # post process properties
254    encryption_key_size_specified = (properties & property_flags['ENCRYPTION_KEY_SIZE_MASK']) != 0
255
256    # if distinct permissions not used and encyrption key size specified -> set READ/WRITE Encrypted
257    if encryption_key_size_specified and not distinct_permissions_used:
258        properties |= property_flags['READ_ENCRYPTED'] | property_flags['WRITE_ENCRYPTED']
259
260    # if distinct permissions not used and authentication is requires -> set READ/WRITE Authenticated
261    if properties & property_flags['AUTHENTICATION_REQUIRED'] and not distinct_permissions_used:
262        properties |= property_flags['READ_AUTHENTICATED'] | property_flags['WRITE_AUTHENTICATED']
263
264    # if distinct permissions not used and authorized is requires -> set READ/WRITE Authorized
265    if properties & property_flags['AUTHORIZATION_REQUIRED'] and not distinct_permissions_used:
266        properties |= property_flags['READ_AUTHORIZED'] | property_flags['WRITE_AUTHORIZED']
267
268    # determine read/write security requirements
269    read_security_level  = 0
270    write_security_level = 0
271    read_requires_sc     = False
272    write_requires_sc    = False
273    if properties & property_flags['READ_AUTHORIZED']:
274        read_security_level = 3
275    elif properties & property_flags['READ_AUTHENTICATED']:
276        read_security_level = 2
277    elif properties & property_flags['READ_AUTHENTICATED_SC']:
278        read_security_level = 2
279        read_requires_sc = True
280    elif properties & property_flags['READ_ENCRYPTED']:
281        read_security_level = 1
282    if properties & property_flags['WRITE_AUTHORIZED']:
283        write_security_level = 3
284    elif properties & property_flags['WRITE_AUTHENTICATED']:
285        write_security_level = 2
286    elif properties & property_flags['WRITE_AUTHENTICATED_SC']:
287        write_security_level = 2
288        write_requires_sc = True
289    elif properties & property_flags['WRITE_ENCRYPTED']:
290        write_security_level = 1
291
292    # map security requirements to flags
293    if read_security_level & 2:
294        properties |= property_flags['READ_PERMISSION_BIT_1']
295    if read_security_level & 1:
296        properties |= property_flags['READ_PERMISSION_BIT_0']
297    if read_requires_sc:
298        properties |= property_flags['READ_PERMISSION_SC']
299    if write_security_level & 2:
300        properties |= property_flags['WRITE_PERMISSION_BIT_1']
301    if write_security_level & 1:
302        properties |= property_flags['WRITE_PERMISSION_BIT_0']
303    if write_requires_sc:
304        properties |= property_flags['WRITE_PERMISSION_SC']
305
306    return properties
307
308def write_permissions_and_key_size_flags_from_properties(properties):
309    return att_flags(properties) & (property_flags['ENCRYPTION_KEY_SIZE_MASK'] | property_flags['WRITE_PERMISSION_BIT_0'] | property_flags['WRITE_PERMISSION_BIT_1'])
310
311def write_8(fout, value):
312    fout.write( "0x%02x, " % (value & 0xff))
313
314def write_16(fout, value):
315    fout.write('0x%02x, 0x%02x, ' % (value & 0xff, (value >> 8) & 0xff))
316
317def write_uuid(fout, uuid):
318    for byte in uuid:
319        fout.write( "0x%02x, " % byte)
320
321def write_string(fout, text):
322    for l in text.lstrip('"').rstrip('"'):
323        write_8(fout, ord(l))
324
325def write_sequence(fout, text):
326    parts = text.split()
327    for part in parts:
328        fout.write("0x%s, " % (part.strip()))
329
330def write_database_hash(fout):
331    fout.write("THE-DATABASE-HASH")
332
333def write_indent(fout):
334    fout.write("    ")
335
336def read_permissions_from_flags(flags):
337    permissions = 0
338    if flags & property_flags['READ_PERMISSION_BIT_0']:
339        permissions |= 1
340    if flags & property_flags['READ_PERMISSION_BIT_1']:
341        permissions |= 2
342    if flags & property_flags['READ_PERMISSION_SC'] and permissions == 2:
343        permissions = 4
344    return permissions
345
346def write_permissions_from_flags(flags):
347    permissions = 0
348    if flags & property_flags['WRITE_PERMISSION_BIT_0']:
349        permissions |= 1
350    if flags & property_flags['WRITE_PERMISSION_BIT_1']:
351        permissions |= 2
352    if flags & property_flags['WRITE_PERMISSION_SC'] and permissions == 2:
353        permissions = 4
354    return permissions
355
356def encryption_key_size_from_flags(flags):
357    encryption_key_size = (flags & 0xf000) >> 12
358    if encryption_key_size > 0:
359        encryption_key_size += 1
360    return encryption_key_size
361
362def is_string(text):
363    for item in text.split(" "):
364        if not all(c in string.hexdigits for c in item):
365            return True
366    return False
367
368def add_client_characteristic_configuration(properties):
369    return properties & (property_flags['NOTIFY'] | property_flags['INDICATE'])
370
371def serviceDefinitionComplete(fout):
372    global services
373    if current_service_uuid_string:
374        # fout.write("\n")
375        # update num instances for this service
376        count = 1
377        if current_service_uuid_string in service_counter:
378            count = service_counter[current_service_uuid_string] + 1
379        service_counter[current_service_uuid_string] = count
380        # add old defines without service counter for first instance for backward compatibility
381        if count == 1:
382            defines_for_services.append('#define ATT_SERVICE_%s_START_HANDLE 0x%04x' % (current_service_uuid_string, current_service_start_handle))
383            defines_for_services.append('#define ATT_SERVICE_%s_END_HANDLE 0x%04x' % (current_service_uuid_string, handle-1))
384
385        # unified defines indicating instance
386        defines_for_services.append('#define ATT_SERVICE_%s_%02x_START_HANDLE 0x%04x' % (current_service_uuid_string, count, current_service_start_handle))
387        defines_for_services.append('#define ATT_SERVICE_%s_%02x_END_HANDLE 0x%04x' % (current_service_uuid_string, count, handle-1))
388        services[current_service_uuid_string+"_" + str(count)] = [current_service_start_handle, handle - 1, count]
389
390def dump_flags(fout, flags):
391    global security_permsission
392    encryption_key_size = encryption_key_size_from_flags(flags)
393    read_permissions    = security_permsission[read_permissions_from_flags(flags)]
394    write_permissions   = security_permsission[write_permissions_from_flags(flags)]
395    write_indent(fout)
396    fout.write('// ')
397    first = 1
398    if flags & property_flags['READ']:
399        fout.write('READ_%s' % read_permissions)
400        first = 0
401    if flags & (property_flags['WRITE'] | property_flags['WRITE_WITHOUT_RESPONSE']):
402        if not first:
403            fout.write(', ')
404        first = 0
405        fout.write('WRITE_%s' % write_permissions)
406    if encryption_key_size > 0:
407        if not first:
408            fout.write(', ')
409        first = 0
410        fout.write('ENCRYPTION_KEY_SIZE=%u' % encryption_key_size)
411    fout.write('\n')
412
413def database_hash_append_uint8(value):
414    global database_hash_message
415    database_hash_message.append(value)
416
417def database_hash_append_uint16(value):
418    global database_hash_message
419    database_hash_append_uint8(value & 0xff)
420    database_hash_append_uint8((value >> 8) & 0xff)
421
422def database_hash_append_value(value):
423    global database_hash_message
424    for byte in value:
425        database_hash_append_uint8(byte)
426
427def parseService(fout, parts, service_type):
428    global handle
429    global total_size
430    global current_service_uuid_string
431    global current_service_start_handle
432
433    serviceDefinitionComplete(fout)
434
435    read_only_anybody_flags = property_flags['READ'];
436
437    write_indent(fout)
438    fout.write('// 0x%04x %s\n' % (handle, '-'.join(parts)))
439
440    uuid = parseUUID(parts[1])
441    uuid_size = len(uuid)
442
443    size = 2 + 2 + 2 + uuid_size + 2
444
445    if service_type == 0x2802:
446        size += 4
447
448    write_indent(fout)
449    write_16(fout, size)
450    write_16(fout, read_only_anybody_flags)
451    write_16(fout, handle)
452    write_16(fout, service_type)
453    write_uuid(fout, uuid)
454    fout.write("\n")
455
456    database_hash_append_uint16(handle)
457    database_hash_append_uint16(service_type)
458    database_hash_append_value(uuid)
459
460    current_service_uuid_string = c_string_for_uuid(parts[1])
461    current_service_start_handle = handle
462    handle = handle + 1
463    total_size = total_size + size
464
465def parsePrimaryService(fout, parts):
466    parseService(fout, parts, 0x2800)
467
468def parseSecondaryService(fout, parts):
469    parseService(fout, parts, 0x2801)
470
471def parseIncludeService(fout, parts):
472    global handle
473    global total_size
474
475    read_only_anybody_flags = property_flags['READ'];
476
477    uuid = parseUUID(parts[1])
478    uuid_size = len(uuid)
479    if uuid_size > 2:
480        uuid_size = 0
481
482    size = 2 + 2 + 2 + 2 + 4 + uuid_size
483
484    keyUUID = c_string_for_uuid(parts[1])
485    for (serviceUUID, service) in services.items():
486        if serviceUUID.startswith(keyUUID):
487            write_indent(fout)
488            fout.write('// 0x%04x %s - range [0x%04x, 0x%04x]\n' % (handle, '-'.join(parts), services[serviceUUID][0], services[serviceUUID][1]))
489
490            write_indent(fout)
491            write_16(fout, size)
492            write_16(fout, read_only_anybody_flags)
493            write_16(fout, handle)
494            write_16(fout, 0x2802)
495            write_16(fout, services[serviceUUID][0])
496            write_16(fout, services[serviceUUID][1])
497            if uuid_size > 0:
498                write_uuid(fout, uuid)
499            fout.write("\n")
500
501            database_hash_append_uint16(handle)
502            database_hash_append_uint16(0x2802)
503            database_hash_append_uint16(services[serviceUUID][0])
504            database_hash_append_uint16(services[serviceUUID][1])
505            if uuid_size > 0:
506                database_hash_append_value(uuid)
507
508            handle = handle + 1
509            total_size = total_size + size
510
511def parseCharacteristic(fout, parts):
512    global handle
513    global total_size
514    global current_characteristic_uuid_string
515    global characteristic_indices
516
517    read_only_anybody_flags = property_flags['READ'];
518
519    # enumerate characteristics with same UUID, using optional name tag if available
520    current_characteristic_uuid_string = c_string_for_uuid(parts[1]);
521    index = 1
522    if current_characteristic_uuid_string in characteristic_indices:
523        index = characteristic_indices[current_characteristic_uuid_string] + 1
524    characteristic_indices[current_characteristic_uuid_string] = index
525    if len(parts) > 4:
526        current_characteristic_uuid_string += '_' + parts[4].upper().replace(' ','_')
527    else:
528        current_characteristic_uuid_string += ('_%02x' % index)
529
530    uuid       = parseUUID(parts[1])
531    uuid_size  = len(uuid)
532    properties = parseProperties(parts[2])
533    value = ', '.join([str(x) for x in parts[3:]])
534
535    # reliable writes is defined in an extended properties
536    if (properties & property_flags['RELIABLE_WRITE']):
537        properties = properties | property_flags['EXTENDED_PROPERTIES']
538
539    write_indent(fout)
540    fout.write('// 0x%04x %s - %s\n' % (handle, '-'.join(parts[0:2]), prettyPrintProperties(parts[2])))
541
542
543    characteristic_properties = gatt_characteristic_properties(properties)
544    size = 2 + 2 + 2 + 2 + (1+2+uuid_size)
545    write_indent(fout)
546    write_16(fout, size)
547    write_16(fout, read_only_anybody_flags)
548    write_16(fout, handle)
549    write_16(fout, 0x2803)
550    write_8(fout, characteristic_properties)
551    write_16(fout, handle+1)
552    write_uuid(fout, uuid)
553    fout.write("\n")
554    total_size = total_size + size
555
556    database_hash_append_uint16(handle)
557    database_hash_append_uint16(0x2803)
558    database_hash_append_uint8(characteristic_properties)
559    database_hash_append_uint16(handle+1)
560    database_hash_append_value(uuid)
561
562    handle = handle + 1
563
564    uuid_is_database_hash = len(uuid) == 2 and uuid[0] == 0x2a and uuid[1] == 0x2b
565
566    size = 2 + 2 + 2 + uuid_size
567    if uuid_is_database_hash:
568        size +=  16
569    else:
570        if is_string(value):
571            size = size + len(value)
572        else:
573            size = size + len(value.split())
574
575    value_flags = att_flags(properties)
576
577    # add UUID128 flag for value handle
578    if uuid_size == 16:
579        value_flags = value_flags | property_flags['LONG_UUID'];
580
581    write_indent(fout)
582    properties_string = prettyPrintProperties(parts[2])
583    if "DYNAMIC" in properties_string:
584        fout.write('// 0x%04x VALUE %s - %s\n' % (handle, '-'.join(parts[0:2]), prettyPrintProperties(parts[2])))
585    else:
586        fout.write('// 0x%04x VALUE %s - %s -'"'%s'"'\n' % (
587        handle, '-'.join(parts[0:2]), prettyPrintProperties(parts[2]), value))
588
589    dump_flags(fout, value_flags)
590
591    write_indent(fout)
592    write_16(fout, size)
593    write_16(fout, value_flags)
594    write_16(fout, handle)
595    write_uuid(fout, uuid)
596    if uuid_is_database_hash:
597        write_database_hash(fout)
598    else:
599        if is_string(value):
600            write_string(fout, value)
601        else:
602            write_sequence(fout,value)
603
604    fout.write("\n")
605    defines_for_characteristics.append('#define ATT_CHARACTERISTIC_%s_VALUE_HANDLE 0x%04x' % (current_characteristic_uuid_string, handle))
606    handle = handle + 1
607
608    if add_client_characteristic_configuration(properties):
609        # use write permissions and encryption key size from attribute value and set READ_ANYBODY | READ | WRITE | DYNAMIC
610        flags  = write_permissions_and_key_size_flags_from_properties(properties)
611        flags |= property_flags['READ']
612        flags |= property_flags['WRITE']
613        flags |= property_flags['WRITE_WITHOUT_RESPONSE']
614        flags |= property_flags['DYNAMIC']
615        size = 2 + 2 + 2 + 2 + 2
616
617        write_indent(fout)
618        fout.write('// 0x%04x CLIENT_CHARACTERISTIC_CONFIGURATION\n' % (handle))
619
620        dump_flags(fout, flags)
621
622        write_indent(fout)
623        write_16(fout, size)
624        write_16(fout, flags)
625        write_16(fout, handle)
626        write_16(fout, 0x2902)
627        write_16(fout, 0)
628        fout.write("\n")
629
630        database_hash_append_uint16(handle)
631        database_hash_append_uint16(0x2902)
632
633        defines_for_characteristics.append('#define ATT_CHARACTERISTIC_%s_CLIENT_CONFIGURATION_HANDLE 0x%04x' % (current_characteristic_uuid_string, handle))
634        handle = handle + 1
635
636
637    if properties & property_flags['RELIABLE_WRITE']:
638        size = 2 + 2 + 2 + 2 + 2
639        write_indent(fout)
640        fout.write('// 0x%04x CHARACTERISTIC_EXTENDED_PROPERTIES\n' % (handle))
641        write_indent(fout)
642        write_16(fout, size)
643        write_16(fout, read_only_anybody_flags)
644        write_16(fout, handle)
645        write_16(fout, 0x2900)
646        write_16(fout, 1)   # Reliable Write
647        fout.write("\n")
648
649        database_hash_append_uint16(handle)
650        database_hash_append_uint16(0x2900)
651        database_hash_append_uint16(1)
652
653        handle = handle + 1
654
655def parseGenericDynamicDescriptor(fout, parts, uuid, name):
656    global handle
657    global total_size
658    global current_characteristic_uuid_string
659
660    properties = parseProperties(parts[1])
661    size = 2 + 2 + 2 + 2
662
663    # use write permissions and encryption key size from attribute value and set READ, WRITE, DYNAMIC, READ_ANYBODY
664    flags  = write_permissions_and_key_size_flags_from_properties(properties)
665    flags |= property_flags['READ']
666    flags |= property_flags['WRITE']
667    flags |= property_flags['DYNAMIC']
668
669    write_indent(fout)
670    fout.write('// 0x%04x %s-%s\n' % (handle, name, '-'.join(parts[1:])))
671
672    dump_flags(fout, flags)
673
674    write_indent(fout)
675    write_16(fout, size)
676    write_16(fout, flags)
677    write_16(fout, handle)
678    write_16(fout, uuid)
679    fout.write("\n")
680
681    database_hash_append_uint16(handle)
682    database_hash_append_uint16(uuid)
683
684    defines_for_characteristics.append('#define ATT_CHARACTERISTIC_%s_%s_HANDLE 0x%04x' % (current_characteristic_uuid_string, name, handle))
685    handle = handle + 1
686
687def parseGenericDynamicReadOnlyDescriptor(fout, parts, uuid, name):
688    global handle
689    global total_size
690    global current_characteristic_uuid_string
691
692    properties = parseProperties(parts[1])
693    size = 2 + 2 + 2 + 2
694
695    # use write permissions and encryption key size from attribute value and set READ, DYNAMIC, READ_ANYBODY
696    flags  = write_permissions_and_key_size_flags_from_properties(properties)
697    flags |= property_flags['READ']
698    flags |= property_flags['DYNAMIC']
699
700    write_indent(fout)
701    fout.write('// 0x%04x %s-%s\n' % (handle, name, '-'.join(parts[1:])))
702
703    dump_flags(fout, flags)
704
705    write_indent(fout)
706    write_16(fout, size)
707    write_16(fout, flags)
708    write_16(fout, handle)
709    write_16(fout, 0x2903)
710    fout.write("\n")
711
712    database_hash_append_uint16(handle)
713    database_hash_append_uint16(uuid)
714
715    defines_for_characteristics.append('#define ATT_CHARACTERISTIC_%s_%s_HANDLE 0x%04x' % (current_characteristic_uuid_string, name, handle))
716    handle = handle + 1
717
718def parseServerCharacteristicConfiguration(fout, parts):
719    parseGenericDynamicDescriptor(fout, parts, 0x2903, 'SERVER_CONFIGURATION')
720
721def parseCharacteristicFormat(fout, parts):
722    global handle
723    global total_size
724
725    read_only_anybody_flags = property_flags['READ'];
726
727    identifier = parts[1]
728    presentation_formats[identifier] = handle
729    # print("format '%s' with handle %d\n" % (identifier, handle))
730
731    format     = parts[2]
732    exponent   = parts[3]
733    unit       = parseUUID(parts[4])
734    name_space = parts[5]
735    description = parseUUID(parts[6])
736
737    size = 2 + 2 + 2 + 2 + 7
738
739    write_indent(fout)
740    fout.write('// 0x%04x CHARACTERISTIC_FORMAT-%s\n' % (handle, '-'.join(parts[1:])))
741    write_indent(fout)
742    write_16(fout, size)
743    write_16(fout, read_only_anybody_flags)
744    write_16(fout, handle)
745    write_16(fout, 0x2904)
746    write_sequence(fout, format)
747    write_sequence(fout, exponent)
748    write_uuid(fout, unit)
749    write_sequence(fout, name_space)
750    write_uuid(fout, description)
751    fout.write("\n")
752
753    database_hash_append_uint16(handle)
754    database_hash_append_uint16(0x2904)
755
756    handle = handle + 1
757
758
759def parseCharacteristicAggregateFormat(fout, parts):
760    global handle
761    global total_size
762
763    read_only_anybody_flags = property_flags['READ'];
764    size = 2 + 2 + 2 + 2 + (len(parts)-1) * 2
765
766    write_indent(fout)
767    fout.write('// 0x%04x CHARACTERISTIC_AGGREGATE_FORMAT-%s\n' % (handle, '-'.join(parts[1:])))
768    write_indent(fout)
769    write_16(fout, size)
770    write_16(fout, read_only_anybody_flags)
771    write_16(fout, handle)
772    write_16(fout, 0x2905)
773    for identifier in parts[1:]:
774        if not identifier in presentation_formats:
775            print(parts)
776            print("ERROR: identifier '%s' in CHARACTERISTIC_AGGREGATE_FORMAT undefined" % identifier)
777            sys.exit(1)
778        format_handle = presentation_formats[identifier]
779        write_16(fout, format_handle)
780    fout.write("\n")
781
782    database_hash_append_uint16(handle)
783    database_hash_append_uint16(0x2905)
784
785    handle = handle + 1
786
787def parseExternalReportReference(fout, parts):
788    global handle
789    global total_size
790
791    read_only_anybody_flags = property_flags['READ'];
792    size = 2 + 2 + 2 + 2 + 2
793
794    report_uuid = int(parts[2], 16)
795
796    write_indent(fout)
797    fout.write('// 0x%04x EXTERNAL_REPORT_REFERENCE-%s\n' % (handle, '-'.join(parts[1:])))
798    write_indent(fout)
799    write_16(fout, size)
800    write_16(fout, read_only_anybody_flags)
801    write_16(fout, handle)
802    write_16(fout, 0x2907)
803    write_16(fout, report_uuid)
804    fout.write("\n")
805    handle = handle + 1
806
807def parseReportReference(fout, parts):
808    global handle
809    global total_size
810
811    read_only_anybody_flags = property_flags['READ'];
812    size = 2 + 2 + 2 + 2 + 1 + 1
813
814    report_id = parts[2]
815    report_type = parts[3]
816
817    write_indent(fout)
818    fout.write('// 0x%04x REPORT_REFERENCE-%s\n' % (handle, '-'.join(parts[1:])))
819    write_indent(fout)
820    write_16(fout, size)
821    write_16(fout, read_only_anybody_flags)
822    write_16(fout, handle)
823    write_16(fout, 0x2908)
824    write_sequence(fout, report_id)
825    write_sequence(fout, report_type)
826    fout.write("\n")
827    handle = handle + 1
828
829def parseNumberOfDigitals(fout, parts):
830    global handle
831    global total_size
832
833    read_only_anybody_flags = property_flags['READ'];
834    size = 2 + 2 + 2 + 2 + 1
835
836    no_of_digitals = parts[1]
837
838    write_indent(fout)
839    fout.write('// 0x%04x NUMBER_OF_DIGITALS-%s\n' % (handle, '-'.join(parts[1:])))
840    write_indent(fout)
841    write_16(fout, size)
842    write_16(fout, read_only_anybody_flags)
843    write_16(fout, handle)
844    write_16(fout, 0x2909)
845    write_sequence(fout, no_of_digitals)
846    fout.write("\n")
847    handle = handle + 1
848
849def parseLines(fname_in, fin, fout):
850    global handle
851    global total_size
852
853    line_count = 0;
854    for line in fin:
855        line = line.strip("\n\r ")
856        line_count += 1
857
858        if line.startswith("//"):
859            fout.write("    //" + line.lstrip('/') + '\n')
860            continue
861
862        if line.startswith("#import"):
863            imported_file = ''
864            parts = re.match('#import\s+<(.*)>\w*',line)
865            if parts and len(parts.groups()) == 1:
866                imported_file = parts.groups()[0]
867            parts = re.match('#import\s+"(.*)"\w*',line)
868            if parts and len(parts.groups()) == 1:
869                imported_file = parts.groups()[0]
870            if len(imported_file) == 0:
871                print('ERROR: #import in file %s - line %u neither <name.gatt> nor "name.gatt" form', (fname_in, line_count))
872                continue
873
874            imported_file = getFile( imported_file )
875            print("Importing %s" % imported_file)
876            try:
877                imported_fin = codecs.open (imported_file, encoding='utf-8')
878                fout.write('\n\n    // ' + line + ' -- BEGIN\n')
879                parseLines(imported_file, imported_fin, fout)
880                fout.write('    // ' + line + ' -- END\n')
881            except IOError as e:
882                print('ERROR: Import failed. Please check path.')
883
884            continue
885
886        if line.startswith("#TODO"):
887            print ("WARNING: #TODO in file %s - line %u not handled, skipping declaration:" % (fname_in, line_count))
888            print ("'%s'" % line)
889            fout.write("// " + line + '\n')
890            continue
891
892        if len(line) == 0:
893            continue
894
895        f = io.StringIO(line)
896        parts_list = csv.reader(f, delimiter=',', quotechar='"')
897
898        for parts in parts_list:
899            for index, object in enumerate(parts):
900                parts[index] = object.strip().lstrip('"').rstrip('"')
901
902            if parts[0] == 'PRIMARY_SERVICE':
903                parsePrimaryService(fout, parts)
904                continue
905
906            if parts[0] == 'SECONDARY_SERVICE':
907                parseSecondaryService(fout, parts)
908                continue
909
910            if parts[0] == 'INCLUDE_SERVICE':
911                parseIncludeService(fout, parts)
912                continue
913
914            # 2803
915            if parts[0] == 'CHARACTERISTIC':
916                parseCharacteristic(fout, parts)
917                continue
918
919            # 2900 Characteristic Extended Properties
920
921            # 2901
922            if parts[0] == 'CHARACTERISTIC_USER_DESCRIPTION':
923                parseGenericDynamicDescriptor(fout, parts, 0x2901, 'USER_DESCRIPTION')
924                continue
925
926
927            # 2902 Client Characteristic Configuration - automatically included in Characteristic if
928            # notification / indication is supported
929            if parts[0] == 'CLIENT_CHARACTERISTIC_CONFIGURATION':
930                continue
931
932            # 2903
933            if parts[0] == 'SERVER_CHARACTERISTIC_CONFIGURATION':
934                parseGenericDynamicDescriptor(fout, parts, 0x2903, 'SERVER_CONFIGURATION')
935                continue
936
937            # 2904
938            if parts[0] == 'CHARACTERISTIC_FORMAT':
939                parseCharacteristicFormat(fout, parts)
940                continue
941
942            # 2905
943            if parts[0] == 'CHARACTERISTIC_AGGREGATE_FORMAT':
944                parseCharacteristicAggregateFormat(fout, parts)
945                continue
946
947            # 2906
948            if parts[0] == 'VALID_RANGE':
949                parseGenericDynamicReadOnlyDescriptor(fout, parts, 0x2906, 'VALID_RANGE')
950                continue
951
952            # 2907
953            if parts[0] == 'EXTERNAL_REPORT_REFERENCE':
954                parseExternalReportReference(fout, parts)
955                continue
956
957            # 2908
958            if parts[0] == 'REPORT_REFERENCE':
959                parseReportReference(fout, parts)
960                continue
961
962            # 2909
963            if parts[0] == 'NUMBER_OF_DIGITALS':
964                parseNumberOfDigitals(fout, parts)
965                continue
966
967            # 290A
968            if parts[0] == 'VALUE_TRIGGER_SETTING':
969                parseGenericDynamicDescriptor(fout, parts, 0x290A, 'VALUE_TRIGGER_SETTING')
970                continue
971
972            # 290B
973            if parts[0] == 'ENVIRONMENTAL_SENSING_CONFIGURATION':
974                parseGenericDynamicDescriptor(fout, parts, 0x290B, 'ENVIRONMENTAL_SENSING_CONFIGURATION')
975                continue
976
977            # 290C
978            if parts[0] == 'ENVIRONMENTAL_SENSING_MEASUREMENT':
979                parseGenericDynamicReadOnlyDescriptor(fout, parts, 0x290C, 'ENVIRONMENTAL_SENSING_MEASUREMENT')
980                continue
981
982            # 290D
983            if parts[0] == 'ENVIRONMENTAL_SENSING_TRIGGER_SETTING':
984                parseGenericDynamicDescriptor(fout, parts, 0x290D, 'ENVIRONMENTAL_SENSING_TRIGGER_SETTING')
985                continue
986
987            print("WARNING: unknown token: %s\n" % (parts[0]))
988
989def parse(fname_in, fin, fname_out, tool_path, fout):
990    global handle
991    global total_size
992
993    fout.write(header.format(fname_out, fname_in, tool_path))
994    fout.write('{\n')
995    write_indent(fout)
996    fout.write('// ATT DB Version\n')
997    write_indent(fout)
998    fout.write('1,\n')
999    fout.write("\n")
1000
1001    parseLines(fname_in, fin, fout)
1002
1003    serviceDefinitionComplete(fout)
1004    write_indent(fout)
1005    fout.write("// END\n");
1006    write_indent(fout)
1007    write_16(fout,0)
1008    fout.write("\n")
1009    total_size = total_size + 2
1010
1011    fout.write("}; // total size %u bytes \n" % total_size);
1012
1013def listHandles(fout):
1014    fout.write('\n\n')
1015    fout.write('//\n')
1016    fout.write('// list service handle ranges\n')
1017    fout.write('//\n')
1018    for define in defines_for_services:
1019        fout.write(define)
1020        fout.write('\n')
1021    fout.write('\n')
1022    fout.write('//\n')
1023    fout.write('// list mapping between characteristics and handles\n')
1024    fout.write('//\n')
1025    for define in defines_for_characteristics:
1026        fout.write(define)
1027        fout.write('\n')
1028
1029def getFile( fileName ):
1030    for d in include_paths:
1031        fullFile = os.path.normpath(d + os.sep + fileName) # because Windows exists
1032        # print("test %s" % fullFile)
1033        if os.path.isfile( fullFile ) == True:
1034            return fullFile
1035    print ("'{0}' not found".format( fileName ))
1036    print ("Include paths: %s" % ", ".join(include_paths))
1037    exit(-1)
1038
1039
1040btstack_root = os.path.abspath(os.path.dirname(sys.argv[0]) + '/..')
1041default_includes = [os.path.normpath(path) for path in [ btstack_root + '/src/', btstack_root + '/src/ble/gatt-service/']]
1042
1043parser = argparse.ArgumentParser(description='BLE GATT configuration generator for use with BTstack')
1044
1045parser.add_argument('-I', action='append', nargs=1, metavar='includes',
1046        help='include search path for .gatt service files and bluetooth_gatt.h (default: %s)' % ", ".join(default_includes))
1047parser.add_argument('gattfile', metavar='gattfile', type=str,
1048        help='gatt file to be compiled')
1049parser.add_argument('hfile', metavar='hfile', type=str,
1050        help='header file to be generated')
1051
1052args = parser.parse_args()
1053
1054# add include path arguments
1055if args.I != None:
1056    for d in args.I:
1057        include_paths.append(os.path.normpath(d[0]))
1058
1059# append default include paths
1060include_paths.extend(default_includes)
1061
1062try:
1063    # read defines from bluetooth_gatt.h
1064    gen_path = getFile( 'bluetooth_gatt.h' )
1065    bluetooth_gatt = read_defines(gen_path)
1066
1067    filename = args.hfile
1068    fin  = codecs.open (args.gattfile, encoding='utf-8')
1069
1070    # pass 1: create temp .h file
1071    ftemp = tempfile.TemporaryFile(mode='w+t')
1072    parse(args.gattfile, fin, filename, sys.argv[0], ftemp)
1073    listHandles(ftemp)
1074
1075    # calc GATT Database Hash
1076    db_hash = aes_cmac(bytearray(16), database_hash_message)
1077    if isinstance(db_hash, str):
1078        # python2
1079        db_hash_sequence = [('0x%02x' % ord(i)) for i in db_hash]
1080    elif isinstance(db_hash, bytes):
1081        # python3
1082        db_hash_sequence = [('0x%02x' % i) for i in db_hash]
1083    else:
1084        print("AES CMAC returns unexpected type %s, abort" % type(db_hash))
1085        sys.exit(1)
1086    # reverse hash to get little endian
1087    db_hash_sequence.reverse()
1088    db_hash_string = ', '.join(db_hash_sequence) + ', '
1089
1090    # pass 2: insert GATT Database Hash
1091    fout = open (filename, 'w')
1092    ftemp.seek(0)
1093    for line in ftemp:
1094        fout.write(line.replace('THE-DATABASE-HASH', db_hash_string))
1095    fout.close()
1096    ftemp.close()
1097
1098    print('Created %s' % filename)
1099
1100except IOError as e:
1101
1102    print(usage)
1103    sys.exit(1)
1104
1105print('Compilation successful!\n')
1106