Working with UUID



  • Hi guys,

    I know it seems like a very noob question, but I can't for the life of me figure out how I can instantiate a UUID using a UUID string.

    For example, I have the uuid string 15ECCA29-0B6E-40B3-9181-BE9509B53200, how can I assign it to the service ID of my BLE device? In the example below, I want to set the service uuid to the provided uuid string,

    from network import Bluetooth
    ble = Bluetooth()
    ble.set_advertisement(name = "BLE Device",  service_uuid= `15ECCA29-0B6E-40B3-9181-BE9509B53200`)
    

    but it results in all kind of weird things happen (Most likely some serious buffer overflows).

    Does anyone know how to do that? Is there a module I need to import (it's not UUID or uuid,...)?

    Thanks,
    M.



  • @jmarcelino said in Working with UUID:

    For some reason I've not yet understood the bytes also have to be in reverse order of how you'd type them.

    Dear @jmarcelino,

    coming from [1], we have been able to shed some light onto the background of the byte-swapping of UUIDs within some Bluetooth stacks around and wrapped it up at [2] by a) reusing your uuid2bytes from above and b) complementing it with the inverted function.

    With kind regards,
    Andreas.

    [1] https://forum.pycom.io/topic/5335/ble-decoding-service-uuid
    [2] https://github.com/hiveeyes/hiveeyes-micropython-firmware/blob/a8249fd8e9895623de8047ca2d6478dba1351aa8/terkin/network/ble/util.py



  • @jmarcelino Thank you for posting that answer! Just spend a long time trying to figure it out and finally found your post. Would be lovely if someone at Pycom could pick this piece of info and add it to the docs.



  • I ran into this same issue. One thing to not is the that the "standard" UUID representation is little endian which is somewhat reverse logic to what we are often used to.

    Took me a bit to wrap my head around why the more common format is not used and realized it is probably more efficient to use the 16byte long bytes object.

    It would be nice to support either format.



  • @jmarcelino that's awesome!
    Thanks



  • @mohpor

    128 bit UUIDs are handled on the Py as bytes objects. For some reason I've not yet understood the bytes also have to be in reverse order of how you'd type them.

    I've made a little function which takes your usual UUID string and returns a suitable bytes object. You're welcome to use it:

    def uuid2bytes(uuid):
        uuid = uuid.encode().replace(b'-',b'')
        tmp = binascii.unhexlify(uuid)
        return bytes(reversed(tmp))
    

    you can use it like this:

    srv1 = bluetooth.service(uuid=uuid2bytes('15ECCA29-0B6E-40B3-9181-BE9509B53200'), isprimary=True)
    

Log in to reply
 

Pycom on Twitter