/**
 *-----------------------------------------------------------------------------
 * Title      : superconducting low level RF EPICS interface
 * ----------------------------------------------------------------------------
 * File       : leepDrv.cpp
 * Author     : Garth Brown, gwbrown@slac.stanford.edu
 * Created    : June 17, 2016
 * Last update: September 6, 2016
 * ----------------------------------------------------------------------------
 * Description:
 * Prototype for FPGA register access to FPGAs using protocol defined in papers
 * given to SLAC by LBNL (Larry Doolittle). Uses asynPortDriver interface. Some of this
 * should eventually be autogenerated from json files or some such, and templates.
 *
 * ----------------------------------------------------------------------------
 * This file is part of LCLS II. It is subject to
 * the license terms in the LICENSE.txt file found in the top-level directory
 * of this distribution and at:
	* https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.
 * No part of LCLS II, including this file, may be
 * copied, modified, propagated, or distributed except according to the terms
 * contained in the LICENSE.txt file.
 * ----------------------------------------------------------------------------
**/

#include "leepDrv.h"
#include <asynOctetSyncIO.h>
#include <asynCommonSyncIO.h>
#include <epicsExit.h>
#include <limits>
#include <netinet/in.h>
#include <math.h>
#include <execinfo.h>
#include <iostream>
#include <stdio.h>
#include <stdexcept>

using namespace std;

// EPICS database driver strings
const char *leepDrv::RunStopString = "RUN_STOP"; /* asynInt32,    r/w */
const char *leepDrv::ReadOneRegString = "READ_ONE_REG"; /* asynInt32 array[2] w */
const char *leepDrv::WriteOneRegString = "WRITE_ONE_REG"; /* asynInt32 array[2] w */
const char *leepDrv::MaxParallelRequestsString = "MAX_PARALLEL_REQUESTS"; /* asynInt32,    r/w */
const char *leepDrv::PollPeriodString = "POLL_PERIOD"; /* asynInt32,    r/w */
const char *leepDrv::CommErrorCountString = "COMM_ERROR_COUNT";  /* asynInt32,    r */
const char *leepDrv::ConfigRomOctetString = "CONFIG_ROM_OCTET";
const char *leepDrv::JsonSha1DesString = "JSON_SHA1_DES";
const char *leepDrv::JsonSha1ActString = "JSON_SHA1_ACT";
// Git SHA1 sum as individual characters
const char *leepDrv::GitSha1ARString = "GIT_SHA1_A_R";
const char *leepDrv::GitSha1BRString = "GIT_SHA1_B_R";
const char *leepDrv::GitSha1CRString = "GIT_SHA1_C_R";
const char *leepDrv::GitSha1DRString = "GIT_SHA1_D_R";
const char *leepDrv::GitSha1ERString = "GIT_SHA1_E_R";
const char *leepDrv::GitSha1FRString = "GIT_SHA1_F_R";
const char *leepDrv::GitSha1GRString = "GIT_SHA1_G_R";
const char *leepDrv::GitSha1HRString = "GIT_SHA1_H_R";
const char *leepDrv::GitSha1IRString = "GIT_SHA1_I_R";
const char *leepDrv::GitSha1JRString = "GIT_SHA1_J_R";
const char *leepDrv::GitSha1KRString = "GIT_SHA1_K_R";
const char *leepDrv::GitSha1LRString = "GIT_SHA1_L_R";
const char *leepDrv::GitSha1MRString = "GIT_SHA1_M_R";
const char *leepDrv::GitSha1NRString = "GIT_SHA1_N_R";
const char *leepDrv::GitSha1ORString = "GIT_SHA1_O_R";
const char *leepDrv::GitSha1PRString = "GIT_SHA1_P_R";
const char *leepDrv::GitSha1QRString = "GIT_SHA1_Q_R";
const char *leepDrv::GitSha1RRString = "GIT_SHA1_R_R";
const char *leepDrv::GitSha1SRString = "GIT_SHA1_S_R";
const char *leepDrv::GitSha1TRString = "GIT_SHA1_T_R";
const char *leepDrv::GitSHA1String = "GIT_SHA1";  /* asynOctet,    r */
const char *leepDrv::FwDescString = "FW_DESC";  /* asynOctet,    r */
const unsigned int leepDrv::ConfigRomOctetAdr = 0x00000800;

DataBuffer::DataBuffer(unsigned int RegCount, unsigned int iStartAddr):
	RegCount(RegCount), ReqSegmentCount( (RegCount + maxRegPerMsg -1)/maxRegPerMsg),
		ReqMsgSize(RegCount + ReqSegmentCount), iStartAddr(iStartAddr)
{
	cout << "Making a waveform buffer with " << dec << RegCount << " points at " << iStartAddr;
	cout << hex << " ( 0x" << iStartAddr << " - 0x" << iStartAddr + RegCount << " )"<< endl;

	reqData.reserve(ReqMsgSize);
	fillWaveRequestMsg();
}

DataBuffer::~DataBuffer()
{ //Nothing to do here

}

void DataBuffer::publish(asynPortDriver *driver, int *paramIndex)
{ //Nothing to do here
	cout << "DataBuffer::publish not defined by a subclass" << endl;
	assert(0);
}

void DataBuffer8::publish(asynPortDriver *driver, int *paramIndex)
{
	driver->doCallbacksInt8Array(data.data(), RegCount, *paramIndex, 0);
}

void DataBuffer16::publish(asynPortDriver *driver, int *paramIndex)
{
	driver->doCallbacksInt16Array(data.data(), RegCount, *paramIndex, 0);
}

void DataBuffer32::publish(asynPortDriver *driver, int *paramIndex)
{
	driver->doCallbacksInt32Array(data.data(), RegCount, *paramIndex, 0);
}

void DataBuffer::fillWaveRequestMsg() /**< For requesting a waveform, fill canned message request with sequential addresses */
{
	unsigned int regAddr, msgOffset;
	size_t buffSize = ReqMsgSize;
	for(msgOffset=0, regAddr= iStartAddr; msgOffset < buffSize; regAddr++, msgOffset++)
	{
		if ( msgOffset % (maxRegPerMsg + nonceSize) == 0)
		{
			reqData[msgOffset] = {0,blankData};
			msgOffset++;
		}

		reqData[msgOffset].addr = regAddr | flagReadMask;
		reqData[msgOffset].data = blankData;
	}
	htonFpgaRegArray(reqData.data(), buffSize);
}

void leepDrvAtExit(void * driver)
{
	leepDrv *exitingDriver = (leepDrv*) driver;
	exitingDriver->shutdown();
}

/** Constructor for the leepDrv class.
 * Calls constructor for the asynPortDriver base class.
 * \param[in] drvPortName The name of the asyn port driver to be created.
 * \param[in] netPortName The name of the asyn port driver to use for the network connection
 * \param[in] maxAddr The number of channels for the paramater with the most channels
 * \paarm[in] paramTableSize The number of asyn params to be created for each device
 *
 * */
leepDrv::leepDrv(const char *drvPortName, const char *netPortName, int maxAddr, int paramTableSize)
: asynPortDriver(drvPortName,
		maxAddr, /* maxAddr */
		paramTableSize,
		asynInt32Mask | asynFloat64Mask | asynInt8ArrayMask | asynOctetMask | asynDrvUserMask | asynFloat32ArrayMask | asynInt32ArrayMask | asynInt16ArrayMask | asynUInt32DigitalMask, /* Interface mask */
		asynInt32Mask | asynFloat64Mask | asynInt8ArrayMask | asynOctetMask | asynEnumMask | asynFloat32ArrayMask | asynInt32ArrayMask | asynInt16ArrayMask | asynUInt32DigitalMask,  /* Interrupt mask */
		ASYN_CANBLOCK | ASYN_MULTIDEVICE, /* asynFlags.  This driver does block and it is multi-device, so flag is 1 */
		1, /* Autoconnect */
		epicsThreadPriorityMedium,
		0), /* Default stack size*/
		_singleMsgQ (maxMsgSize, maxMsgSize), isShuttingDown_(0), netSendCount_(0), lastResponseCount_ (0), netWaitingRequests_(0),
		newWaveAvailable_(0), newWaveRead_ (0), ConfigRomOctetBuf ( ConfigRomOctetCount, ConfigRomOctetAdr ), cfgRecordType (0), cfgRecordEnd (0), fwDescSize(0)
{
	asynStatus status = asynSuccess;

	/* Create the epicsMutex for locking access to communications counters from other threads */
	comCountersMutexId_ = epicsMutexCreate();
	if (!comCountersMutexId_) {
		printf("%s ERROR: epicsMutexCreate failure\n", __PRETTY_FUNCTION__);
		return;
	}
	epicsThreadSleep(defaultPollPeriod);

	createParam(ReadOneRegString, asynParamInt32Array, &p_ReadOneReg);
	createParam(WriteOneRegString, asynParamInt32Array, &p_WriteOneReg);
	createParam(RunStopString, asynParamInt32, &p_RunStop);
printf("%s created RunStop parameter\n", __PRETTY_FUNCTION__);
	createParam(MaxParallelRequestsString, asynParamInt32,
			&p_MaxParallelRequests);
	createParam(CommErrorCountString, asynParamInt32, &p_CommErrorCount);
	createParam(PollPeriodString, asynParamFloat64, &p_PollPeriod);

	createParam(ConfigRomOctetString, asynParamOctet, &p_ConfigRomOctet);
	createParam(JsonSha1DesString, asynParamOctet, &p_JsonSha1Des);
	createParam(JsonSha1ActString, asynParamOctet, &p_JsonSha1Act);
	createParam(FwDescString, asynParamOctet, &p_FwDesc);
	createParam(GitSHA1String, asynParamOctet, &p_GitSHA1);
	createParam(GitSha1ARString, asynParamInt32, &p_GitSha1AR);
	createParam(GitSha1BRString, asynParamInt32, &p_GitSha1BR);
	createParam(GitSha1CRString, asynParamInt32, &p_GitSha1CR);
	createParam(GitSha1DRString, asynParamInt32, &p_GitSha1DR);
	createParam(GitSha1ERString, asynParamInt32, &p_GitSha1ER);
	createParam(GitSha1FRString, asynParamInt32, &p_GitSha1FR);
	createParam(GitSha1GRString, asynParamInt32, &p_GitSha1GR);
	createParam(GitSha1HRString, asynParamInt32, &p_GitSha1HR);
	createParam(GitSha1IRString, asynParamInt32, &p_GitSha1IR);
	createParam(GitSha1JRString, asynParamInt32, &p_GitSha1JR);
	createParam(GitSha1KRString, asynParamInt32, &p_GitSha1KR);
	createParam(GitSha1LRString, asynParamInt32, &p_GitSha1LR);
	createParam(GitSha1MRString, asynParamInt32, &p_GitSha1MR);
	createParam(GitSha1NRString, asynParamInt32, &p_GitSha1NR);
	createParam(GitSha1ORString, asynParamInt32, &p_GitSha1OR);
	createParam(GitSha1PRString, asynParamInt32, &p_GitSha1PR);
	createParam(GitSha1QRString, asynParamInt32, &p_GitSha1QR);
	createParam(GitSha1RRString, asynParamInt32, &p_GitSha1RR);
	createParam(GitSha1SRString, asynParamInt32, &p_GitSha1SR);
	createParam(GitSha1TRString, asynParamInt32, &p_GitSha1TR);

	// Set these early, consider adding interlock for race condition with polling loop.
	setIntegerParam(p_RunStop, stop);
printf("%s set RunStop parameter to stop\n", __PRETTY_FUNCTION__);
	setIntegerParam(p_MaxParallelRequests, defaultMaxParallelRequests);
	setIntegerParam(p_CommErrorCount, 0);
	setDoubleParam(p_PollPeriod, defaultPollPeriod);

	pPolledRegMsg_ = new FpgaReg[1] { {flagReadMask,blankData}};
	PolledRegMsgSize_ = 1;

	epicsThreadSleep(defaultPollPeriod);

	printf("%s created %ld parameters.\n",__PRETTY_FUNCTION__,NUM_SCLLRF_PARAMS);

	status=pasynCommonSyncIO->connect(netPortName, 0, &pCommonAsynUser_, 0);
	if(status!=asynSuccess)
		printf( "%s: connect: failed to connect to port %s with status %d\n",
				__PRETTY_FUNCTION__,netPortName, status);
	else  printf( "%s: connect: %s asynUser \"Common\" connected to port %s\n",__PRETTY_FUNCTION__, drvPortName, netPortName);

	status=pasynOctetSyncIO->connect( netPortName,0,&pOctetAsynUser_,0);
	if(status!=asynSuccess)
		printf( "%s: connect: failed to connect to Read port %s with status %d\n",
				__PRETTY_FUNCTION__,netPortName, status);
	else  printf( "%s: connect: %s asynUser \"Octet\" connected to port %s\n",__PRETTY_FUNCTION__, drvPortName,netPortName);

	// The createParam calls are queued up rather than executed right away, so
	// give them a chance to be created before we start writing to them.
	// TODO: Is there a way to check that the params were finished being created?
	epicsThreadSleep(defaultPollPeriod);

	readEventId_ = epicsEventMustCreate(epicsEventEmpty);
	startResponseHandler(netPortName);

	epicsThreadSleep(defaultPollPeriod);

	startPoller(netPortName, defaultPollPeriod);

	singleMsgQueueEventId_ = epicsEventMustCreate(epicsEventEmpty);
	startSingleMessageQueuer(netPortName);
	printf("%s %s initialized and threads started.\n",__PRETTY_FUNCTION__, drvPortName);

	epicsAtExit(leepDrvAtExit, this);
}

void leepDrv::init()
{
	return;
}

void leepDrv::shutdown()
{
	isShuttingDown_ = true;
	wakeupPoller();
	wakeupReader();
}

leepDrv::~leepDrv()
{
	FpgaReg finalMsg = {0,blankData};
	htonFpgaRegArray(&finalMsg, sizeof(FpgaReg));
	_singleMsgQ.send(&finalMsg, sizeof(FpgaReg));
	pasynOctetSyncIO->disconnect(pOctetAsynUser_);
	pasynCommonSyncIO->disconnectDevice(pCommonAsynUser_);
	pasynCommonSyncIO->disconnect(pCommonAsynUser_);
	delete pPolledRegMsg_;
}

/** Called when you have the asyn parameter name and want the corresponding
 * register address.
  * \param[in] function From pAsynUser->reason, corresponding to a registered parameter.
  * \param[in] pToFpga Pointer to the {Address, Data} structure where the register address will be written
  * \param[in] nElements Number of elements to read. */
asynStatus leepDrv::functionToRegister(const int function,
		FpgaReg *pToFpga)
{
	// base class has no registers defined
	return asynError;
}

static void singleMessageQueuerC(void *drvPvt)
{
	printf("%s: starting\n", __PRETTY_FUNCTION__);
	leepDrv *pleepDriver = (leepDrv*)drvPvt;
	try
	{
		pleepDriver->singleMessageQueuer();
	}
	catch(std::exception e)
	{
		cout << "Unhandled exception in singleMessageQueuer, thread exiting" << endl;
		cout<< e.what() <<endl;
	}
	printf("%s: exiting\n", __PRETTY_FUNCTION__);
}

/** Starts the poller thread.
 ** Derived classes will typically call this at near the end of their constructor.
 ** Derived classes can typically use the base class implementation of the poller thread,
 ** but are free to re-implement it if necessary.
 ** \param[in] pollPeriod The time between polls. */
asynStatus leepDrv::startSingleMessageQueuer(const char *netPortName)
{
	std::string  strThreadName(netPortName);
	strThreadName += "singleMessageQueuer";
	epicsThreadCreate(strThreadName.c_str(),
			epicsThreadPriorityMedium,
			epicsThreadGetStackSize(epicsThreadStackMedium),
			(EPICSTHREADFUNC)singleMessageQueuerC, (void *)this);
	return asynSuccess;
}

// This will queue messages as the requests are received, and aggregate
// them into UDP packets. They will be sent out in the order queued.
//
// To send messages through the single message queuer, use _singleMsgQ.send(&message, messageSize)
// where:
// message is an FpgaReg or array of them
// messageSize is sizeof(message), the size in bytes not array elements.
void leepDrv::singleMessageQueuer()
{
	FpgaReg pMsgBuff[maxRegPerMsg + nonceSize]; // buffer big enough for one packet
	unsigned int sendBufByteCount;
	unsigned int sendBufRegCount;
	printf("\n%s \n", __PRETTY_FUNCTION__);

	// Main polling loop
	while (1)
	{

		std::fill( pMsgBuff, pMsgBuff + minRegPerMsg,
				(FpgaReg) {flagReadMask,blankData} );
		htonFpgaRegArray(pMsgBuff, minRegPerMsg + nonceSize);
		// pMsgBuff[0] is the nonce space
		sendBufByteCount = sizeof(FpgaReg);

		// Block and wait for incoming single register writes
		sendBufByteCount+=_singleMsgQ.receive(&pMsgBuff[1],sizeof(pMsgBuff));

		if(sendBufByteCount%sizeof(FpgaReg) != 0)
		{
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
					"%s %s: FOUND %d QUEUED BYTES, WHICH IS NOT A MULTIPLE OF FpgaReg SIZE!\n", portName, __PRETTY_FUNCTION__, sendBufByteCount);
			for(unsigned int i=0;i<=sendBufByteCount/sizeof(FpgaReg); i++)
			{
				cout << std::hex << pMsgBuff[i].addr << ": " << pMsgBuff[i].data << endl;
			}
		}

		if (isShuttingDown_)
		{
			printf("%s got shutdown flag.\n", __PRETTY_FUNCTION__);
			break;
		}
		if(sendBufByteCount < sizeof(FpgaReg))// receive returned -1
		{
			continue;
		}

		sendBufRegCount = sendBufByteCount/sizeof(FpgaReg);

		while(_singleMsgQ.pending()>0)
		{
			if(_singleMsgQ.pending() + sendBufByteCount < sizeof(pMsgBuff))
			{
				sendBufByteCount += _singleMsgQ.tryReceive(&pMsgBuff[sendBufRegCount],sizeof(pMsgBuff)-sendBufByteCount);
				sendBufRegCount = sendBufByteCount/sizeof(FpgaReg);
			}
			else
			{
				break;
			}
		}
		if(sendBufByteCount%sizeof(FpgaReg) != 0)
		{
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
					"%s %s: FOUND %d QUEUED BYTES, WHICH IS NOT A MULTIPLE OF FpgaReg SIZE!\n", portName, __PRETTY_FUNCTION__, sendBufByteCount);
			for(unsigned int i=0;i<=sendBufByteCount/sizeof(FpgaReg); i++)
			{
				cout << std::hex << pMsgBuff[i].addr << ": " << pMsgBuff[i].data << endl;
			}
		}

		asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,
				"%s %s: found %d queued bytes\n", portName, __PRETTY_FUNCTION__, sendBufRegCount);

		if(sendBufRegCount < minRegPerMsg)
		{
			sendBufRegCount = minRegPerMsg;
		}

		if (sendRegRequest(pMsgBuff, sendBufRegCount) != asynSuccess)
		{
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,"%s %s: stopping. %s\n", portName, __PRETTY_FUNCTION__,
					pOctetAsynUser_->errorMessage);
			if (isShuttingDown_)
			{
				printf("%s got shutdown flag.\n", __PRETTY_FUNCTION__);
				break;
			}
		}
		else
		{
			asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,
					"%s %s: done sending %u queued requests\n", portName, __PRETTY_FUNCTION__, sendBufRegCount);
		}
	}
	printf("%s: exiting\n", __PRETTY_FUNCTION__);
}

asynStatus leepDrv::writeUInt32Digital(asynUser *pasynUser, epicsUInt32 value, epicsUInt32 mask)
{
	asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "--> %s: value: %d, mask: %x\n", __PRETTY_FUNCTION__, value, mask);
	if (isShuttingDown_)
	{
		return asynSuccess;
	}
	int function = pasynUser->reason;
//	int addr = 0;
	asynStatus status = asynSuccess;
	const char *paramName;
	FpgaReg regSendBuf[minRegPerMsg]; // LBL reports problems when smaller requests are sent
	std::fill( regSendBuf, regSendBuf + sizeof( regSendBuf )/sizeof( *regSendBuf), (FpgaReg) {flagReadMask,blankData} );
	int chan;

	epicsTimeStamp timeStamp; getTimeStamp(&timeStamp);

	// Some registers have more than 1 "channel"
	getAddress(pasynUser, &chan);

	/* Set the parameter in the parameter library. */
	status = (asynStatus) setUIntDigitalParam(chan, function, value, mask);

	/* Fetch the parameter string name for possible use in debugging */
	getParamName(function, &paramName);
	asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "%s: function=%d, %s\n",
			__PRETTY_FUNCTION__, function, paramName);

	if (function == p_RunStop) {
		printf("%s %s setting RunStop for polling loop to %s\n", portName, __PRETTY_FUNCTION__, (value==run)?"RUN":"STOP");
		if (value == run)
			pollEvent_.signal();
	}
	else {
		// Convert function to address & FpgaReg.
		status = functionToRegister(function, &regSendBuf[0]);
		if (status == asynSuccess) // Yes, this function is a register write
		{
			asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
					"%s: found function=%d, name=%s, at chan %d + %d\n",
					__PRETTY_FUNCTION__, function, paramName, regSendBuf[0].addr, chan);
			regSendBuf[0].data = (uint32_t) value;
			regSendBuf[0].addr += (uint32_t) chan; // Add offset for multi-element short arrays/channels
			if(chan == 0)
			{
				regSendBuf[1].addr = (uint32_t) (regSendBuf[0].addr | flagReadMask); // Request readback value for the same register
			}
			htonFpgaRegArray(regSendBuf, sizeof( regSendBuf )/sizeof( *regSendBuf));

			if(chan== 0)
			{
				_singleMsgQ.send(&regSendBuf[0], 2*sizeof( FpgaReg ));
			}
			else
			{
				_singleMsgQ.send(&regSendBuf[0], sizeof( FpgaReg ));
			}
		}
		else
		{
			asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
				"%s: function=%d, name=%s not a register, skip network request\n",
				__PRETTY_FUNCTION__, function, paramName);
		}
	}

	/* Do callbacks so higher layers see any changes */
	status = (asynStatus) callParamCallbacks(chan, chan);

	if (status)
		epicsSnprintf(pasynUser->errorMessage, pasynUser->errorMessageSize,
				"%s: status=%d, function=%d, name=%s, value=%u",
				__PRETTY_FUNCTION__, status, function, paramName, value);
	else
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
			"<-- %s: function=%d, name=%s, value=%u\n",
			__PRETTY_FUNCTION__, function, paramName, value);
	return status;
}

/** Called when asyn clients call pasynInt32->write().
 * \param[in] pasynUser pasynUser structure that encodes the reason and address.
 * \param[in] value Pointer to the value to read. */
asynStatus leepDrv::writeInt32(asynUser *pasynUser, epicsInt32 value)
{
	if (isShuttingDown_)
	{
		return asynSuccess;
	}

	int function = pasynUser->reason;
//	int addr = 0;
	asynStatus status = asynSuccess;
	const char *paramName;
	FpgaReg regSendBuf[minRegPerMsg]; // LBL reports problems when smaller requests are sent
	std::fill( regSendBuf, regSendBuf + sizeof( regSendBuf )/sizeof( *regSendBuf), (FpgaReg)  {flagReadMask,blankData} );
	int chan;

	epicsTimeStamp timeStamp; getTimeStamp(&timeStamp);

	// Some registers have more than 1 "channel"
	getAddress(pasynUser, &chan);

	/* Fetch the parameter string name for possible use in debugging */
	getParamName(function, &paramName);
	asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "--> %s: function=%d, %s channel %d, value %d\n",
			__PRETTY_FUNCTION__, function, paramName, chan, value);

	if (function == p_RunStop) {
		printf("%s %s setting RunStop to %s\n", portName, __PRETTY_FUNCTION__, (value==run)?"RUN":"STOP");
		if (value == run)
			pollEvent_.signal(); // wake up the polling thread
	}
	else {
		// Convert function to address & FpgaReg.
		status = functionToRegister(function, &regSendBuf[0]);
		if (status == asynSuccess) // Yes, this function is a register write
		{
			asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
				"%s: found function=%d, name=%s, at addr %d + %d\n",
				__PRETTY_FUNCTION__, function, paramName, regSendBuf[0].addr, chan);
			regSendBuf[0].data = (int32_t) value;
			regSendBuf[0].addr += (uint32_t) chan; // Add offset for multi-element short arrays/channels
			// Writable arrays are not also readable.
			if(chan == 0) // If not a writable array, send along a readback request
			{
				regSendBuf[1].addr = (uint32_t) (regSendBuf[0].addr | flagReadMask); // Request readback value for the same register
			}
			htonFpgaRegArray(regSendBuf, sizeof( regSendBuf )/sizeof( *regSendBuf));

			if(chan== 0) // Probably not a writable array
			{
				_singleMsgQ.send(&regSendBuf[0], 2*sizeof( FpgaReg ));
			}
			else
			{
				_singleMsgQ.send(&regSendBuf[0], sizeof( FpgaReg ));
			}
		}
		else
		{
			asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
				"%s: function=%d, name=%s not a register, skip network request\n",
				__PRETTY_FUNCTION__, function, paramName);
		}
	}

	/* Set the parameter in the parameter library. */
	status = (asynStatus) setIntegerParam(chan, function, value);
	/* Do callbacks so higher layers see any changes */
	status = (asynStatus) callParamCallbacks(chan, chan);

	if (status)
		epicsSnprintf(pasynUser->errorMessage, pasynUser->errorMessageSize,
				"%s: status=%d, function=%d, name=%s, value=%d",
				__PRETTY_FUNCTION__, status, function, paramName, value);
	else
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
			"<-- %s: function=%d, name=%s, channel=%d, value=%d\n",
			__PRETTY_FUNCTION__, function, paramName, chan, value);
	return status;
}

/** Called when asyn clients call pasynInt32->read().
 * \param[in] pasynUser pasynUser structure that encodes the reason and address.
 * \param[in] value Pointer to the value to read. */
asynStatus leepDrv::readInt32(asynUser *pasynUser, epicsInt32 *value)
{
	if (isShuttingDown_)
	{
		return asynSuccess;
	}

	int function = pasynUser->reason;
//	int addr = 0;
	asynStatus status = asynSuccess;
	const char *paramName;
	FpgaReg regSendBuf[minRegPerMsg]; // LBL reports problems when smaller requests are sent
	std::fill( regSendBuf, regSendBuf + sizeof( regSendBuf )/sizeof( *regSendBuf), (FpgaReg)  {flagReadMask,blankData} );
	int address;

	epicsTimeStamp timeStamp; getTimeStamp(&timeStamp);

	// Some registers have more than 1 "channel"
	getAddress(pasynUser, &address);

	/* Fetch the parameter string name for possible use in debugging */
	getParamName(function, &paramName);
	asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "--> %s: function=%d, %s\n",
			__PRETTY_FUNCTION__, function, paramName);

	// Convert function to address & FpgaReg.
	status = functionToRegister(function, &regSendBuf[0]);
	if ((status == asynSuccess) && (regSendBuf[0].addr & flagReadMask)) // Yes, this function is a register write
	{
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
				"%s: found function=%d, name=%s, at address %d\n",
				__PRETTY_FUNCTION__, function, paramName, regSendBuf[1].addr);
		regSendBuf[0].data = (int32_t) *value;
		regSendBuf[0].addr += (uint32_t) address;
		htonFpgaRegArray(regSendBuf, sizeof( regSendBuf )/sizeof( *regSendBuf));
		_singleMsgQ.send(&regSendBuf[0], sizeof( FpgaReg ));
	}
	else
	{
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
				"%s: function=%d, name=%s not a register read address, skip network request\n",
				__PRETTY_FUNCTION__, function, paramName);
		status=asynPortDriver::readInt32(pasynUser, value);
	}
	return status;
}

asynStatus leepDrv::readInt8Array(asynUser *pasynUser, epicsInt8 *value,
								size_t nElements, size_t *nIn)
{
	if (isShuttingDown_)
	{
		return asynSuccess;
	}

	asynStatus status;
	epicsInt32 *value32 = new epicsInt32[nElements];
	int function = pasynUser->reason;
	const char *paramName;
	getParamName(function, &paramName);
	std::copy(value, value+nElements, value32);
	cout << "I'm probably doing this wrong, is it ever called? " << __PRETTY_FUNCTION__ << " " << paramName << endl;
	status = readInt32Array(pasynUser, value32, nElements, nIn);
	delete value32;
	return status;
}

asynStatus leepDrv::readInt16Array(asynUser *pasynUser, epicsInt16 *value,
								size_t nElements, size_t *nIn)
{
	if (isShuttingDown_)
	{
		return asynSuccess;
	}

	asynStatus status;
	epicsInt32 *value32 = new epicsInt32[nElements];
	int function = pasynUser->reason;
	const char *paramName;
	getParamName(function, &paramName);
	std::copy(value, value+nElements, value32);
	cout << "I'm probably doing this wrong, is it ever called? " << __PRETTY_FUNCTION__ << " " << paramName << endl;
	status = readInt32Array(pasynUser, value32, nElements, nIn);
	delete value32;
	return status;
}

/** Called when asyn clients call pasynInt32Array->write().
  * The base class implementation simply prints an error message.
  * Derived classes may reimplement this function if required.
  * \param[in] pasynUser pasynUser structure that encodes the reason and address.
  * \param[in] value Pointer to the array to write.
  * \param[in] nElements Number of elements to write. */
asynStatus leepDrv::readInt32Array(asynUser *pasynUser, epicsInt32 *value,
								size_t nElements, size_t *nIn)
{
	if (isShuttingDown_)
	{
		return asynSuccess;
	}

	int function = pasynUser->reason;
	asynStatus status = asynSuccess;
//	int nCopy;
	FpgaReg regSendBuf[maxMsgSize/sizeof(FpgaReg)];
	unsigned int i, uOutBuffIndex;
	uint32_t uRegAddr;
	const char *paramName;

	//getIntegerParam(P_ArrayLength, &nCopy);
	//if ((int) nElements < nCopy)
	//	nCopy = (int) nElements;

	/* Fetch the parameter string name for possible use in debugging */
	getParamName(function, &paramName);

	if(nElements < 2)
	{
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "%s: array with %d elements, function=%d, %s\n",
				__PRETTY_FUNCTION__, (int) nElements, function, paramName);
		return status;
	}
	else
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "--> %s: array with %d elements, function=%d, %s\n",
				__PRETTY_FUNCTION__, (int) nElements, function, paramName);

	if ( function == p_ReadOneReg )
	{
		uOutBuffIndex = 1; // index of first register past the nonce
		regSendBuf[1].addr = uReadOneRegAddr = value[0] | flagReadMask;
		regSendBuf[1].data = value[1];
	}
	else if ( function == p_WriteOneReg  )
	{
		uOutBuffIndex = 1; // index of first register past the nonce
		regSendBuf[1].addr = uWriteOneRegAddr = value[0];
		regSendBuf[1].data = value[1];
	}
	else
	{
		status = functionToRegister(function, &regSendBuf[1]);
		if (status != asynSuccess)
			return status;

		uRegAddr = regSendBuf[1].addr;
		uOutBuffIndex = 1; // index of first register past the nonce

		for(i=0; i<nElements; ++i, ++uOutBuffIndex)
		{
			regSendBuf[uOutBuffIndex].data = (int32_t) value[i];
			regSendBuf[uOutBuffIndex].addr = (uint32_t) (uRegAddr + i)|flagReadMask;

			// If there's more to send than will fit in the max message size, break
			// it up into chunks and send each chunk individually
			if(uOutBuffIndex == maxMsgSize/sizeof(FpgaReg)-1)
			{
				htonFpgaRegArray(regSendBuf, uOutBuffIndex+1);
				status = sendRegRequest(regSendBuf, uOutBuffIndex+1);

				if (status)
					epicsSnprintf(pasynUser->errorMessage, pasynUser->errorMessageSize,
							"%s %s: status=%d, function=%d, sending array segment %u of %s", portName, __PRETTY_FUNCTION__,
							status, function, i/uOutBuffIndex +1, paramName);
				else
					asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "%s: function=%d, sending array segment %u of %s\n",
							__PRETTY_FUNCTION__, function, i/uOutBuffIndex +1, paramName);
				uOutBuffIndex = 0; // loop will increment to index of first register past the nonce
			}
		}
	}

	htonFpgaRegArray(regSendBuf, uOutBuffIndex);
	status = sendRegRequest(regSendBuf, uOutBuffIndex);
	*nIn = nElements;
	if (status)
		epicsSnprintf(pasynUser->errorMessage, pasynUser->errorMessageSize,
				"%s %s: status=%d, function=%d, sent %s", portName, __PRETTY_FUNCTION__,
				status, function, paramName);
	else
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "<-- %s: function=%d, sent %s\n",
				__PRETTY_FUNCTION__, function, paramName);

	return status; //(writeArray < epicsInt32 > (pasynUser, value, nElements));
}

asynStatus leepDrv::writeInt8Array(asynUser *pasynUser, epicsInt8 *value,
								size_t nElements)
{
	asynStatus status;
	epicsInt32 *value32 = new epicsInt32[nElements];
	std::copy(value, value+nElements, value32);
	status = writeInt32Array(pasynUser, value32, nElements);
	delete value32;
	return status;
}

asynStatus leepDrv::writeInt16Array(asynUser *pasynUser, epicsInt16 *value,
								size_t nElements)
{
	asynStatus status;
	epicsInt32 *value32 = new epicsInt32[nElements];
	std::copy(value, value+nElements, value32);
	status = writeInt32Array(pasynUser, value32, nElements);
	delete value32;
	return status;
}

/** Called when asyn clients call pasynInt32Array->write().
  * The base class implementation simply prints an error message.
  * Derived classes may reimplement this function if required.
  * \param[in] pasynUser pasynUser structure that encodes the reason and address.
  * \param[in] value Pointer to the array to write.
  * \param[in] nElements Number of elements to write. */
asynStatus leepDrv::writeInt32Array(asynUser *pasynUser, epicsInt32 *value,
								size_t nElements)
{
	if (isShuttingDown_)
	{
		return asynSuccess;
	}

	int function = pasynUser->reason;
	asynStatus status = asynSuccess;
//	int nCopy;
	FpgaReg regSendBuf[maxMsgSize/sizeof(FpgaReg)];
	unsigned int i, uOutBuffIndex;
	uint32_t uRegAddr;
	const char *paramName;

	//getIntegerParam(P_ArrayLength, &nCopy);
	//if ((int) nElements < nCopy)
	//	nCopy = (int) nElements;

	/* Fetch the parameter string name for possible use in debugging */
	getParamName(function, &paramName);

	if(nElements < 2)
	{
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "%s: array with %d elements, function=%d, %s\n",
				__PRETTY_FUNCTION__, (int) nElements, function, paramName);
		return status;
	}
	else
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "--> %s: array with %d elements, function=%d, %s\n",
				__PRETTY_FUNCTION__, (int) nElements, function, paramName);

	if ( function == p_ReadOneReg )
	{
		uOutBuffIndex = 1; // index of first register past the nonce
		regSendBuf[1].addr = uReadOneRegAddr = value[0] | flagReadMask;
		regSendBuf[1].data = value[1];
	}
	else if ( function == p_WriteOneReg  )
	{
		uOutBuffIndex = 1; // index of first register past the nonce
		regSendBuf[1].addr = uWriteOneRegAddr = value[0];
		regSendBuf[1].data = value[1];
	}
	else
	{
		status = functionToRegister(function, &regSendBuf[1]);
		if (status != asynSuccess)
			return status;

		uRegAddr = addrMask & regSendBuf[1].addr;
		uOutBuffIndex = 1; // index of first register past the nonce

		for(i=0; i<nElements; ++i, ++uOutBuffIndex)
		{
			regSendBuf[uOutBuffIndex].data = (int32_t) value[i];
			regSendBuf[uOutBuffIndex].addr = (uint32_t) uRegAddr + i;

			// If there's more to send than will fit in the max message size, break
			// it up into chunks and send each chunk individually
			if(uOutBuffIndex == maxMsgSize/sizeof(FpgaReg)-1)
			{
				htonFpgaRegArray(regSendBuf, uOutBuffIndex+1);
				status = sendRegRequest(regSendBuf, uOutBuffIndex+1);

				if (status)
					epicsSnprintf(pasynUser->errorMessage, pasynUser->errorMessageSize,
							"%s %s: status=%d, function=%d, sending array segment %u of %s", portName, __PRETTY_FUNCTION__,
							status, function, i/uOutBuffIndex +1, paramName);
				else
					asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "%s: function=%d, sending array segment %u of %s\n",
							__PRETTY_FUNCTION__, function, i/uOutBuffIndex +1, paramName);
				uOutBuffIndex = 0; // loop will increment to index of first register past the nonce
			}
		}
	}

	htonFpgaRegArray(regSendBuf, uOutBuffIndex);
	status = sendRegRequest(regSendBuf, uOutBuffIndex);

	if (status)
		epicsSnprintf(pasynUser->errorMessage, pasynUser->errorMessageSize,
				"%s %s: status=%d, function=%d, sent %s", portName, __PRETTY_FUNCTION__,
				status, function, paramName);
	else
		asynPrint(pasynUser, ASYN_TRACEIO_DRIVER, "<-- %s: function=%d, sent %s\n",
				__PRETTY_FUNCTION__, function, paramName);

	return status; //(writeArray < epicsInt32 > (pasynUser, value, nElements));
}

typedef struct
{
	FpgaReg* sendBuff;
	size_t sendBuffSize;
	leepDrv* pDriver;
} regPollerThreadArgs;

static void regPollerC(void *drvPvt)
{
	leepDrv *pleepDriver = (leepDrv*)drvPvt;
	try
	{
		pleepDriver->regPoller();
	}
	catch(std::exception e)
	{
		cout << "Unhandled exception in regPoller, thread exiting" << endl;
		cout<< e.what() <<endl;
	}
	printf("%s: exiting\n", __PRETTY_FUNCTION__);
}

/** Starts the poller thread.
 ** Derived classes will typically call this at near the end of their constructor.
 ** Derived classes can typically use the base class implementation of the poller thread,
 ** but are free to re-implement it if necessary.
 ** \param[in] pollPeriod The time between polls. */
asynStatus leepDrv::startPoller(const char *netPortName, double pollPeriod)
{
	std::string  strThreadName(netPortName);
	strThreadName += "asynPoller";
	pollPeriod_ = pollPeriod;
	epicsThreadCreate(strThreadName.c_str(),
			epicsThreadPriorityMedium,
			epicsThreadGetStackSize(epicsThreadStackMedium),
			(EPICSTHREADFUNC)regPollerC, (void *)this);
	return asynSuccess;
}

void leepDrv::regPoller()
{
	bool status = (bool) epicsEventWaitOK;
	int runStop;
	unsigned int regBuffCount;
	FpgaReg *pTempRegMsg = pPolledRegMsg_;

	pollEvent_.wait(); // Block when first created, to give subclass constructors a chance to finish
	while(1) {
		getDoubleParam(p_PollPeriod, &pollPeriod_);
		getIntegerParam(p_RunStop, &runStop);
		if (runStop == run && pollPeriod_ != 0.0)
		{
			status = pollEvent_.wait( pollPeriod_);
		}
		else
		{
			pollEvent_.wait();
			status = (bool) epicsEventWaitOK;
		}

		if (isShuttingDown_) {
			break;
		}

		if (status == epicsEventWaitOK)
		{
			/* We got an event, rather than a timeout.  This is because other software
			 ** knows that we should do a poll.
			 **/
		}
		else
		{
			getIntegerParam(p_RunStop, &runStop);
			if (runStop == stop)
			{
				continue;
			}
		}

		pTempRegMsg = pPolledRegMsg_;
		regBuffCount = PolledRegMsgSize_;

		// The register polling message may be too big for a single request.
		// If so, it is expected to have an extra "nonce" element every
		// maxMsgSize/sizeof(FpgaReg)
		sendBigBuffer(pTempRegMsg, regBuffCount);

		asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,
				"%s: woke up and sent a poll\n", __PRETTY_FUNCTION__);
	}
}

/** Wakes up the poller thread to make it start polling. */
asynStatus leepDrv::wakeupPoller()
{
	pollEvent_.signal();
	return asynSuccess;
}


// The register request message may be too big for a single UDP packet.
// If so, it is expected to have an extra "nonce" element every
// maxMsgSize/sizeof(FpgaReg) and be send in one maxMsgSize segments.
// FpgaReg arrays sent to this function should have a blank inserted
// ahead of every maxRegPerMsg register messages.
asynStatus leepDrv::sendBigBuffer(FpgaReg *regBuffer, unsigned int regBuffCount)
{
	asynStatus status = asynSuccess;
	unsigned int regBuffRemainingCount = regBuffCount;

	while (regBuffRemainingCount > maxMsgSize/sizeof(FpgaReg))
	{
		status = sendRegRequest(regBuffer, maxMsgSize/sizeof(FpgaReg));
		if(status != asynSuccess)
		{
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,"%s %s: write failed with status %u\n", portName, __PRETTY_FUNCTION__,
					status);
			return status;
		}
		regBuffRemainingCount -= maxMsgSize/sizeof(FpgaReg);
		regBuffer = &regBuffer[maxMsgSize/sizeof(FpgaReg)];
	}

	status = sendRegRequest(regBuffer, regBuffRemainingCount);
	if(status != asynSuccess)
	{
		asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,"%s %s: write failed with status %u\n", portName, __PRETTY_FUNCTION__,
				status);
	}
	return status;
}


/** Polls the device
  * \param[in] regBuffer array of FpgaReg messages in network byte order.
  * Note that the first "register" regBuffer[0] is really the nonce, not data.
  * This function will set the nonce before sending.
  * Other than the nonce, data in the array is not changed. This reduces the
  * processing required, since most messages are canned and repeated at regular intervals.
  * \param[in] regBuffCount is the number of FpgaReg type elements, including the nonce
  **  */
asynStatus leepDrv::sendRegRequest(FpgaReg *regBuffer, unsigned int regBuffCount)
{
	if(regBuffer == NULL || regBuffCount < 5)
	{
		fprintf(stderr, "Problem with send request. regBuffCount = %d:\n", regBuffCount);
		epicsThreadSuspendSelf();
	}
	size_t writtenCount;
	epicsInt32 errorCount;
	asynStatus status = asynSuccess;
	char * pWriteBuffer;
	pWriteBuffer = reinterpret_cast<char*>(regBuffer);
	int maxParallelRequests;
	getIntegerParam(p_MaxParallelRequests, &maxParallelRequests);

	asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER, "--> %s( regBuffer=%p, regBuffCount=%u )\n",
			__PRETTY_FUNCTION__, regBuffer, regBuffCount);

	epicsMutexLock(comCountersMutexId_); // protect netSendCount and netWaitingRequests
	// Throttle so that we don't overflow buffers if response handling falls behind
	if( netWaitingRequests_ >= (unsigned) maxParallelRequests )
		asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,
				"%s: too many requests waiting for responses (%u), throttling requests.\n",__PRETTY_FUNCTION__, maxParallelRequests);

	while( netWaitingRequests_ >= (unsigned) maxParallelRequests )
	{
		// Go outside mutex if we need to exit or sleep
		epicsMutexUnlock(comCountersMutexId_);
		if (isShuttingDown_)
		{
			return asynDisconnected;
		}
		epicsThreadSleep(throttleLoopDelay);
		epicsMutexLock(comCountersMutexId_); // protect netSendCount and netWaitingRequests
	}

	++netSendCount_; // increment and roll over if needed

	// use the nonce at the start of the buffer for register count, and
	// send counter. Can be used for error checking.
	regBuffer[0] = (FpgaReg) { (uint32_t) htonl(netSendCount_), (int32_t) htonl(regBuffCount*sizeof(FpgaReg)) };
	status = pasynOctetSyncIO->write(pOctetAsynUser_, pWriteBuffer,
			regBuffCount*sizeof(FpgaReg), writeTimeout, &writtenCount);

	if (status != asynSuccess)
	{
		if (!isShuttingDown_)
		{
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,"%s %s: failed to write. %s\n", portName, __PRETTY_FUNCTION__,
					pOctetAsynUser_->errorMessage);
			getIntegerParam(p_CommErrorCount, &errorCount);
			setIntegerParam(p_CommErrorCount, errorCount + 1);
			callParamCallbacks();
		}
	}
	else
	{
		++netWaitingRequests_;
	}
	epicsMutexUnlock(comCountersMutexId_);
	wakeupReader();
	epicsThreadSleep(0); // to allow other threads to take the CPU

	asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER, "<-- %s( regBuffer=%p, regBuffCount=%u )\n",
			__PRETTY_FUNCTION__, regBuffer, regBuffCount);
	return status;
}


static void responseHandlerC(void *drvPvt)
{
	leepDrv *pleepDriver = (leepDrv*)drvPvt;
	try
	{
		pleepDriver->responseHandler();
	}
	catch(std::exception e)
	{
		cout << "Unhandled exception in responseHandler, thread exiting" << endl;
		cout<< e.what() <<endl;
	}
	printf("%s: exiting\n", __PRETTY_FUNCTION__);
}

/** Starts the poller thread.
 ** Derived classes will typically call this at near the end of their constructor.
 ** Derived classes can typically use the base class implementation of the poller thread,
 ** but are free to re-implement it if necessary.
 ** \param[in] pollPeriod The time between polls. */
asynStatus leepDrv::startResponseHandler(const char *netPortName)
{
	std::string  strThreadName(netPortName);
	strThreadName += "responseHandler";
	readTimeout_ = readTimeout;
	epicsThreadCreate(strThreadName.c_str(),
			epicsThreadPriorityMedium, epicsThreadGetStackSize(epicsThreadStackMedium),
			(EPICSTHREADFUNC) responseHandlerC, (void *) this);
	return asynSuccess;
}

/** Wakes up the reader thread to check for data. */
asynStatus leepDrv::wakeupReader()
{
	epicsEventSignal(readEventId_);
	return asynSuccess;
}

// Most of the main loop is network error handling, signaling, network details.
void leepDrv::responseHandler()
{
	epicsEventWaitStatus waitStatus;
	epicsMutexLockStatus mutexStatus;
	char pReadBuffer[maxMsgSize];
	FpgaReg *pRegReadback;
	size_t readCount = 0; // Number of bytes to process from the network read
	epicsInt32 errorCount;
	int eomReason;
	int noDataCounter = 0; // If we try to read this many times and get no data, give up and decrement netWaitingRequests_
	int maxParallelRequests;

	while (1)
	{
		getIntegerParam(p_MaxParallelRequests, &maxParallelRequests);

		// The asyn framework doesn't allow writes while a read is blocking,
		// so the same behavior is approximated here with events.
		//asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,
		//		"waiting for data... ");
		waitStatus = epicsEventWaitWithTimeout(readEventId_, readTimeout_);

		if (isShuttingDown_)
		{
			break;
		}
		if (waitStatus == epicsEventWaitOK) // We got an event, signaling to expect data back
		{
			while (netWaitingRequests_>0) // Writers increment atomic netWaitingRequests when they send a request
			{
				// Note: pRegReadback/pReadBuffer would have reentrancy problems, except only this one
				// thread reads it. More than one read thread and it could break.
				pRegReadback = reinterpret_cast<FpgaReg*>(pReadBuffer);
				pRegReadback[0] = (FpgaReg) {0, 0}; // Reset count, so we won't try to process data that isn't there.

				mutexStatus = epicsMutexLock(comCountersMutexId_); // protect netWaitingRequests from being modified by the write thread
				assert(mutexStatus != epicsMutexLockError);

				// First read just the nonce for a sanity check.
				pasynOctetSyncIO->read(pOctetAsynUser_, pReadBuffer,
						nonceSize*sizeof(FpgaReg), 0.05, &readCount, &eomReason);

				// Prevent an endless loop here while senders are throttled
				if(readCount == 0)
				{
					++noDataCounter;
					if(noDataCounter > (int)(defaultPollPeriod/throttleLoopDelay))
						netWaitingRequests_--;
					epicsMutexUnlock(comCountersMutexId_); // protect netWaitingRequests from being modified by the write thread
					continue;
				}
				else // Get the amount of data to read from the nonce presumably read in, and read that many more bytes
				{
					noDataCounter = 0;
					if(ntohl(pRegReadback[0].data) <= (int) maxMsgSize)
					{
						try
						{ // read in the number of bytes the nonce says to expect, starting with the second register location
							asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,"%s %s: read %u byte nonce, says sequence # %u with %d bytes.\n",
									portName, __PRETTY_FUNCTION__, (unsigned) readCount, ntohl(pRegReadback[0].addr), ntohl(pRegReadback[0].data));
							pasynOctetSyncIO->read(pOctetAsynUser_, &pReadBuffer[nonceSize*sizeof(FpgaReg)],
									ntohl(pRegReadback[0].data)-nonceSize*sizeof(FpgaReg), 0.05, &readCount, &eomReason);
							readCount += nonceSize*sizeof(FpgaReg);
							asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,"%s %s: got %u bytes total for response #%u\n",
									portName, __PRETTY_FUNCTION__, (unsigned) readCount, ntohl(pRegReadback[0].addr));
						}
						catch(std::exception e)
						{
							cout << "Unhandled exception in responseHandler trying to read data" << endl;
							cout<< e.what() <<endl;
						}
					}
					else
					{
						// Clear out any cruft left over that we didn't process.
						pasynOctetSyncIO->flush(pOctetAsynUser_);
						netWaitingRequests_--;
						asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
							"%s %s: presumed nonce says sequence # %u with %d bytes.\n",
							portName, __PRETTY_FUNCTION__, ntohl(pRegReadback[0].addr), ntohl(pRegReadback[0].data));
						epicsMutexUnlock(comCountersMutexId_); // protect netWaitingRequests from being modified by the write thread
						getIntegerParam(p_CommErrorCount, &errorCount);
						setIntegerParam(p_CommErrorCount, errorCount + 1);
						callParamCallbacks();
						continue;
					}

				}
				if (maxParallelRequests == 1) // Not sending out multiple requests at once
				{
					pasynOctetSyncIO->flush(pOctetAsynUser_); // so it's safe to clear any "junk bits" out of the buffer
				}
				epicsMutexUnlock(comCountersMutexId_); // protect netWaitingRequests from being modified by the write thread

				ntohFpgaRegArray(pRegReadback, (readCount)/sizeof(FpgaReg));

				processReadbackBuffer(pRegReadback, readCount);
				/* Do callbacks so higher layers see any changes */
				(asynStatus) callParamCallbacks();

				epicsThreadSleep(0); // sleep to be nice to other threads
			} // while (netWaitingRequests>0)
		} // if (status == epicsEventWaitOK)
		else // Timed out waiting for sender to signal. Could be a network glitch, so count request as lost.
		{
			if(netWaitingRequests_>0)
			{
				asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
						"%s %s: receive thread timed out after %fs waiting for %d responses. Network losses?\n", portName, __PRETTY_FUNCTION__, readTimeout_, netWaitingRequests_);
				netWaitingRequests_--;
			}
		}
	}
}

// Iterate over each register in the buffer returned from the FPGA
// Array passed to this function contains the nonce, with the buffer
// size at pRegReadback[0].data
asynStatus leepDrv::processReadbackBuffer(FpgaReg *pRegReadback, unsigned int readCount)
{
	unsigned i;
	asynStatus status = asynSuccess;
	int bytesLeft = readCount; // signed to make error detection easier
	epicsInt32 errorCount;

	// Check for an invalid nonce
	if(pRegReadback[0].addr < 1 || pRegReadback[0].data < 1)
		return asynError;

	// We put the message size in the data of the first buffer element for error checking
	// and to handle multiple messages received
	while(bytesLeft > 0)
	{

		if (isShuttingDown_)
		{
			break;
		}

		// We can read partial messages, so watch array bounds if received message size is smaller than expected
		if (bytesLeft < pRegReadback[0].data)
		{
			//pRegReadback[0].data = bytesLeft; // Testing made clear this isn't enough, so just bail.
			pasynOctetSyncIO->flush(pOctetAsynUser_); // Should we clear out waiting partial messages?
			if(netWaitingRequests_ > 0)
				netWaitingRequests_--;
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
					"%s %s: Read %u bytes from network, %d bytes left to process, but expected %u bytes\n",
					portName, __PRETTY_FUNCTION__, readCount, bytesLeft, (unsigned) pRegReadback[0].data);
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
					"%s %s: Response from request #%u, expected is request #%u\n",
					portName, __PRETTY_FUNCTION__, (unsigned) pRegReadback[0].addr,
					lastResponseCount_ + 1);
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
					"%s: Discarding this message\n",
					__PRETTY_FUNCTION__);
			getIntegerParam(p_CommErrorCount, &errorCount);
			setIntegerParam(p_CommErrorCount, errorCount + 1);
			return asynError;
		}

		if (pRegReadback[0].addr > lastResponseCount_ + 1)
		{
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
					"%s %s: Missing response message, got response from request #%u, expected is request #%u\n",
					portName, __PRETTY_FUNCTION__, (unsigned) pRegReadback[0].addr,
					lastResponseCount_ + 1);

			getIntegerParam(p_CommErrorCount, &errorCount);
			setIntegerParam(p_CommErrorCount, errorCount + 1);
		}
		if (pRegReadback[0].addr < lastResponseCount_ + 1)
		{// NOTE: In testing so far, it has only reached here from data problems other than true out-of-order data
			asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
					"%s %s: Out-of-order response message, got response from request #%u, expected is request #%u\n",
					portName, __PRETTY_FUNCTION__, (unsigned) pRegReadback[0].addr,
					lastResponseCount_ + 1);

			getIntegerParam(p_CommErrorCount, &errorCount);
			setIntegerParam(p_CommErrorCount, errorCount + 1);
		}
		lastResponseCount_ = pRegReadback[0].addr;

		// Data read from the network may contain multiple responses. Take them one at a time.
		// Use the register count from the nonce in pRegReadback[0].data to determine how much
		// to process before the next response with its own nonce.
		for (i = 1; i < pRegReadback[0].data / sizeof(FpgaReg); ++i)
		{
			if(pRegReadback[i].addr & flagReadMask)
			{
				status = processRegReadback(&pRegReadback[i]);
			}
			else
			{
				processRegWriteResponse(&pRegReadback[i]);
			}
			if (status)
				epicsSnprintf(pOctetAsynUser_->errorMessage,
						pOctetAsynUser_->errorMessageSize,
						"%s %s: status=%d, couldn't process address=0x%x, value=%u",
						portName, __PRETTY_FUNCTION__, status,
						(unsigned) pRegReadback[i].addr,
						(unsigned) pRegReadback[i].data);
			//		else
			//			asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,
			//					"%s %s: address=0x%x, value=%u\n", portName, __PRETTY_FUNCTION__,
			//					(unsigned ) pRegReadback[i].addr,
			//					(unsigned ) pRegReadback[i].data);
		}

		// check if this was a response to the most recent request
		if (pRegReadback[0].addr < netSendCount_ )
		{
			asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,
					"%s %s: processed response from request #%u, most recent is request #%u\n",
					portName, __PRETTY_FUNCTION__, (unsigned) pRegReadback[0].addr,
					netSendCount_);
			netWaitingRequests_ = netSendCount_ - pRegReadback[0].addr;
		}
		else
			netWaitingRequests_ = 0; // We have the most recent, no outstanding requests

		// decrement number of bytes left to process by the numbr of bytes we just processed
		if(bytesLeft > pRegReadback[0].data)
			bytesLeft -= pRegReadback[0].data;
		else // guard against mangled/partial messages
			bytesLeft = 0;

		// The nonce in pRegReadback[0] contains the message size. Move pointer to the next message.
		pRegReadback = & pRegReadback[pRegReadback[0].data/sizeof(FpgaReg)];
	} // while(bytesLeft > 0)

	return asynSuccess;
}

asynStatus leepDrv::catGitSHA1()
{
	int twoByte;
	int i;
	asynStatus status;
	char pGitSHA1[42];

	strGitSHA1.str("");
	strGitSHA1.clear();
	strGitSHA1 << setfill('0') << std::setw(4) << std::hex;
	cout << "Git SHA1: ";
	for (i=p_GitSha1AR; i<=p_GitSha1JR; i++)
	{
		status = (asynStatus) getIntegerParam(i, &twoByte);
		strGitSHA1 << twoByte;
	}
	strcpy(pGitSHA1, strGitSHA1.str().c_str());
	printf("%s", pGitSHA1);
	cout << endl;
	// when used with stringin reccord, it unfortunately can only handle 19 of the 20 characters
	status = setStringParam(p_GitSHA1, pGitSHA1);

	return status;
}

/**  Extract register address and data from the received message and set the appropriate
 * asyn parameter.
 * Some registers have a "new waveform data ready" flag. If they have this and it is set,
 * set weveIsReady to true.
 * Note: This function should not set waveIsReady to false. That is done by a loop in the
 * calling function.
* \param[in] pFromFpga Data returned from the FPGA for a single register
*/
asynStatus leepDrv::processRegReadback(const FpgaReg *pFromFpga)
{
	epicsInt32 errorCount;
	epicsInt32 iReg[2];
	asynStatus status = asynSuccess;
	char pSha[42];

	/* Map address to parameter, set the parameter in the parameter library. */
	switch (pFromFpga->addr)
	{
	case JsonSha1RAdr|flagReadMask:

	strJsonSha1.str("");
	strJsonSha1.clear();
	strJsonSha1 << setfill('0') << std::setw(4) << std::hex;
		for(unsigned int i = 0;
				(pFromFpga[i].addr - flagReadMask) < (GitSha1ARAdr - 1) &&
						(pFromFpga[i].addr - flagReadMask) >= JsonSha1RAdr; i++)
		{
			strJsonSha1 << setfill('0') << std::setw(4) << std::hex << (unsigned int) (pFromFpga[i].data & JsonSha1Mask);
		}
		strcpy(pSha, strJsonSha1.str().c_str());
		status = (asynStatus) setStringParam(p_JsonSha1Act, pSha);
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for JsonSha1 sum: %s\n", __PRETTY_FUNCTION__,
				strJsonSha1.str().c_str());
	break;

	case GitSha1ARAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1AR,
				(pFromFpga->data & GitSha1AMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1ARString,
				(unsigned int) (pFromFpga->data & GitSha1AMask));
	break;

	case GitSha1BRAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1BR,
				(pFromFpga->data & GitSha1BMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1BRString,
				(unsigned int) (pFromFpga->data & GitSha1BMask));
	break;

	case GitSha1CRAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1CR,
				(pFromFpga->data & GitSha1CMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1CRString,
				(unsigned int) (pFromFpga->data & GitSha1CMask));
	break;

	case GitSha1DRAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1DR,
				(pFromFpga->data & GitSha1DMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1DRString,
				(unsigned int) (pFromFpga->data & GitSha1DMask));
	break;

	case GitSha1ERAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1ER,
				(pFromFpga->data & GitSha1EMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1ERString,
				(unsigned int) (pFromFpga->data & GitSha1EMask));
	break;

	case GitSha1FRAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1FR,
				(pFromFpga->data & GitSha1FMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1FRString,
				(unsigned int) (pFromFpga->data & GitSha1FMask));
	break;

	case GitSha1GRAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1GR,
				(pFromFpga->data & GitSha1GMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1GRString,
				(unsigned int) (pFromFpga->data & GitSha1GMask));
	break;

	case GitSha1HRAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1HR,
				(pFromFpga->data & GitSha1HMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1HRString,
				(unsigned int) (pFromFpga->data & GitSha1HMask));
	break;

	case GitSha1IRAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1IR,
				(pFromFpga->data & GitSha1IMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1IRString,
				(unsigned int) (pFromFpga->data & GitSha1IMask));
	break;

	case GitSha1JRAdr|flagReadMask:

		status = (asynStatus) setIntegerParam(p_GitSha1JR,
				(pFromFpga->data & GitSha1JMask) );
		asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s: readback for address=%s, value=0x%x\n", __PRETTY_FUNCTION__,
				GitSha1JRString,
				(unsigned int) (pFromFpga->data & GitSha1JMask));
		catGitSHA1();
	break;

	default:
		if ((pFromFpga->addr >= (ConfigRomOctetBuf.iStartAddr|flagReadMask)) &&
				(pFromFpga->addr < ((ConfigRomOctetBuf.iStartAddr|flagReadMask) + ConfigRomOctetBuf.RegCount)))
		{
			unsigned int index = (pFromFpga->addr - (ConfigRomOctetBuf.iStartAddr|flagReadMask));
			ConfigRomOctetBuf.data[index*2] = (pFromFpga->data & 0xFF);
			ConfigRomOctetBuf.data[index*2+1] = (pFromFpga->data >>8 & 0xFF);
			if (index >= cfgRecordEnd)
			{
				if(cfgRecordType == 1) // if this is the firmware description string we just finished reading
				{
					//doCallbacksInt8Array( (char*) &ConfigRomOctetBuf.data[index - fwDescSize], fwDescSize, p_FwDesc, 0);
					setStringParam(p_FwDesc, (char*) &ConfigRomOctetBuf.data[index - fwDescSize]);
					fwDescSize = 0;
				}
				cfgRecordType = (pFromFpga->data >>14 & 0x3);
				cfgRecordEnd += (pFromFpga->data & 0x3FFF);

				if(cfgRecordType == 1) // if this is the firmware description string we are about to read
				{
					fwDescSize = (pFromFpga->data & 0x3FFF);
				}
			}
			asynPrint(pOctetAsynUser_, ASYN_TRACEIO_DRIVER,
				"%s %s: readback for address=%s, channel %u, value=0x%x\n", portName, __PRETTY_FUNCTION__,
				"ConfigRomOctet",index,
				(unsigned int) (pFromFpga->data & 0xFFFF));
			if(index == ConfigRomOctetBuf.RegCount - 1)
			{
				//doCallbacksInt8Array( ConfigRomOctetBuf.data.data(), ConfigRomOctetBuf.RegCount, p_ConfigRomOctet, 0);
				setStringParam(p_ConfigRomOctet, ConfigRomOctetBuf.data.data());
				cfgRecordEnd = 0;
				cfgRecordType = 0;
			}
		}
		else
		{
			asynPrint(pOctetAsynUser_, ASYN_TRACE_ERROR,
					"%s %s: value read from unmapped address 0x%X, value=0x%X\n", portName, __PRETTY_FUNCTION__,
					pFromFpga->addr, (unsigned ) pFromFpga->data);
			getIntegerParam(p_CommErrorCount, &errorCount);
			setIntegerParam(p_CommErrorCount, ++errorCount);
			status = asynError;
		}
	}

	// Base class only has a generic register. Decode if appropriate
	if(pFromFpga->addr == (uReadOneRegAddr|flagReadMask))
	{
		iReg[0] = pFromFpga->addr;
		iReg[1] = pFromFpga->data;
		doCallbacksInt32Array(iReg, 2, p_ReadOneReg, 0);
		asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,
				"%s: got one reg read response.\n", __PRETTY_FUNCTION__);
		return asynSuccess;
	}

	return status;
}

/**  Extract register address and data from the received message and set the appropriate
 * asyn parameter.
 * Some registers have a "new waveform data ready" flag. If they have this and it is set,
 * set weveIsReady to true.
 * Note: This function should not set waveIsReady to false. That is done by a loop in the
 * calling function.
* \param[in] pFromFpga Data returned from the FPGA for a single register
* \param[in] waveIsReady A flag that gets set to true if the appropriate bit was set by the FPGA
*/
asynStatus leepDrv::processRegWriteResponse(const FpgaReg *pFromFpga)
{
	epicsInt32 errorCount;
	epicsInt32 iReg[2];

	// Base class only has a generic register. Decode if appropriate
	if(pFromFpga->addr == (uWriteOneRegAddr))
	{
		iReg[0] = pFromFpga->addr;
		iReg[1] = pFromFpga->data;
		doCallbacksInt32Array(iReg, 2, p_WriteOneReg, 0);
		asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER,
				"%s: got one reg write response.\n", __PRETTY_FUNCTION__);
		return asynSuccess;
	}

	asynPrint(pOctetAsynUser_, ASYN_TRACE_ERROR,
		"%s %s: write response from FPGA for unmapped address 0x%X, value=0x%X\n", portName, __PRETTY_FUNCTION__,
		pFromFpga->addr, (unsigned ) pFromFpga->data);
	getIntegerParam(p_CommErrorCount, &errorCount);
	setIntegerParam(p_CommErrorCount, ++errorCount);
	return asynError;
}

void htonFpgaRegArray(FpgaReg *buffer, unsigned int regCount)
{
	unsigned int i;

	for (i=0; i<regCount; ++i)
	{
		buffer[i].addr = htonl(buffer[i].addr);
		buffer[i].data = htonl(buffer[i].data);
	}
}


void ntohFpgaRegArray(FpgaReg *buffer, unsigned int regCount)
{
	unsigned int i;

	for (i=0; i<regCount; ++i)
	{
		buffer[i].addr = ntohl(buffer[i].addr);
		buffer[i].data = ntohl(buffer[i].data);
	}
}


// snagged from https://graphics.stanford.edu/~seander/bithacks.html#Interleave64bitOps
unsigned short InterleaveEnableBits(unsigned char i, unsigned char q)
{
	return (((i * 0x0101010101010101ULL & 0x8040201008040201ULL) *
	0x0102040810204081ULL >> 49) & 0x5555) |
	(((q * 0x0101010101010101ULL & 0x8040201008040201ULL) *
	0x0102040810204081ULL >> 48) & 0xAAAA);
}

// I and Q in the *keep registers alternate bits indicating active I or Q.
// This function removes every other bit, so you can get only I or only Q.
// Pinched from https://stackoverflow.com/questions/4909263/how-to-efficiently-de-interleave-bits-inverse-morton
uint32_t DeInterleaveBits(uint32_t x)
{
	x = x & 0x55555555;
	x = (x | (x >> 1)) & 0x33333333;
	x = (x | (x >> 2)) & 0x0F0F0F0F;
	x = (x | (x >> 4)) & 0x00FF00FF;
	x = (x | (x >> 8)) & 0x0000FFFF;
	return x;
}

extern "C" {

/* Configuration routine.  Called directly, or from the iocsh function below */

/** EPICS iocsh callable function to call constructor for the leepDrv class.
 * \param[in] portName The name of the asyn port driver to be created.
 * \param[in] netPortName The name of the asynIPport this will use to communicate */
int leepDrvConfigure(const char *drvPortName, const char *netPortName)
{
	new leepDrv(drvPortName, netPortName, 0, 7);
	return asynSuccess;
}


/* EPICS iocsh shell commands */

static const iocshArg initArg0 = { "drvPortName",iocshArgString};
static const iocshArg initArg1 = { "IP port name",iocshArgString};
static const iocshArg * const initArgs[] = {&initArg0,
		&initArg1};
static const iocshFuncDef initFuncDef = {"leepDrvConfigure",2,initArgs};
static void initCallFunc(const iocshArgBuf *args)
{
	leepDrvConfigure(args[0].sval, args[1].sval);
}

void leepDrvRegister(void)
{
	iocshRegister(&initFuncDef,initCallFunc);
}

epicsExportRegistrar(leepDrvRegister);

}

