Created
September 24, 2019 23:26
-
-
Save kbrafford/b517289bdbbd2102b1e23bc3c7aa841e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# uuid.py | |
# | |
# Create a Bluetooth LE service UUID, formatted for use with Nordic's SDK | |
# | |
# Keith Brafford (2019 Sep 24) | |
import click | |
import requests | |
import re | |
import sys | |
# nordic lbs uuid (for testing) | |
#uuid = '00001523-1212-EFDE-1523-785FEABCD123' | |
# Reverse and flatten a 2-deep nested list | |
def flatten_uuid(uuid): | |
def inner(l): | |
while l: | |
yield l.pop() | |
def outer(l): | |
while l: | |
g = inner(l.pop()) | |
for item in g: | |
yield item | |
g = outer([[int(x) for x in bytes.fromhex(s)] for s in uuid.split("-")]) | |
return list(g) | |
TEMPLATE = """/* ble service '%s' UUID: %s */ | |
#define %s_UUID_BASE {%s \\ | |
%s%s} | |
""" | |
def uuid_to_c(uuid, svc_name="MYSERVICE"): | |
# zero out the values that will be over-written by the characteristic | |
uuid = uuid[0:4] + "0000" + uuid[8:] | |
values = flatten_uuid(uuid) | |
vals_0 = ", ".join(["0x%02x" % v for v in values[:8]]) | |
vals_1 = ", ".join(["0x%02x" % v for v in values[8:]]).strip(", ") | |
indentation = " " * (len(svc_name) + 20) | |
print(TEMPLATE % (svc_name.lower(), uuid, svc_name.upper(), | |
vals_0, indentation, vals_1)) | |
@click.command() | |
@click.option('--uuid', default = 'x', help="your existing uuid; omit to generate random uuid") | |
@click.option('--svc_name', default = "MYSERVICE", help="ble service name") | |
def uuid(uuid, svc_name): | |
"""Generate Bluetooth Low Energy UUIDs for use with the Nordic Semiconductor Ecosystem""" | |
r = re.compile("[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}") | |
UUID_URL = "https://www.uuidgenerator.net/version4" | |
if uuid == "x": | |
content = requests.get(UUID_URL).text | |
uuid = r.findall(content)[0] | |
else: | |
# do a sanity check to see that they passed in something that looks like the | |
# type of UUID we are looking for | |
if not r.findall(uuid): | |
sys.stderr.write("Error: '%s' doesn't look like a BLE UUID\nsee %s for details" % | |
(uuid, UUID_URL)) | |
sys.exit(1) | |
uuid_to_c(uuid, svc_name = svc_name) | |
if __name__ == "__main__": | |
uuid() |
Author
kbrafford
commented
Sep 25, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment