/**
 * Name: reset.c
 * Desc: Shows how to perform a soft device reset
 *       on a T7 device
**/

#ifdef WIN32
	#include <winsock2.h>
	#include <ws2tcpip.h>
	#include <windows.h>
#else
	#include <unistd.h> // For sleep() (with Mac OS). Might need Sleep for Linux, and include windows.h for Win
	#include <arpa/inet.h>  // For inet_ntoa()
#endif
#include <stdio.h>
#include <stdlib.h>

#include <math.h>

#include "../LJM_Utilities.h"
#include "LabJackM.h"

int main()
{
	int err = 0;
	int errAddress = INITIAL_ERR_ADDRESS;
	int handle;
	const char * deviceType = "LJM_dtT7";
	const char * connectionType = "LJM_ctUSB";
	const char * identifier = "LJM_idANY";

	int msWait = 2000;

	// Set up the reset command
	int ResetNumFrames = 1;
	int aResetReadOrWrites[4] = {LJM_WRITE, LJM_WRITE, LJM_WRITE, LJM_WRITE};
	int aResetAddresses[1] = {61998};
	int aResetTypes[4] = {LJM_BYTE, LJM_BYTE, LJM_BYTE, LJM_BYTE};
	int aResetNumValues[1] = {4};
	double aResetValues[4] = {0x4C, 0x4A, 0x00, 0x05};

	// Set up an operation to be performed after the reset to make sure
	// device communication is working
	const char * NAME = {"SERIAL_NUMBER"};
	double value = 0;

	printf("Warning: This program is not fully functional.\n");
	WaitForUser();

	EnableLoggingLevel(LJM_TRACE);

	// Open a LabJack
	err = LJM_OpenS(deviceType, connectionType, identifier, &handle);
	ErrorCheck(err, "LJM_OpenS");

	// Get device info and print it out
	PrintDeviceInfoFromHandle(handle);
	printf("\n");

	// Perform the soft reset command
	printf("Performing a soft reset command..\n");

	err = LJM_eAddresses(handle, ResetNumFrames, aResetAddresses, aResetTypes,
		aResetReadOrWrites, aResetNumValues, aResetValues, &errAddress);
	ErrorCheckWithAddress(err, errAddress, "LJM_eAddresses (reset command)");

	printf("Please wait %d ms..\n", msWait);
	MillisecondSleep(msWait);
	printf("...Wait complete.\n\n");


	// err = LJM_Close(handle);
	// ErrorCheck(err, "first LJM_Close");
	// err = LJM_OpenS("LJM_dtT7", "LJM_ctANY", "LJM_idANY", &handle);
	// ErrorCheckWithAddress(err, errAddress, "LJM_OpenS");

	err = LJM_eReadName(handle, NAME, &value);
	ErrorCheck(err, "LJM_eReadName");

	// Print results
	printf("%s: %f\n", NAME, value);


	// Close
	err = LJM_Close(handle);
	ErrorCheck(err, "final LJM_Close");

	WaitForUserIfWindows();

	return LJME_NOERROR;
}
