2017-08-21 2 views
-1

J'ai un Raspberry Pi Zero W que j'essaye d'écrire le code auquel me connecter. La commande bind() échoue avec -1. Je ne peux pas utiliser BDADDR_ANY que je reçois une erreur de compilation de:Raspberry Pi bluez C++, pourquoi la fonction bind() renvoie -1 (fail)?

prenant adresse temporaire

J'utilise à la place my_bdaddr_any mais c'est ce qui obtient le -1 retour. Si j'utilise my_bdaddr_all ou my_bdaddr_local, la liaison fonctionne, mais le accept() ne fonctionne jamais. Voici mon extrait de code:

char buf[1024] = {0}; 
int bluetoothSocket, client, bytes_read;   
struct sockaddr_rc loc_addr = {0}; 
struct sockaddr_rc client_addr = {0}; 

socklen_t opt = sizeof(client_addr);  

bdaddr_t my_bdaddr_any = {0, 0, 0, 0, 0, 0}; 
bdaddr_t my_bdaddr_all = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; 
bdaddr_t my_bdaddr_local = {0, 0, 0, 0xff, 0xff, 0xff};  

bluetoothSocket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);  

loc_addr.rc_family = AF_BLUETOOTH; 
loc_addr.rc_bdaddr = (bdaddr_t &) my_bdaddr_all;     
loc_addr.rc_channel = (uint8_t) 1; 

int ret = -1; 

if(ret = bind(bluetoothSocket, (struct sockaddr *)&loc_addr, sizeof(loc_addr)) == -1)  
{ 
    printf("Bluetooth bind failed.\n"); 
    return 0; 
} 

listen(bluetoothSocket, 1); 

client = accept(bluetoothSocket, (struct sockaddr *)&client_addr, &opt); 

if (client == -1) 
{ 
    close(client);" 
} 

ba2str(&loc_addr.rc_bdaddr, buf); 
fprintf(stderr, "accepted connection from %s\n", buf); 
memset(buf, 0, sizeof(buf)); 

bytes_read = read(client, buf, sizeof(buf)); 
if (bytes_read > 0) 
{ 
    printf("Bluetooth bytes received [%s]\n", buf); 
} 
close(client); 
close(bluetoothSocket); 
return; 
+0

Avez-vous vérifié 'errno'? –

+0

Je viens de le faire et j'ai reçu le message "Adresse déjà utilisée". Cela n'a pas de sens, mais je ferais mieux d'enquêter. J'essayais auparavant de trouver comment obtenir errno, mais j'ai découvert qu'il s'agissait d'une variable globale définie par la fonction et que tout ce que j'avais à faire était d'ajouter ce code: 'printf (" Liaison Bluetooth a échoué "ERRNO =% d \ n ", errno); char * errorMessage = strerror_r (errno, buf, 1024); printf ("% s \ n", errorMessage); ' –

Répondre

0

Le problème bind() est due à un autre programme en cours qui était déjà lié au périphérique Bluetooth. J'ai ajouté ce code afin de savoir pourquoi j'ai continué à obtenir le -1 sur bind().

if (ret = bind(bluetoothSocket, (struct sockaddr *)&loc_addr, sizeof(loc_addr)) == -1) 
{ 
    printf("Bluetooth bind failed. ERRNO=%d\n", errno); 
    char *errorMessage = strerror_r(errno, buf, 1024); 
    printf("%s\n", errorMessage); 
    return 0; 
}