Add functions for converting bluetooth addresses

This commit is contained in:
Jef Driesen 2018-02-15 08:25:28 +01:00
parent efd47cd9a1
commit becaf02ab6
2 changed files with 83 additions and 0 deletions

View File

@ -24,6 +24,7 @@
#endif
#include <stdlib.h> // malloc, free
#include <stdio.h>
#include "socket.h"
@ -223,6 +224,54 @@ error:
#endif
#endif
char *
dc_bluetooth_addr2str(dc_bluetooth_address_t address, char *str, size_t size)
{
if (str == NULL || size < DC_BLUETOOTH_SIZE)
return NULL;
int n = snprintf(str, size, "%02X:%02X:%02X:%02X:%02X:%02X",
(unsigned char)((address >> 40) & 0xFF),
(unsigned char)((address >> 32) & 0xFF),
(unsigned char)((address >> 24) & 0xFF),
(unsigned char)((address >> 16) & 0xFF),
(unsigned char)((address >> 8) & 0xFF),
(unsigned char)((address >> 0) & 0xFF));
if (n < 0 || (size_t) n >= size)
return NULL;
return str;
}
dc_bluetooth_address_t
dc_bluetooth_str2addr(const char *str)
{
dc_bluetooth_address_t address = 0;
if (str == NULL)
return 0;
unsigned char c = 0;
while ((c = *str++) != '\0') {
if (c == ':') {
continue;
} else if (c >= '0' && c <= '9') {
c -= '0';
} else if (c >= 'A' && c <= 'F') {
c -= 'A' - 10;
} else if (c >= 'a' && c <= 'f') {
c -= 'a' - 10;
} else {
return 0; /* Invalid character! */
}
address <<= 4;
address |= c;
}
return address;
}
dc_bluetooth_address_t
dc_bluetooth_device_get_address (dc_bluetooth_device_t *device)
{

View File

@ -32,6 +32,12 @@
extern "C" {
#endif /* __cplusplus */
/**
* The minimum number of bytes (including the terminating null byte) for
* formatting a bluetooth address as a string.
*/
#define DC_BLUETOOTH_SIZE 18
/**
* Bluetooth address (48 bits).
*/
@ -41,6 +47,34 @@ typedef unsigned __int64 dc_bluetooth_address_t;
typedef unsigned long long dc_bluetooth_address_t;
#endif
/**
* Convert a bluetooth address to a string.
*
* The bluetooth address is formatted as XX:XX:XX:XX:XX:XX, where each
* XX is a hexadecimal number specifying an octet of the 48-bit address.
* The minimum size for the buffer is #DC_BLUETOOTH_SIZE bytes.
*
* @param[in] address A bluetooth address.
* @param[in] str The memory buffer to store the result.
* @param[in] size The size of the memory buffer.
* @returns The null-terminated string on success, or NULL on failure.
*/
char *
dc_bluetooth_addr2str(dc_bluetooth_address_t address, char *str, size_t size);
/**
* Convert a string to a bluetooth address.
*
* The string is expected to be in the format XX:XX:XX:XX:XX:XX, where
* each XX is a hexadecimal number specifying an octet of the 48-bit
* address.
*
* @param[in] address A null-terminated string.
* @returns The bluetooth address on success, or zero on failure.
*/
dc_bluetooth_address_t
dc_bluetooth_str2addr(const char *address);
/**
* Opaque object representing a bluetooth device.
*/