#pragma once
#include "GlobalDefs.h"
#include "Status.h"
#include "SysThread.h"
#include "SysPerfTimer.h"
#include "defines.h"
#include "SysSemaphore.h"

class TimeSync
{
public:
	enum
	{
		TIME_STR_SIZE				= 128,
		ZDA_MESSAGE_SIZE			= 38,
	};

	TimeSync( Status *pStatus );
	~TimeSync();

	bool Initialize( char *commPort, char *strIP1, int UDPport1, char *strIP2, int UDPport2 );
	bool InitSerial( char *commPort );
	bool InitUDPSocket1();
	bool InitUDPSocket2();
	bool InitDAQCounters();
	bool DAQmxErrChk( int error );
	void EnumerateSerialPorts(CUIntArray& ports);

	bool ReadChar( char *character );
	bool ReadString( char *cmd, int maxBytesToRead, DWORD *bytesRead );
	int  ReadDataWaiting();
	bool SendTimeZDA_UDP( char *bufZDAmsg );
	int Checksum(const char *s);

	void GetZDAStr( char *str ) 
	{
		m_semTimeStr.Lock();
		sprintf_s( str, 128, m_chTimeMessage );
		m_semTimeStr.Unlock();
	}

private:
	void			Thread();
	void			ThreadSim();
	static void ThreadEntry( void *pStatusObj );

	SysThread				m_thread;
	Status					*m_pStatus;
	HANDLE					m_hCom;
	SysPerfTimer			m_SerialTimer;

	bool						m_bInitialized1;
	bool						m_bInitialSync;
	char						m_chTimeMessage[128];
	bool						m_bInitialized2;

	SOCKET					m_UPSSocket1;
	int						m_UDPport1;
	struct sockaddr_in	m_sockaddr1;
	char						m_strIP1[ 128 ];

	SOCKET					m_UPSSocket2;
	int						m_UDPport2;
	struct sockaddr_in	m_sockaddr2;
	char						m_strIP2[ 128 ];

	bool						m_bSimSerial;
	SysSemaphore			m_semTimeStr;

};

