Search code examples
c++bluetooth-lowenergypopen

How to store the hcitool lescan result with C language, and print it on the terminal


I try to capture the result of the hcitool lescan command on the terminal of ubuntu linux, 18.04.

Here is my code

x_pipe = popen("/usr/bin/hcitool lescan", "w");
if (!x_pipe) 
{
  perror("x popen failed!");
  pclose(x_pipe);
  return -1;
}
sleep(3);
while(fgets(buffer, sizeof(buffer), x_pipe) != NULL)
{
  printf("Debug: %s", buffer);
}

Here is my test result

root@device100:~# bt_service
LE Scan ...
76:AC:17:0C:B8:CF (unknown)
23:61:7A:13:08:E2 (unknown)
27:17:7F:D4:2E:13 (unknown)
20:20:CE:D8:42:22 (unknown)
5C:AD:01:C6:EB:7D (unknown)

I know that I send the command to bluetooth device, and it has start scaning. But, this result from the terminal is unexpect what i thought.

I thought... (expecting)

root@device100:~# bt_service
LE Scan ...
Debug: 76:AC:17:0C:B8:CF (unknown)
Debug: 23:61:7A:13:08:E2 (unknown)
Debug: 27:17:7F:D4:2E:13 (unknown)
Debug: 20:20:CE:D8:42:22 (unknown)
Debug: 5C:AD:01:C6:EB:7D (unknown)

Solution

  • But, I can see the data in the terminal.

    Because (quoting popen manual)

    The return value from popen() is a normal standard I/O stream in all respects save that it must be closed with pclose() rather than fclose(3). Writing to such a stream writes to the standard input of the command; the command's standard output is the same as that of the process that called popen(), unless this is altered by the command itself. Conversely, reading from the stream reads the command's standard output, and the command's standard input is the same as that of the process that called popen().

    You opened your pipe for writing, so stdout of your pipe goes to stdout to your process (your console).

    Just open it for reading

    FILE *x_pipe = popen("/usr/bin/hcitool lescan", "r");
    

    Optionally you can also redirect the commands stderr to stdout to capture all possible output:

    FILE *x_pipe = popen("/usr/bin/hcitool lescan 2>&1", "r");