/* Notes
   Sample program from "Bluetooth Essentials for Programmers" 
      by Albert S. Huang and Larry Rudolph, Cambridge University Press, 2007.  
   The program is also available from the textbook's home page

   Programs scans for responding robots using bluetooth and prints their 
   MAC address and name. 

   Additional note by Henry Walker
   2013-06-10:  compile with the line
      gcc -o simplescan simplescan.c -lbluetooth

   Additional comments by Dilan Ustek, Jordan Yuan, 
   Spencer Liberto
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

int main(int argc, char **argv)
{
    inquiry_info *devices = NULL;
    int max_rsp, num_rsp;
    int adapter_id, sock, len, flags;
    int i;
    char addr[19] = { 0 };
    char name[248] = { 0 };

    adapter_id = hci_get_route(NULL); 
    sock = hci_open_dev( adapter_id ); //open socket
    if (adapter_id < 0 || sock < 0) {
        perror("error opening socket");
        exit(1);
    }

    // initializations and memory allocation
    len  = 8;
    max_rsp = 255;
    flags = IREQ_CACHE_FLUSH;
    devices = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));
    
    num_rsp = hci_inquiry(adapter_id, len, max_rsp, NULL, &devices, 
                          flags); //inquire the number of responding devices
    if( num_rsp < 0 ) perror("hci_inquiry");

    // print name and address of each visible device
    for (i = 0; i < num_rsp; i++) {
      ba2str(&(devices+i)->bdaddr, addr); //turn address of the device into string
        memset(name, 0, sizeof(name));
        if (0 != hci_read_remote_name(sock, &(devices+i)->bdaddr, 
                                      sizeof(name), name, 0)) { // if there is no name found, print [unknown]
            strcpy(name, "[unknown]");
        }
        printf("%s  %s\n", addr, name);
    }

    //clean up
    free( devices );
    close( sock );
    return 0;
}
 
