/*
 * wifimon.c
 * by omin0us <omin0us208@gmail.com>
 * <http://dtors.ath.c> 
 *
 * console based Wifi Strength Meter
 *
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>

#define VERSION   "0.2-test"

/* change to what ever your distro might use */
#define PROCPATH  "/proc/net/wireless"

/* also possibly distro dependant. default is eth0. sometimes will be
 * under wlan0 or wlan1, etc
 */
#define INTERFACE "eth0"


void get_strength(void);
void sig_handle(void);

int link_quality=0;
int poll_interval=1;

int main(){
  
  struct itimerval timer;
 
/* set up our timing intervals */ 
  timer.it_interval.tv_sec = poll_interval;
  timer.it_interval.tv_usec = 0;
  timer.it_value.tv_sec = poll_interval;
  timer.it_value.tv_usec = 0;

/* print a super cool banner msg!!1! */
  printf("omin-wifimon v%s\n",VERSION);
  printf("<omin0us208@gmail.com>\n");
  printf("<http://dtors.ath.cx>\n");
  printf("----------------------\n"); 

  setitimer(ITIMER_REAL,&timer,NULL);
  signal(SIGALRM,sig_handle);

  get_strength();
  while(1)sleep(1);
  return(0);
}


/*
 * draw out the strength meter upon call.
 */

void sig_handle(void){
  int i;
  int bar_len;
  int spaces;
	 
/* some distro's only go up to 92 for strenth. slack goes up to 100. so adjust
 * the math in this acourdingly
 */
  printf("  Link: %d%% \t",((link_quality)*(100)/100));
  
/* calculate the bar meter...in ascii */
  bar_len = ((link_quality)*(100)/100)/5;
  spaces = 20-bar_len;
  printf(" [");
  for(i=0;i<=bar_len;i++)
    printf("#");
  for(i=0;i<spaces;i++)
    printf("-");
    printf("]\r");
  fflush(stdout);
  get_strength();
}

/*
 * parse out the wifi signal information
 */

void get_strength(void){
  FILE *fd;
  char tmp[255];
  char *p;
  
  
    fd = fopen(PROCPATH,"r");
    
    fgets(tmp,255,fd);
    fgets(tmp,255,fd);

/* graph that shit. usually in /proc/net/wireless. ymmv */
    while(fgets(tmp,255,fd)){
      p = tmp + strspn(tmp," ");
      if(!strncmp(p,INTERFACE, strlen(INTERFACE))){
	p += strspn(p," ")+1;
	sscanf(p,"%*s %*s %d %*s %*s %*s %*s %*s %*s %*s  ",&link_quality);
      }
    }

    fclose(fd);
}

 
