Python 脚本:生成随机 NimBLE BLE UUID

以下脚本生成 C++ 格式的随机 BLE UUID 源代码行,适合与 NimBLE 一起使用。

示例输出

random_uuid_example.cpp
static const ble_uuid128_t custom_service =
    BLE_UUID128_INIT(0xB5, 0xB6, 0xA7, 0xB8, 0xC9, 0x8D, 0x90, 0x42,
                     0x8E, 0x39, 0xA5, 0x62, 0x23, 0x90, 0x97, 0x54);

generate_nimble_uuid.py

generate_nimble_uuid.py
#!/usr/bin/env python3
import argparse
import uuid

def main():
    parser = argparse.ArgumentParser(description="Generate C++ BLE UUID source line.")
    parser.add_argument("name", help="Variable name for the UUID")
    args = parser.parse_args()

    u = uuid.uuid4()
    bytes_le = u.bytes_le  # 小端字节序

    # 将字节格式化为 C++ 宏的十六进制
    hex_bytes = ', '.join(f'0x{b:02X}' for b in bytes_le)
    # 分成两行:每行 8 个字节
    hex_list = hex_bytes.split(', ')
    line1 = ', '.join(hex_list[:8])
    line2 = ', '.join(hex_list[8:])
    print(f"static const ble_uuid128_t {args.name} = ")
    print(f"    BLE_UUID128_INIT({line1},")
    print(f"                     {line2});")

if __name__ == "__main__":
    main()

Check out similar posts by category: Bluetooth, Python