tcoder
Posts: 20
Joined: Sun Sep 18, 2016 5:05 pm

How to determine if bluetooth client is closed?

Thu Aug 24, 2017 7:15 pm

In my code, I want to make it such that it waits until the client is closed or has left so that I can service the next client. I can't find anyway to determine that the client has closed the socket. How can I do that? Here is my code.

Code: Select all

void *StartBluetoothThread(void *val)
{  
  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_any;         
  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. ERRNO=%d\n", errno);
    char *errorMessage = strerror_r(errno, buf, 1024);
    printf("%s\n", errorMessage);
    return 0;
  }
    
  ret = -1;
  
  if((ret = listen(bluetoothSocket, 1)) == -1)
  {
    printf("Bluetooth listen failed. ERRNO=%d\n", errno);
    char *errorMessage = strerror_r(errno, buf, 1024);
    printf("%s\n", errorMessage);
    return 0;
  }
  
  while (stopThread == false)
  {
    printf("Waiting for new client to connect.\n");
    
    client = accept(bluetoothSocket, (struct sockaddr *)&client_addr, &opt);
    
    if (client == -1)
    {
      printf("Bluetooth connect failed.\n");
      close(client);
      delay(1000);
      continue;
    }
         
    printf("Bluetooth connection made.\n");
    
    ba2str(&client_addr.rc_bdaddr, buf);
    fprintf(stderr, "accepted connection from %s\n", buf);
    memset(buf, 0, sizeof(buf));

    while (client > 0)
    {
      // read data from the client
      bytes_read = read(client, buf, sizeof(buf));
    
      if (bytes_read > 0) 
      {
        printf("Bluetooth bytes received [%s]\n", buf);
      }
      delay(500);
    }     
    close(client);
    printf("Bluetooth disconnected.\n");
  }      
  
  close(client);
  close(bluetoothSocket);
  return 0;    
}

Return to “C/C++”