/*
  tdial.cpp
  David Rowe 13/3/02

  Demonstrates calling using the dial-tone detector:
  - takes port 1 off hook
  - waits for dial tone
  - dials port 2
  - waits for rings on dial 2

  DR 13/3/02: Found that Studio 308 doesnt like "11" dialled with 100ms DTMF pulses,
  changed to 200ms (vpbdial) pulses and was OK.
*/

#include "vpbapi.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../kbhit.h"

void verbose(int);
int ctwaitforevent(int h, void *timer,int event_type,int data,int timeout_ms);
int finish = 0;

int main(int argc, char *argv[]) {
	int       h1, h2, finished;
        int       tries,fails; 
	void      *timer1, *timer2;
	int       ret;

	if (argc != 2) {
		printf("usage: tdial Number\n");
		exit(0);
	}
	
	h1 = vpb_open(0,0);
	h2 = vpb_open(0,1);
        vpb_timer_open(&timer1, h1, 0, 1000);
        vpb_timer_open(&timer2, h2, 0, 1000);
	tries = fails = 0;

	vpb_sethook_sync(h1,VPB_ONHOOK);
	vpb_sleep(2000);

	finished = 0;
	do {
		tries++;

		vpb_sethook_sync(h1,VPB_OFFHOOK);
		printf("waiting for dial tone...\n");
		ret = ctwaitforevent(h1, timer1, VPB_TONEDETECT, VPB_DIAL, 5000);
		if (ret != -1) {
			printf("dial tone!\n");
			vpb_dial_sync(h1, argv[1]);
			printf("waiting for ring....\n");
			ret = ctwaitforevent(h2, timer2, VPB_RING, 0, 5000);
			if (ret == -1) {
				fails++;
			}
		}
		else {
			fails++;
		}
			
		printf("tries: %d fails: %d\n", tries, fails);
		vpb_sethook_sync(h1,VPB_ONHOOK);
		vpb_sleep(2000);
	} while(!kbhit());

	vpb_close(h1);
	vpb_close(h2);
	return 0;
}

int ctwaitforevent(int h,void *timer,int event_type,int data,int timeout_ms) {
  char      s[VPB_MAX_STR];
  int       ret, state;
  VPB_EVENT e;   

  vpb_timer_change_period(timer, timeout_ms);
  if (timeout_ms != 0)
    vpb_timer_start(timer);

  state = 1;
  while((state == 1) && !finish) {
    ret = vpb_get_event_ch_async(h, &e);

    if (ret == VPB_OK) {
      vpb_translate_event(&e, s); s[strlen(s)-1]=0;

      if ((e.type == event_type) && (e.data == data)) {
	state = 0;
      }
      if (e.type == VPB_TIMEREXP) {
	state = 2;
      }
    }
    else
      vpb_sleep(100);
  }
	  
  vpb_timer_stop(timer);	
  if (state == 0)
    return e.type;
  else
    return -1;
}

