/* Notes by Henry Walker
   2013-06-19:  compile with the line
      gcc -o rfcomm-serial-getname-alt rfcomm-serial-getname-alt.c -lbluetooth

   This program retrieves the 16-character name of the robot over Bluetooth

   Since the Scribbler 2 echos all commands it receives,
   * since the scribbler command for the first or last half of the name
     contains 9 bytes, this version counts the number of bytes in the echo
     before retrieving the name information
   * since each half name is 8 characters, the program continues to read
     the name over Bluetooth until all 8 characters have been retrieved      
*/

#include <stdio.h>
#include <fcntl.h> 
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char **argv)
{
  char message[9];
  int robot = open ("/dev/rfcomm0", O_RDWR);
  int nbytes = 8;
  int i;

  message[0]= 78; // get first 8 bytes of the robot's 16-byte name
  message[1]= 0;  // not used
  message[2]= 0;  // not used
  message[3]= 0;  // not used
  message[4]= 0;  // not used
  message[5]= 0;  // not used
  message[6]= 0;  // not used
  message[7]= 0;  // not used
  message[8]= 0;  // not used

  write (robot, message, 9);
  i = 9;
  while (i > 0)
    i-=read(robot, message, 1);

  printf ("retrieving first 8 bytes of robot's 16-byte name\n");
  i = 0;
  while (i < nbytes)
    i+=read(robot, &message[i], 1);
  printf ("number of bytes returned:  %d\n", nbytes);
  for (i = 0; i < nbytes; i++)
    putchar(message[i]);
  printf ("\n");

  message[0]= 64; // get last 8 bytes of the robot's 16-byte name
  message[1]= 0;  // not used
  message[2]= 0;  // not used
  message[3]= 0;  // not used
  message[4]= 0;  // not used
  message[5]= 0;  // not used
  message[6]= 0;  // not used
  message[7]= 0;  // not used
  message[8]= 0;  // not used

  write (robot, message, 9);
  i = 9;
  while (i > 0)
    i-=read(robot, message, 1);

  printf ("retrieving last 8 bytes of robot's 16-byte name\n");
  i = 0;
  while (i < nbytes)
    i+=read(robot, &message[i], 1);
  printf ("number of bytes returned:  %d\n", nbytes);
  for (i = 0; i < nbytes; i++)
    putchar(message[i]);
  printf ("\n");

  close(robot);
  return 0;
}
