1#!/usr/bin/env python 2# 3# BLE GATT configuration generator for use with BTstack, v0.1 4# Copyright 2011 Matthias Ringwald 5# 6# Format of input file: 7# PRIMARY_SERVICE, SERVICE_UUID 8# CHARACTERISTIC, ATTRIBUTE_TYPE_UUID, [READ | WRITE | DYNAMIC], VALUE 9 10import codecs 11import csv 12import io 13import os 14import re 15import string 16 17header = ''' 18// {0} generated from {1} for BTstack 19 20// binary representation 21// attribute size in bytes (16), flags(16), handle (16), uuid (16/128), value(...) 22 23#include <stdint.h> 24 25const uint8_t profile_data[] = 26''' 27 28usage = ''' 29Usage: ./compile_gatt.py profile.gatt profile.h 30''' 31 32import re 33import sys 34 35print(''' 36BLE configuration generator for use with BTstack, v0.1 37Copyright 2011 Matthias Ringwald 38''') 39 40assigned_uuids = { 41 'GAP_SERVICE' : 0x1800, 42 'GATT_SERVICE' : 0x1801, 43 'GAP_DEVICE_NAME' : 0x2a00, 44 'GAP_APPEARANCE' : 0x2a01, 45 'GAP_PERIPHERAL_PRIVACY_FLAG' : 0x2A02, 46 'GAP_RECONNECTION_ADDRESS' : 0x2A03, 47 'GAP_PERIPHERAL_PREFERRED_CONNECTION_PARAMETERS' : 0x2A04, 48 'GATT_SERVICE_CHANGED' : 0x2a05, 49} 50 51property_flags = { 52 'BROADCAST' : 0x01, 53 'READ' : 0x02, 54 'WRITE_WITHOUT_RESPONSE' : 0x04, 55 'WRITE' : 0x08, 56 'NOTIFY': 0x10, 57 'INDICATE' : 0x20, 58 'AUTHENTICATED_SIGNED_WRITE' : 0x40, 59 'EXTENDED_PROPERTIES' : 0x80, 60 # custom BTstack extension 61 'DYNAMIC': 0x100, 62 'LONG_UUID': 0x200, 63 'AUTHENTICATION_REQUIRED': 0x400, 64 'AUTHORIZATION_REQUIRED': 0x800, 65 'ENCRYPTION_KEY_SIZE_7': 0x6000, 66 'ENCRYPTION_KEY_SIZE_8': 0x7000, 67 'ENCRYPTION_KEY_SIZE_9': 0x8000, 68 'ENCRYPTION_KEY_SIZE_10': 0x9000, 69 'ENCRYPTION_KEY_SIZE_11': 0xa000, 70 'ENCRYPTION_KEY_SIZE_12': 0xb000, 71 'ENCRYPTION_KEY_SIZE_13': 0xc000, 72 'ENCRYPTION_KEY_SIZE_14': 0xd000, 73 'ENCRYPTION_KEY_SIZE_15': 0xe000, 74 'ENCRYPTION_KEY_SIZE_16': 0xf000, 75 # only used by gatt compiler >= 0xffff 76 # Extended Properties 77 'RELIABLE_WRITE': 0x10000, 78} 79 80services = dict() 81characteristic_indices = dict() 82presentation_formats = dict() 83current_service_uuid_string = "" 84current_service_start_handle = 0 85current_characteristic_uuid_string = "" 86defines_for_characteristics = [] 87defines_for_services = [] 88 89handle = 1 90total_size = 0 91 92def read_defines(infile): 93 defines = dict() 94 with open (infile, 'rt') as fin: 95 for line in fin: 96 parts = re.match('#define\s+(\w+)\s+(\w+)',line) 97 if parts and len(parts.groups()) == 2: 98 (key, value) = parts.groups() 99 defines[key] = int(value, 16) 100 return defines 101 102def keyForUUID(uuid): 103 keyUUID = "" 104 for i in uuid: 105 keyUUID += "%02x" % i 106 return keyUUID 107 108def c_string_for_uuid(uuid): 109 return uuid.replace('-', '_') 110 111def twoByteLEFor(value): 112 return [ (value & 0xff), (value >> 8)] 113 114def is_128bit_uuid(text): 115 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): 116 return True 117 return False 118 119def parseUUID128(uuid): 120 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) 121 uuid_bytes = [] 122 for i in range(8, 0, -1): 123 uuid_bytes = uuid_bytes + twoByteLEFor(int(parts.group(i),16)) 124 return uuid_bytes 125 126def parseUUID(uuid): 127 if uuid in assigned_uuids: 128 return twoByteLEFor(assigned_uuids[uuid]) 129 uuid_upper = uuid.upper().replace('.','_') 130 if uuid_upper in bluetooth_gatt: 131 return twoByteLEFor(bluetooth_gatt[uuid_upper]) 132 if is_128bit_uuid(uuid): 133 return parseUUID128(uuid) 134 uuidInt = int(uuid, 16) 135 return twoByteLEFor(uuidInt) 136 137def parseProperties(properties): 138 value = 0 139 parts = properties.split("|") 140 for property in parts: 141 property = property.strip() 142 if property in property_flags: 143 value |= property_flags[property] 144 else: 145 print("WARNING: property %s undefined" % (property)) 146 return value 147 148def write_8(fout, value): 149 fout.write( "0x%02x, " % (value & 0xff)) 150 151def write_16(fout, value): 152 fout.write('0x%02x, 0x%02x, ' % (value & 0xff, (value >> 8) & 0xff)) 153 154def write_uuid(uuid): 155 for byte in uuid: 156 fout.write( "0x%02x, " % byte) 157 158def write_string(fout, text): 159 for l in text.lstrip('"').rstrip('"'): 160 write_8(fout, ord(l)) 161 162def write_sequence(fout, text): 163 parts = text.split() 164 for part in parts: 165 fout.write("0x%s, " % (part.strip())) 166 167def write_indent(fout): 168 fout.write(" ") 169 170def is_string(text): 171 for item in text.split(" "): 172 if not all(c in string.hexdigits for c in item): 173 return True 174 return False 175 176def add_client_characteristic_configuration(properties): 177 return properties & (property_flags['NOTIFY'] | property_flags['INDICATE']) 178 179def serviceDefinitionComplete(fout): 180 global services 181 if current_service_uuid_string: 182 fout.write("\n") 183 # print("append service %s = [%d, %d]" % (current_characteristic_uuid_string, current_service_start_handle, handle-1)) 184 defines_for_services.append('#define ATT_SERVICE_%s_START_HANDLE 0x%04x' % (current_service_uuid_string, current_service_start_handle)) 185 defines_for_services.append('#define ATT_SERVICE_%s_END_HANDLE 0x%04x' % (current_service_uuid_string, handle-1)) 186 services[current_service_uuid_string] = [current_service_start_handle, handle-1] 187 188def parseService(fout, parts, service_type): 189 global handle 190 global total_size 191 global current_service_uuid_string 192 global current_service_start_handle 193 194 serviceDefinitionComplete(fout) 195 196 property = property_flags['READ']; 197 198 write_indent(fout) 199 fout.write('// 0x%04x %s\n' % (handle, '-'.join(parts))) 200 201 uuid = parseUUID(parts[1]) 202 uuid_size = len(uuid) 203 204 size = 2 + 2 + 2 + uuid_size + 2 205 206 if service_type == 0x2802: 207 size += 4 208 209 write_indent(fout) 210 write_16(fout, size) 211 write_16(fout, property) 212 write_16(fout, handle) 213 write_16(fout, service_type) 214 write_uuid(uuid) 215 fout.write("\n") 216 217 current_service_uuid_string = c_string_for_uuid(parts[1]) 218 current_service_start_handle = handle 219 handle = handle + 1 220 total_size = total_size + size 221 222def parsePrimaryService(fout, parts): 223 parseService(fout, parts, 0x2800) 224 225def parseSecondaryService(fout, parts): 226 parseService(fout, parts, 0x2801) 227 228def parseIncludeService(fout, parts): 229 global handle 230 global total_size 231 232 property = property_flags['READ']; 233 234 write_indent(fout) 235 fout.write('// 0x%04x %s\n' % (handle, '-'.join(parts))) 236 237 uuid = parseUUID(parts[1]) 238 uuid_size = len(uuid) 239 if uuid_size > 2: 240 uuid_size = 0 241 # print("Include Service ", c_string_for_uuid(uuid)) 242 243 size = 2 + 2 + 2 + 2 + 4 + uuid_size 244 245 keyUUID = c_string_for_uuid(parts[1]) 246 247 write_indent(fout) 248 write_16(fout, size) 249 write_16(fout, property) 250 write_16(fout, handle) 251 write_16(fout, 0x2802) 252 write_16(fout, services[keyUUID][0]) 253 write_16(fout, services[keyUUID][1]) 254 if uuid_size > 0: 255 write_uuid(uuid) 256 fout.write("\n") 257 258 handle = handle + 1 259 total_size = total_size + size 260 261 262def parseCharacteristic(fout, parts): 263 global handle 264 global total_size 265 global current_characteristic_uuid_string 266 global characteristic_indices 267 268 property_read = property_flags['READ']; 269 270 # enumerate characteristics with same UUID, using optional name tag if available 271 current_characteristic_uuid_string = c_string_for_uuid(parts[1]); 272 index = 1 273 if current_characteristic_uuid_string in characteristic_indices: 274 index = characteristic_indices[current_characteristic_uuid_string] + 1 275 characteristic_indices[current_characteristic_uuid_string] = index 276 if len(parts) > 4: 277 current_characteristic_uuid_string += '_' + parts[4].upper().replace(' ','_') 278 else: 279 current_characteristic_uuid_string += ('_%02x' % index) 280 281 uuid = parseUUID(parts[1]) 282 uuid_size = len(uuid) 283 properties = parseProperties(parts[2]) 284 value = ', '.join([str(x) for x in parts[3:]]) 285 286 # reliable writes is defined in an extended properties 287 if (properties & property_flags['RELIABLE_WRITE']): 288 properties = properties | property_flags['EXTENDED_PROPERTIES'] 289 290 write_indent(fout) 291 fout.write('// 0x%04x %s\n' % (handle, '-'.join(parts[0:3]))) 292 293 size = 2 + 2 + 2 + 2 + (1+2+uuid_size) 294 write_indent(fout) 295 write_16(fout, size) 296 write_16(fout, property_read) 297 write_16(fout, handle) 298 write_16(fout, 0x2803) 299 write_8(fout, properties) 300 write_16(fout, handle+1) 301 write_uuid(uuid) 302 fout.write("\n") 303 handle = handle + 1 304 total_size = total_size + size 305 306 size = 2 + 2 + 2 + uuid_size 307 if is_string(value): 308 size = size + len(value) 309 else: 310 size = size + len(value.split()) 311 312 if uuid_size == 16: 313 properties = properties | property_flags['LONG_UUID']; 314 315 write_indent(fout) 316 fout.write('// 0x%04x VALUE-%s-'"'%s'"'\n' % (handle, '-'.join(parts[1:3]),value)) 317 write_indent(fout) 318 write_16(fout, size) 319 write_16(fout, properties) 320 write_16(fout, handle) 321 write_uuid(uuid) 322 if is_string(value): 323 write_string(fout, value) 324 else: 325 write_sequence(fout,value) 326 327 fout.write("\n") 328 defines_for_characteristics.append('#define ATT_CHARACTERISTIC_%s_VALUE_HANDLE 0x%04x' % (current_characteristic_uuid_string, handle)) 329 handle = handle + 1 330 331 if add_client_characteristic_configuration(properties): 332 size = 2 + 2 + 2 + 2 + 2 333 write_indent(fout) 334 fout.write('// 0x%04x CLIENT_CHARACTERISTIC_CONFIGURATION\n' % (handle)) 335 write_indent(fout) 336 write_16(fout, size) 337 write_16(fout, property_flags['READ'] | property_flags['WRITE'] | property_flags['DYNAMIC']) 338 write_16(fout, handle) 339 write_16(fout, 0x2902) 340 write_16(fout, 0) 341 fout.write("\n") 342 defines_for_characteristics.append('#define ATT_CHARACTERISTIC_%s_CLIENT_CONFIGURATION_HANDLE 0x%04x' % (current_characteristic_uuid_string, handle)) 343 handle = handle + 1 344 345 if properties & property_flags['RELIABLE_WRITE']: 346 size = 2 + 2 + 2 + 2 + 2 347 write_indent(fout) 348 fout.write('// 0x%04x CHARACTERISTIC_EXTENDED_PROPERTIES\n' % (handle)) 349 write_indent(fout) 350 write_16(fout, size) 351 write_16(fout, property_flags['READ']) 352 write_16(fout, handle) 353 write_16(fout, 0x2900) 354 write_16(fout, 1) # Reliable Write 355 fout.write("\n") 356 handle = handle + 1 357 358def parseCharacteristicUserDescription(fout, parts): 359 global handle 360 global total_size 361 global current_characteristic_uuid_string 362 363 properties = parseProperties(parts[1]) 364 value = parts[2] 365 366 size = 2 + 2 + 2 + 2 367 if is_string(value): 368 size = size + len(value) - 2 369 else: 370 size = size + len(value.split()) 371 372 write_indent(fout) 373 fout.write('// 0x%04x CHARACTERISTIC_USER_DESCRIPTION-%s\n' % (handle, '-'.join(parts[1:]))) 374 write_indent(fout) 375 write_16(fout, size) 376 write_16(fout, properties) 377 write_16(fout, handle) 378 write_16(fout, 0x2901) 379 if is_string(value): 380 write_string(fout, value) 381 else: 382 write_sequence(fout,value) 383 fout.write("\n") 384 defines_for_characteristics.append('#define ATT_CHARACTERISTIC_%s_USER_DESCRIPTION_HANDLE 0x%04x' % (current_characteristic_uuid_string, handle)) 385 handle = handle + 1 386 387def parseServerCharacteristicConfiguration(fout, parts): 388 global handle 389 global total_size 390 global current_characteristic_uuid_string 391 392 properties = parseProperties(parts[1]) 393 properties = properties | property_flags['DYNAMIC'] 394 size = 2 + 2 + 2 + 2 395 396 write_indent(fout) 397 fout.write('// 0x%04x SERVER_CHARACTERISTIC_CONFIGURATION-%s\n' % (handle, '-'.join(parts[1:]))) 398 write_indent(fout) 399 write_16(fout, size) 400 write_16(fout, properties) 401 write_16(fout, handle) 402 write_16(fout, 0x2903) 403 fout.write("\n") 404 defines_for_characteristics.append('#define ATT_CHARACTERISTIC_%s_SERVER_CONFIGURATION_HANDLE 0x%04x' % (current_characteristic_uuid_string, handle)) 405 handle = handle + 1 406 407def parseCharacteristicFormat(fout, parts): 408 global handle 409 global total_size 410 411 property_read = property_flags['READ']; 412 413 identifier = parts[1] 414 presentation_formats[identifier] = handle 415 # print("format '%s' with handle %d\n" % (identifier, handle)) 416 417 format = parts[2] 418 exponent = parts[3] 419 unit = parseUUID(parts[4]) 420 name_space = parts[5] 421 description = parseUUID(parts[6]) 422 423 size = 2 + 2 + 2 + 2 + 7 424 425 write_indent(fout) 426 fout.write('// 0x%04x CHARACTERISTIC_FORMAT-%s\n' % (handle, '-'.join(parts[1:]))) 427 write_indent(fout) 428 write_16(fout, size) 429 write_16(fout, property_read) 430 write_16(fout, handle) 431 write_16(fout, 0x2904) 432 write_sequence(fout, format) 433 write_sequence(fout, exponent) 434 write_uuid(unit) 435 write_sequence(fout, name_space) 436 write_uuid(description) 437 fout.write("\n") 438 handle = handle + 1 439 440 441def parseCharacteristicAggregateFormat(fout, parts): 442 global handle 443 global total_size 444 445 property_read = property_flags['READ']; 446 size = 2 + 2 + 2 + 2 + (len(parts)-1) * 2 447 448 write_indent(fout) 449 fout.write('// 0x%04x CHARACTERISTIC_AGGREGATE_FORMAT-%s\n' % (handle, '-'.join(parts[1:]))) 450 write_indent(fout) 451 write_16(fout, size) 452 write_16(fout, property_read) 453 write_16(fout, handle) 454 write_16(fout, 0x2905) 455 for identifier in parts[1:]: 456 format_handle = presentation_formats[identifier] 457 if format == 0: 458 print("ERROR: identifier '%s' in CHARACTERISTIC_AGGREGATE_FORMAT undefined" % identifier) 459 sys.exit(1) 460 write_16(fout, format_handle) 461 fout.write("\n") 462 handle = handle + 1 463 464def parseReportReference(fout, parts): 465 global handle 466 global total_size 467 468 property_read = property_flags['READ']; 469 size = 2 + 2 + 2 + 2 + 1 + 1 470 471 report_id = parts[1] 472 report_type = parts[2] 473 474 write_indent(fout) 475 fout.write('// 0x%04x REPORT_REFERENCE-%s\n' % (handle, '-'.join(parts[1:]))) 476 write_indent(fout) 477 write_16(fout, size) 478 write_16(fout, property_read) 479 write_16(fout, handle) 480 write_16(fout, 0x2908) 481 write_sequence(fout, report_id) 482 write_sequence(fout, report_type) 483 fout.write("\n") 484 handle = handle + 1 485 486 487def parseNumberOfDigitals(fout, parts): 488 global handle 489 global total_size 490 491 property_read = property_flags['READ']; 492 size = 2 + 2 + 2 + 2 + 1 493 494 no_of_digitals = parts[1] 495 496 write_indent(fout) 497 fout.write('// 0x%04x NUMBER_OF_DIGITALS-%s\n' % (handle, '-'.join(parts[1:]))) 498 write_indent(fout) 499 write_16(fout, size) 500 write_16(fout, property_read) 501 write_16(fout, handle) 502 write_16(fout, 0x2909) 503 write_sequence(fout, no_of_digitals) 504 fout.write("\n") 505 handle = handle + 1 506 507 508def parse(fname_in, fin, fname_out, fout): 509 global handle 510 global total_size 511 512 fout.write(header.format(fname_out, fname_in)) 513 fout.write('{\n') 514 515 line_count = 0; 516 for line in fin: 517 line = line.strip("\n\r ") 518 line_count += 1 519 520 if line.startswith("//"): 521 fout.write(" //" + line.lstrip('/') + '\n') 522 continue 523 524 if line.startswith("#"): 525 print ("WARNING: #TODO in line %u not handled, skipping declaration:" % line_count) 526 print ("'%s'" % line) 527 fout.write("// " + line + '\n') 528 continue 529 530 if len(line) == 0: 531 continue 532 533 f = io.StringIO(line) 534 parts_list = csv.reader(f, delimiter=',', quotechar='"') 535 536 for parts in parts_list: 537 for index, object in enumerate(parts): 538 parts[index] = object.strip().lstrip('"').rstrip('"') 539 540 if parts[0] == 'PRIMARY_SERVICE': 541 parsePrimaryService(fout, parts) 542 continue 543 544 if parts[0] == 'SECONDARY_SERVICE': 545 parseSecondaryService(fout, parts) 546 continue 547 548 if parts[0] == 'INCLUDE_SERVICE': 549 parseIncludeService(fout, parts) 550 continue 551 552 # 2803 553 if parts[0] == 'CHARACTERISTIC': 554 parseCharacteristic(fout, parts) 555 continue 556 557 # 2900 Characteristic Extended Properties 558 559 # 2901 560 if parts[0] == 'CHARACTERISTIC_USER_DESCRIPTION': 561 parseCharacteristicUserDescription(fout, parts) 562 continue 563 564 565 # 2902 Client Characteristic Configuration - automatically included in Characteristic if 566 # notification / indication is supported 567 if parts[0] == 'CHARACTERISTIC_USER_DESCRIPTION': 568 continue 569 570 # 2903 571 if parts[0] == 'SERVER_CHARACTERISTIC_CONFIGURATION': 572 parseServerCharacteristicConfiguration(fout, parts) 573 continue 574 575 # 2904 576 if parts[0] == 'CHARACTERISTIC_FORMAT': 577 parseCharacteristicFormat(fout, parts) 578 continue 579 580 # 2905 581 if parts[0] == 'CHARACTERISTIC_AGGREGATE_FORMAT': 582 parseCharacteristicAggregateFormat(fout, parts) 583 continue 584 585 # 2906 586 if parts[0] == 'VALID_RANGE': 587 print("WARNING: %s not implemented yet\n" % (parts[0])) 588 continue 589 590 # 2907 591 if parts[0] == 'EXTERNAL_REPORT_REFERENCE': 592 print("WARNING: %s not implemented yet\n" % (parts[0])) 593 continue 594 595 # 2908 596 if parts[0] == 'REPORT_REFERENCE': 597 parseReportReference(fout, parts) 598 continue 599 600 # 2909 601 if parts[0] == 'NUMBER_OF_DIGITALS': 602 parseNumberOfDigitals(fout, parts) 603 continue 604 605 # 290A 606 if parts[0] == 'VALUE_TRIGGER_SETTING': 607 print("WARNING: %s not implemented yet\n" % (parts[0])) 608 continue 609 610 # 290B 611 if parts[0] == 'ENVIRONMENTAL_SENSING_CONFIGURATION': 612 print("WARNING: %s not implemented yet\n" % (parts[0])) 613 continue 614 615 # 290C 616 if parts[0] == 'ENVIRONMENTAL_SENSING_MEASUREMENT': 617 print("WARNING: %s not implemented yet\n" % (parts[0])) 618 continue 619 620 # 290D 621 if parts[0] == 'ENVIRONMENTAL_SENSING_TRIGGER_SETTING': 622 print("WARNING: %s not implemented yet\n" % (parts[0])) 623 continue 624 625 # 2906 626 if parts[0] == 'VALID_RANGE': 627 print("WARNING: %s not implemented yet\n" % (parts[0])) 628 continue 629 630 print("WARNING: unknown token: %s\n" % (parts[0])) 631 632 serviceDefinitionComplete(fout) 633 write_indent(fout) 634 fout.write("// END\n"); 635 write_indent(fout) 636 write_16(fout,0) 637 fout.write("\n") 638 total_size = total_size + 2 639 640 fout.write("}; // total size %u bytes \n" % total_size); 641 642def listHandles(fout): 643 fout.write('\n\n') 644 fout.write('//\n') 645 fout.write('// list service handle ranges\n') 646 fout.write('//\n') 647 for define in defines_for_services: 648 fout.write(define) 649 fout.write('\n') 650 fout.write('\n') 651 fout.write('//\n') 652 fout.write('// list mapping between characteristics and handles\n') 653 fout.write('//\n') 654 for define in defines_for_characteristics: 655 fout.write(define) 656 fout.write('\n') 657 658if (len(sys.argv) < 3): 659 print(usage) 660 sys.exit(1) 661try: 662 # read defines from bluetooth_gatt.h 663 btstack_root = os.path.abspath(os.path.dirname(sys.argv[0]) + '/..') 664 gen_path = btstack_root + '/src/bluetooth_gatt.h' 665 bluetooth_gatt = read_defines(gen_path) 666 667 filename = sys.argv[2] 668 fin = codecs.open (sys.argv[1], encoding='utf-8') 669 fout = open (filename, 'w') 670 parse(sys.argv[1], fin, filename, fout) 671 listHandles(fout) 672 fout.close() 673 print('Created %s' % filename) 674 675except IOError as e: 676 print(usage) 677 sys.exit(1) 678 679print('Compilation successful!\n') 680