// PC-robot communication
// T. Braunl, April 2020

#include "radio.h"
#include <stdio.h>
#define MAX   8
#define ITER 10

int main ()
{ int   k, i, num, ret ,myid, robot, who, id[256];
  float sum, avg;
  char  rbuf[MAX], sbuf[MAX] = "PSD";

  printf("PC program for robot communication\n");
  RADIOInit();
  myid = RADIOGetID();
  printf("my id is: %d\n", myid);

  // get robot ID
  { printf("scanning IDs\n");
    ret = RADIOStatus(id); 
    if (ret<0) printf("error RADIOStatus\n");
     else printf("number of robots: %d\n", ret);
    if (ret<1)
    { printf("no robots found\n"); return 0; //exit
    }
    for (i=0; i<ret; i++) printf(" %d", id[i]); // print all robot IDs
    printf("\n");                               // new line
    robot = id[ret-1];
    printf("robot ID is %d\n", robot);
  }
  
  sum=0.0;
  for (i=0; i<ITER; i++)
  { RADIOSend(robot, sbuf);
    RADIOReceive(&who, rbuf, MAX);
    printf("%d: received from robot %d value %s\n", i, who, rbuf);
    sscanf ((char*)rbuf, "%d", &num);
    sum +=num;
  }
  avg = sum/ITER;
  printf("Average distance: %5.1f mm\n", avg);
}

