diff --git a/sys/include/net/bluetil/addr.h b/sys/include/net/bluetil/addr.h index f69907bc63..a2d8dc42e4 100644 --- a/sys/include/net/bluetil/addr.h +++ b/sys/include/net/bluetil/addr.h @@ -55,6 +55,19 @@ void bluetil_addr_sprint(char *out, const uint8_t *addr); */ void bluetil_addr_print(const uint8_t *addr); +/** + * @brief Parse a BLE address from the given string + * + * @param[out] addr buffer to write the BLE address, *must* be able to hold + * BLE_ADDR_LEN bytes + * @param[in] addr_str address string, must be at least of length + * (BLUETIL_ADDR_STRLEN - 1) + * + * @return a pointer to the resulting address on success + * @return NULL on parsing error + */ +uint8_t *bluetil_addr_from_str(uint8_t *addr, const char *addr_str); + /** * @brief Get a string representation of the given BLE addresses IID-based * link local address diff --git a/sys/net/ble/bluetil/bluetil_addr/bluetil_addr.c b/sys/net/ble/bluetil/bluetil_addr/bluetil_addr.c index 910f4121e0..b620f9e415 100644 --- a/sys/net/ble/bluetil/bluetil_addr/bluetil_addr.c +++ b/sys/net/ble/bluetil/bluetil_addr/bluetil_addr.c @@ -26,6 +26,13 @@ #include "net/eui48.h" #include "net/bluetil/addr.h" +static int _is_hex_char(char c) +{ + return (((c >= '0') && (c <= '9')) || + ((c >= 'A') && (c <= 'F')) || + ((c >= 'a') && (c <= 'f'))); +} + void bluetil_addr_sprint(char *out, const uint8_t *addr) { assert(out); @@ -50,6 +57,28 @@ void bluetil_addr_print(const uint8_t *addr) printf("%s", str); } +uint8_t *bluetil_addr_from_str(uint8_t *addr, const char *addr_str) +{ + assert(addr); + assert(addr_str); + + /* check for colons */ + for (unsigned i = 2; i < (BLUETIL_ADDR_STRLEN - 1); i += 3) { + if (addr_str[i] != ':') { + return NULL; + } + } + + unsigned pos = BLE_ADDR_LEN; + for (unsigned i = 0; i < (BLUETIL_ADDR_STRLEN - 1); i += 3) { + if (!_is_hex_char(addr_str[i]) || !_is_hex_char(addr_str[i + 1])) { + return NULL; + } + addr[--pos] = fmt_hex_byte(addr_str + i); + } + return addr; +} + void bluetil_addr_ipv6_l2ll_sprint(char *out, const uint8_t *addr) { assert(out);