// ioctl (fd, TIOCCBRK, 0);
//#include <sys/types.h>
//#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
//#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <sched.h>
#include <math.h>
  
	      

//#include <signal.h>
//#include <syslog.h>
//#include <string.h>
//http://www.easysw.com/~mike/serial/serial.html#2_2_1
/*
#define TIOCM_LE        0x001                                                   
#define TIOCM_DTR       0x002                                                   
#define TIOCM_RTS       0x004                                                   
#define TIOCM_ST        0x008                                                   
#define TIOCM_SR        0x010                                                   
#define TIOCM_CTS       0x020                                                   
#define TIOCM_CAR       0x040                                                   
#define TIOCM_RNG       0x080                                                   
#define TIOCM_DSR       0x100                                                   
#define TIOCM_CD        TIOCM_CAR                                               
#define TIOCM_RI        TIOCM_RNG                                               
#define TIOCM_OUT1      0x2000                                                  
#define TIOCM_OUT2      0x4000                                                  
#define TIOCM_LOOP      0x8000              
*/

int main(void) {

int fd;
int dtr_bit = TIOCM_DTR;
int dtr_bit_0 = 0;
int flags;
long delta;
struct timeval timex,timey;    
struct sched_param p;

// | O_NDELAY
/*Open monitor device. */
  if ((fd = open("/dev/ttyS1", O_RDWR)) < 0) {
        
  if ((fd = open("/dev/tts/1", O_RDWR)) < 0) {
        exit(1);
  }

  }


  /* Line is opened, so DTR is high. Force it anyway to be sure. */

//  ioctl(fd, TIOCMGET, &flags);
//  printf("ZACATEK: %x\n",flags);
//getchar();  
  
//  ioctl(fd, TIOCMBIS, &dtr_bit_0);
//  sleep(1);
  
//printf("DTR 0 %x\n",flags);
//getchar();  
  
sched_getparam(0,&p);

p.sched_priority = 50;
sched_setscheduler(0, SCHED_RR, &p);

while (1) {

ioctl(fd, TIOCMSET, &dtr_bit_0);
sleep(6);  
  
//  ioctl(fd, TIOCMGET, &flags);
//  printf("Discharge...\n");
       
  ioctl(fd, TIOCMSET, &dtr_bit);
  gettimeofday(&timex,NULL);
  flags =0;


    while (!(flags&TIOCM_DSR)) {
    ioctl(fd, TIOCMGET, &flags);
//    printf("*");
    }
//    printf("\n");

//read(fd,&flags,1);
  gettimeofday(&timey,NULL);

  //ioctl(fd, TIOCMGET, &flags);
  
  delta= ((timey.tv_sec-timex.tv_sec)*1000)+(timey.tv_usec-timex.tv_usec);
  
  
  printf("DELTA: %lu \n",delta);
  printf("TEPLOTA: %f \n", (200-(1000/log(delta))));
  
//  sleep(1);
  }
}

  
