经过长时间的努力,我成功地让SDP工作了。以下是代码。它是根据https://people.csail.mit.edu/albert/bluez-intro/x604.html上的示例设计的。
在我看来,这似乎过于复杂了。这是“计算机科学家疯狂”的一个例子!对于像这样常见而简单的事情,他们应该包含一个便捷的封装。
#define BYTE uint8_t
#define UUID uuid_t
#define LIST sdp_list_t
#define SESSION sdp_session_t
#define RECORD sdp_record_t
#define DATA sdp_data_t
#include "stdio.h"
#include "string.h"
#include "ctype.h"
#include "unistd.h"
#include "stdlib.h"
#include "bluetooth/bluetooth.h"
#include "bluetooth/sdp.h"
#include "bluetooth/sdp_lib.h"
#define DEV_ADDR "E4:12:1D:96:10:EF"
main(
int argc,
char **argv)
{
static BYTE uuid[16] = {
0xd8, 0x30, 0x8c, 0x4e, 0x94, 0x69, 0x40, 0x51,
0x8a, 0xdc, 0x7a, 0x26, 0x63, 0xe4, 0x15, 0xe2
};
int chan;
chan = GetServiceChannel( uuid );
if( chan > 0 ) {
printf( "specified service is on channel %d\n", chan );
}
else {
fprintf( stderr, " can't find channel\n" );
}
exit( 0 );
}
int
GetServiceChannel(
BYTE *uuid)
{
SESSION *s;
UUID svc_uuid;
LIST *response_list,*search_list,*attrid_list,*r;
RECORD *rec;
int range;
int n;
BYTE addr[6];
int chan=0;
str2ba( DEV_ADDR, (bdaddr_t *)&addr );
s = sdp_connect( BDADDR_ANY, (bdaddr_t *)&addr, SDP_RETRY_IF_BUSY );
if( !s ) {
fprintf( stderr, "can't connect to sdp server\n" );
return( 0 );
}
sdp_uuid128_create( &svc_uuid, uuid );
search_list = sdp_list_append( NULL, &svc_uuid );
range = 0x0000ffff;
attrid_list = sdp_list_append( NULL, &range );
n = sdp_service_search_attr_req(
s, search_list, SDP_ATTR_REQ_RANGE, attrid_list, &response_list );
if( n ) {
fprintf( stderr, "search failed.\n" );
return( 0 );;
}
n = sdp_list_len( response_list );
if( n <= 0 ) {
fprintf( stderr, "no responses.\n" );
return( 0 );;
}
r = response_list;
while( r ) {
sdp_record_t *rec;
LIST *proto_list,*p;
rec = (RECORD *)r->data;
n = sdp_get_access_protos( rec, &proto_list );
if( n ) {
fprintf( stderr, "can't get access protocols.\n" );
return( 0 );
}
p = proto_list;
while( p ) {
LIST *pds;
int proto=0;
pds = (LIST *)p->data;
while( pds ) {
DATA *d;
int dtd;
d = pds->data;
while( d ) {
dtd = d->dtd;
switch( dtd ) {
case SDP_UUID16:
case SDP_UUID32:
case SDP_UUID128:
proto = sdp_uuid_to_proto( &d->val.uuid );
break;
case SDP_UINT8:
if( proto == RFCOMM_UUID ) {
chan = d->val.uint8;
}
break;
}
d = d->next;
}
pds = pds->next;
}
sdp_list_free( (LIST *)p->data, 0 );
p = p->next;
}
sdp_list_free( proto_list, 0 );
r = r->next;
}
return( chan );
}
要做的事情:
To make:
gcc getchan.c -o getchan -l bluetooth