// walk.cpp : sapien go forward

#include "stdafx.h"

#include <windows.h>

static double unit;

void sapien_send(HANDLE f, int b)
{
  LARGE_INTEGER c1, c2;
  int x = 128;

  QueryPerformanceCounter(&c1);
  EscapeCommFunction(f, SETBREAK);
  do { QueryPerformanceCounter(&c2); } while (c2.QuadPart - c1.QuadPart < (long long)(8.0 * unit));

  while (x)
  {
    double u;
	if (b & x) u = 4.0 * unit;
	else u = unit;

    QueryPerformanceCounter(&c1);
	EscapeCommFunction(f, CLRBREAK);
    do { QueryPerformanceCounter(&c2); } while (c2.QuadPart - c1.QuadPart < (long long)u);

	EscapeCommFunction(f, SETBREAK);
    do { QueryPerformanceCounter(&c1); } while (c1.QuadPart - c2.QuadPart < (long long)unit);

	x >>= 1;
  }
  EscapeCommFunction(f, CLRBREAK);
}


int _tmain(int argc, _TCHAR* argv[])
{
  LARGE_INTEGER freq;
  if (!QueryPerformanceFrequency(&freq))
  {
	  printf("high resolution timer not supported. giving up.\n");
	  return 1;
  }
  unit = (double)(freq.QuadPart) / 1200.0;
  printf("unit:%ld:%u\n", freq.HighPart, freq.LowPart);

  HANDLE FHandle = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  DWORD written;
  char *buf = "\0x00";
  printf("wakeup tower...\n");
  WriteFile(FHandle, buf, 1, &written, 0);
  Sleep(1000);
  if (FHandle==INVALID_HANDLE_VALUE)
  {
	  printf("error opening port\n");
	  return 0;
  }

  sapien_send(FHandle, 0x86);

  return 0;
}

