#include <stdio.h>
#include <stdbool.h>
#include <process.h>
#include <conio.h>
#include "dxlib2.h"

#define ADDRESS_GOAL_POSITION     30
#define ADDRESS_PRESENT_POSITION  36

HANDLE     g_hThread = INVALID_HANDLE_VALUE;
BOOL       g_TermThread = FALSE;
DXDEVICEID  dev;

#define TIMEOUT   50
#define ID        1

// 位置取得
BOOL DxGetPosition (DXDEVICEID dvid, UCHAR id, SHORT *pos, int timeout, TDxErrorCode *err) {
  return DX_ReadWordData (dvid, id, ADDRESS_PRESENT_POSITION, (USHORT *)pos, timeout, err);
}

// 位置指令
BOOL DxSetPosition (DXDEVICEID dvid, UCHAR id, SHORT pos, int timeout, TDxErrorCode *err) {
  return DX_WriteWordData (dvid, id, ADDRESS_GOAL_POSITION, (USHORT)pos, timeout, err);
}


unsigned __stdcall testThread (void *dummy) {
  TDxErrorCode err;
  short p;

  while (!g_TermThread) {
    // 現在位置の読み取り
    DxGetPosition (dev, ID, &p, TIMEOUT, &err) ? printf ("\rGETPOS=[%4d]", p) : printf ("\rGETPOS Fail=[%d]", err);
  }

  _endthreadex (0);
  return 0;
}

void main (void) {
  TDxErrorCode  err;
  int f = 1;
  int pos = 0;
  unsigned threadID;

  if ((dev = DX_OpenPort ("\\\\.\\COM11", 57143))) {
    if (DX_Active (dev)) {
      // 指定IDのデバイスがあるかどうか確認
      if (DX_Ping (dev, ID, TIMEOUT, &err)) {
        // 読み出し専用スレッド作成
        if ((g_hThread = (HANDLE)_beginthreadex (NULL, 0, &testThread, NULL, 0, &threadID)) == INVALID_HANDLE_VALUE) {
          printf ("Beginthread Error\n");
        } else {
          while (1) {
            pos += f;
            if (pos > 1023) { pos = 1023; f = -1; }
            else if (pos < 0) { pos = 0; f = 1; }
            if (!DxSetPosition (dev, ID, pos, TIMEOUT, &err)) printf ("\nSetPos Fail[%d]\n", err);
            // 5ミリ秒待ち
            Sleep (5);
            // 何かキーを押すとループを抜ける
            if (kbhit ()) break;
          }
          // スレッド終了
          g_TermThread = TRUE;
          WaitForSingleObject (g_hThread, 2000);
        }
      } else
        printf("Cannot find ID=%d\n", ID);
    }
    DX_ClosePort(dev);
  } else {
    printf("Open error\n");
  }

  printf( "\nFin");
  getchar();
}
