/*
 * Remote Laboratory Logic Analyzer Part
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * (c) 2014 Timothy Pearson
 * Raptor Engineering
 * http://www.raptorengineeringinc.com
 */

#include "define.h"
#include "part.h"

#include <tdeaboutdata.h>   //::createAboutData()
#include <tdeaction.h>
#include <tdelocale.h>
#include <tdemessagebox.h>  //::start()
#include <tdefiledialog.h>
#include <tdeparts/genericfactory.h>
#include <kstatusbar.h>
#include <kstdaction.h>
#include <tqfile.h>        //encodeName()
#include <tqtimer.h>
#include <tqvbox.h>
#include <tqsocket.h>
#include <tqmutex.h>
#include <tqgroupbox.h>
#include <tqlayout.h>
#include <tqcombobox.h>
#include <tqcheckbox.h>
#include <tqpushbutton.h>
#include <tqeventloop.h>
#include <tqapplication.h>
#include <unistd.h>       //access()
#include <stdint.h>
#include <cmath>

#include "tracewidget.h"
#include "floatspinbox.h"
#include "layout.h"

#define NETWORK_COMM_TIMEOUT_MS 15000

/* exception handling */
struct exit_exception {
	int c;
	exit_exception(int c):c(c) { }
};

enum connectionStates {
	LogicAnalyzerState_InitialRequest			= 0,
	LogicAnalyzerState_ResetRequest				= 2,
	LogicAnalyzerState_HorizontalDivCountRequest		= 4,
	LogicAnalyzerState_ChannelCountRequest			= 8,
	LogicAnalyzerState_ChannelNameRequest			= 10,
	LogicAnalyzerState_ChannelActiveStateRequest		= 12,
	LogicAnalyzerState_TraceSampleCountRequest		= 14,
	LogicAnalyzerState_TraceSecondsDivRequest		= 16,
	LogicAnalyzerState_RunningRequest			= 18,
	LogicAnalyzerState_TraceRequest				= 50,
	LogicAnalyzerState_ChannelActiveStateUpdate		= 100,
	LogicAnalyzerState_TraceVoltsDivUpdate			= 102,
	LogicAnalyzerState_RunningUpdate			= 106,
	LogicAnalyzerState_ExternalCommandRequest		= 255
};

namespace RemoteLab {

typedef KParts::GenericFactory<RemoteLab::LogicAnalyzerPart> Factory;
#define CLIENT_LIBRARY "libremotelab_logicanalyzer"
K_EXPORT_COMPONENT_FACTORY( libremotelab_logicanalyzer, RemoteLab::Factory )

LogicAnalyzerPart::LogicAnalyzerPart( TQWidget *parentWidget, const char *widgetName, TQObject *parent, const char *name, const TQStringList& )
	: RemoteInstrumentPart( parent, name ), m_traceWidget(0), m_commHandlerState(-1), m_commHandlerMode(0), m_commHandlerCommandState(0), m_connectionActiveAndValid(false),
	m_base(0), stopTraceUpdate(false)
{
	// Initialize important base class variables
	m_clientLibraryName = CLIENT_LIBRARY;

	// Initialize mutex
	m_instrumentMutex = new TQMutex(false);

	// Initialize kpart
	setInstance(Factory::instance());
	setWidget(new TQVBox(parentWidget, widgetName));

	// Create timers
	m_forcedUpdateTimer = new TQTimer(this);
	connect(m_forcedUpdateTimer, SIGNAL(timeout()), this, SLOT(mainEventLoop()));
	m_updateTimeoutTimer = new TQTimer(this);
	connect(m_updateTimeoutTimer, SIGNAL(timeout()), this, SLOT(mainEventLoop()));

	// Initialize data
	m_hdivs = 0;
	m_vdivs = 0;
	for (int traceno=0; traceno<=MAXTRACES; traceno++) {
		m_samplesInTrace[traceno] = 0;
		m_channelActive[traceno] = false;
		m_channelName[traceno] = TQString("Channel %1").arg(traceno);
		m_voltsDiv[traceno] = 0;
		m_secsDiv[traceno] = 0;

		m_voltsDivSet[traceno] = false;
		m_channelActiveSet[traceno] = false;
	}
	m_runningSet = false;

	// Create widgets
	m_base = new LogicAnalyzerBase(widget());
	m_traceControlWidgetGrid = new TQGridLayout(m_base->traceControlLayoutWidget);
	m_traceWidget = m_base->traceScrollWidget->traceWidget();
	m_base->traceScrollWidget->setSizePolicy(TQSizePolicy(TQSizePolicy::MinimumExpanding, TQSizePolicy::MinimumExpanding));
	m_base->traceScrollWidget->setResizePolicy(TQScrollView::AutoOneFit);
	m_base->traceScrollWidget->setHScrollBarMode(TQScrollView::Auto);
	m_base->traceScrollWidget->setVScrollBarMode(TQScrollView::Auto);
	m_traceWidget->showLeftTraceInfoArea(true);
	m_traceWidget->fitLeftTraceInfoArea(true);
	m_traceWidget->setLeftTraceInfoAreaFitSpacing(10);
	m_traceWidget->showLeftCursorTraceInfoArea(true);
	m_traceWidget->setMinimumPixelsPerHorizDiv(30);
	m_traceWidget->setNumberOfCursors(3);
	m_traceWidget->setTraceInfoCursor(2);
	m_traceWidget->setHoverCursor(2);
	m_traceWidget->setCursorColor(0, TQColor(0, 255, 0));
	m_traceWidget->setCursorColor(1, TQColor(0, 255, 0));
	m_traceWidget->setCursorColor(2, TQColor(255, 255, 0));
	m_traceWidget->setCursorHighlightColor(0, TQColor(192, 255, 192));
	m_traceWidget->setCursorHighlightColor(1, TQColor(192, 255, 192));
	m_traceWidget->setCursorHighlightColor(2, TQColor(255, 255, 192));
	m_traceWidget->setCursorOrientation(0, TQt::Vertical);
	m_traceWidget->setCursorOrientation(1, TQt::Vertical);
	m_traceWidget->setCursorOrientation(2, TQt::Vertical);
	m_traceWidget->setCursorEnabled(0, true);
	m_traceWidget->setCursorEnabled(1, true);
	m_traceWidget->setCursorEnabled(2, true);
	m_traceWidget->setCursorName(0, "Cursor V1");
	m_traceWidget->setCursorName(1, "Cursor V2");
	m_traceWidget->setCursorName(2, "Cursor VH");
	m_traceWidget->setCursorPosition(0, 25);
	m_traceWidget->setCursorPosition(1, 75);
	TraceNumberList activeTraces;
	for (uint trace=0; trace<1; trace++) {
		activeTraces.append(trace);
	}
	m_traceWidget->setCursorActiveTraceList(0, activeTraces);
	m_traceWidget->setCursorActiveTraceList(1, activeTraces);
	m_traceWidget->setCursorActiveTraceList(2, activeTraces);
	m_traceWidget->setZoomBoxEnabled(false);
	m_traceWidget->setHorizCursorDirectClickEnabled(true);

	connect(m_base->acqStart, SIGNAL(clicked()), this, SLOT(startDAQ()));
	connect(m_base->acqStop, SIGNAL(clicked()), this, SLOT(stopDAQ()));
	connect(m_base->runControlStartButton, SIGNAL(clicked()), this, SLOT(startLogicAnalyzer()));
	connect(m_base->runControlStopButton, SIGNAL(clicked()), this, SLOT(stopLogicAnalyzer()));

	connect(m_base->waveformSave, SIGNAL(clicked()), this, SLOT(saveWaveforms()));
	connect(m_base->waveformRecall, SIGNAL(clicked()), this, SLOT(recallWaveforms()));

	TQTimer::singleShot(0, this, TQT_SLOT(postInit()));
}

LogicAnalyzerPart::~LogicAnalyzerPart() {
	if (m_instrumentMutex->locked()) {
		printf("[WARNING] Exiting when data transfer still in progress!\n\r"); fflush(stdout);
	}

	disconnectFromServer();
	delete m_instrumentMutex;
}

void LogicAnalyzerPart::postInit() {
	setUsingFixedSize(false);
}

bool LogicAnalyzerPart::openURL(const KURL &url) {
	int ret;
	m_connectionActiveAndValid = false;
	ret = connectToServer(url.url());
	processLockouts();
	return (ret != 0);
}

bool LogicAnalyzerPart::closeURL() {
	disconnectFromServer();
	m_url = KURL();
	return true;
}

void LogicAnalyzerPart::processLockouts() {
	// Largest area
	if (m_connectionActiveAndValid) {
		if ((m_commHandlerMode < 2) && (m_commHandlerState < 2)) {
			m_base->setEnabled(false);
		}
		else {
			m_base->setEnabled(true);
		}
	}
	else {
		m_base->setEnabled(false);
	}

	// Middle area
	if (((m_commHandlerMode < 2) && (m_commHandlerState < 50)) || (stopTraceUpdate)) {
		m_base->groupLogicAnalyzerCaptureControls->setEnabled(false);
	}
	else {
		m_base->groupLogicAnalyzerCaptureControls->setEnabled(true);
	}

	// Least area
	if (stopTraceUpdate) {
		m_base->acqStop->setEnabled(false);
		m_base->acqStart->setEnabled(true);
		m_base->waveformSave->setEnabled(true);
		m_base->waveformRecall->setEnabled(true);
	}
	else {
		m_base->acqStop->setEnabled(true);
		m_base->acqStart->setEnabled(false);
		m_base->waveformSave->setEnabled(false);
		m_base->waveformRecall->setEnabled(false);
	}
	if (m_running) {
		m_base->runControlStartButton->setEnabled(false);
		m_base->runControlStopButton->setEnabled(true);
	}
	else {
		m_base->runControlStartButton->setEnabled(true);
		m_base->runControlStopButton->setEnabled(false);
	}
}

void LogicAnalyzerPart::disconnectFromServerCallback() {
	m_forcedUpdateTimer->stop();
	m_updateTimeoutTimer->stop();
	m_connectionActiveAndValid = false;
}

void LogicAnalyzerPart::connectionFinishedCallback() {
	connect(m_socket, SIGNAL(readyRead()), m_socket, SLOT(processPendingData()));
	m_socket->processPendingData();
	connect(m_socket, SIGNAL(newDataReceived()), this, SLOT(mainEventLoop()));
	m_tickerState = 0;
	m_commHandlerState = 0;
	m_commHandlerMode = 0;
	m_socket->setDataTimeout(NETWORK_COMM_TIMEOUT_MS);
	m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);
	processLockouts();
	mainEventLoop();
	return;
}

void LogicAnalyzerPart::connectionStatusChangedCallback() {
	processLockouts();
}

void LogicAnalyzerPart::setTickerMessage(TQString message) {
	int i;
	bool updatesPending = false;
	for (i=0; i<=MAXTRACES;i++) {
		if (m_channelActiveSet[i]) updatesPending = true;
		if (m_voltsDivSet[i]) updatesPending = true;
		if (m_runningSet) updatesPending = true;
	}

	m_connectionActiveAndValid = true;
	TQString tickerChar;
	switch (m_tickerState) {
		case 0:
			tickerChar = "-";
			break;
		case 1:
			tickerChar = "\\";
			break;
		case 2:
			tickerChar = "|";
			break;
		case 3:
			tickerChar = "/";
			break;
	}
	if (updatesPending) {
		setStatusMessage(i18n("Updates pending") + ", " + message + TQString("... %1").arg(tickerChar));
	}
	else {
		setStatusMessage(message + TQString("... %1").arg(tickerChar));
	}
	m_tickerState++;
	if (m_tickerState > 3) {
		m_tickerState = 0;
	}
}

#define UPDATEDISPLAY_TIMEOUT		m_connectionActiveAndValid = false;														\
					m_tickerState = 0;																\
					m_commHandlerState = LogicAnalyzerState_ResetRequest;													\
					m_commHandlerMode = 0;																\
					m_socket->clearIncomingData();															\
					setStatusMessage(i18n("Server ping timeout.  Please verify the status of your network connection."));						\
					m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);											\
					m_instrumentMutex->unlock();															\
					return;

#define COMMUNICATIONS_FAILED		m_connectionActiveAndValid = false;														\
					m_tickerState = 0;																\
					m_commHandlerState = LogicAnalyzerState_ResetRequest;													\
					m_commHandlerMode = 0;																\
					m_socket->clearIncomingData();															\
					setStatusMessage(i18n("Instrument communication failure.  Please verify the status of your network connection."));				\
					m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);											\
					m_instrumentMutex->unlock();															\
					return;

#define SET_WATCHDOG_TIMER		if (!m_updateTimeoutTimer->isActive()) m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);
#define PAT_WATCHDOG_TIMER		m_updateTimeoutTimer->stop(); m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);

#define SET_NEXT_STATE(x)		if (m_commHandlerMode == 0) {															\
						m_commHandlerState = x;															\
					}																		\
					else {																		\
						m_commHandlerState = LogicAnalyzerState_ExternalCommandRequest;											\
						EXEC_NEXT_STATE_IMMEDIATELY														\
					}
#define SET_NEXT_STATE_DATA_WAITING(x)	m_commHandlerState = x;

#define EXEC_NEXT_STATE_IMMEDIATELY	m_forcedUpdateTimer->start(0, TRUE);

int getNextActiveChannel(int current, bool* activity, int maxtracenumber) {
	int ret = -1;
	for (int i=current+1; i<=maxtracenumber; i++) {
		if (activity[i]) {
			ret = i;
			break;
		}
	}
	return ret;
}

void LogicAnalyzerPart::mainEventLoop() {
	TQDataStream ds(m_socket);
	ds.setPrintableData(true);

	if (!m_instrumentMutex->tryLock()) {
		EXEC_NEXT_STATE_IMMEDIATELY
		return;
	}

	if (m_socket) {
		if ((m_commHandlerMode == 0) || (m_commHandlerMode == 1)) {
			if (m_commHandlerState == LogicAnalyzerState_InitialRequest) {
				// Request logic analyzer access
				ds << TQString("LOGICANALYZER");
				m_socket->writeEndOfFrame();

				m_commHandlerState = LogicAnalyzerState_InitialRequest+1;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_InitialRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Connected"));
	
					// Get command status
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						SET_NEXT_STATE(LogicAnalyzerState_ResetRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_ResetRequest) {
				// Reset logicanalyzer
				ds << TQString("RESET");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_ResetRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_ResetRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Reset complete]"));
	
					// Get command status
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						SET_NEXT_STATE(LogicAnalyzerState_HorizontalDivCountRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_HorizontalDivCountRequest) {
				// Get number of horizontal divisions, step 1
				ds << TQString("GETHORIZONTALDIVCOUNT");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_HorizontalDivCountRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_HorizontalDivCountRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received horizontal division count]"));

					// Get number of horizontal divisions, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_hdivs;
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(LogicAnalyzerState_ChannelCountRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_ChannelCountRequest) {
				// Get number of channels, step 1
				ds << TQString("GETNUMBEROFCHANNELS");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_ChannelCountRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_ChannelCountRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received number of channels]"));
	
					// Get number of channels, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_maxNumberOfTraces;
						if (m_maxNumberOfTraces > MAXTRACES) {
							m_maxNumberOfTraces = MAXTRACES;
						}

						// Lock the number of vertical divisions to the number of traces
						// This provides a useful baseline effect whereby each trace has a dotted zero line
						m_vdivs = m_maxNumberOfTraces;

						// Set true/false (0-1) to one division
						double voltsDiv = 1.5;
						int traceno;
						for (traceno=0; traceno<m_maxNumberOfTraces; traceno++) {
							m_voltsDiv[traceno+1] = voltsDiv;
						}

						// Stack all channels vertically
						double offset = ((double)m_vdivs/2)*voltsDiv;
						double step = ((double)m_vdivs/m_maxNumberOfTraces)*voltsDiv;
						offset = offset - step;		// Make sure the first channel text is visible
						for (int i=0;i<m_maxNumberOfTraces; i++) {
							m_traceWidget->setTraceOffset(i, offset, true);
							m_traceWidget->setTraceTextOffset(i, 0.75, true);
							offset = offset - step;
						}
					}
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						m_currentOpChannel = 1;
						SET_NEXT_STATE(LogicAnalyzerState_ChannelNameRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_ChannelNameRequest) {
				// Get channel name, step 1
				ds << TQString("GETCHANNELNAME");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_ChannelNameRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_ChannelNameRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received channel names]"));

					// Get channel status, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						int traceno;
						for (traceno=0; traceno<m_maxNumberOfTraces; traceno++) {
							ds >> m_channelName[traceno+1];
						}
					}
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						SET_NEXT_STATE(LogicAnalyzerState_ChannelActiveStateRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_ChannelActiveStateRequest) {
				// Get channel status, step 1
				ds << TQString("GETCHANNELACTIVE");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_ChannelActiveStateRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_ChannelActiveStateRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received channel activity status]"));

					// Get channel status, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						int traceno;
						for (traceno=0; traceno<m_maxNumberOfTraces; traceno++) {
							TQ_INT16 active;
							ds >> active;
							m_channelActive[traceno+1] = (active != 0);
						}
					}
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						SET_NEXT_STATE(LogicAnalyzerState_TraceSampleCountRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_TraceSampleCountRequest) {
				// Get number of samples in trace, step 1
				ds << TQString("GETTRACESAMPLECOUNT");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_TraceSampleCountRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_TraceSampleCountRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received trace sample count]"));
	
					// Get number of samples in trace, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						int traceno;
						for (traceno=0; traceno<m_maxNumberOfTraces; traceno++) {
							ds >> m_samplesInTrace[traceno+1];
						}
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(LogicAnalyzerState_TraceSecondsDivRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_TraceSecondsDivRequest) {
				// Get seconds per division, step 1
				ds << TQString("GETSECONDSSDIV");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_TraceSecondsDivRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_TraceSecondsDivRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received seconds/div]"));

					// Get seconds per division, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						int traceno;
						for (traceno=0; traceno<m_maxNumberOfTraces; traceno++) {
							ds >> m_secsDiv[traceno+1];
						}
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(LogicAnalyzerState_RunningRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_RunningRequest) {
				// Get running, step 1
				ds << TQString("GETRUNNING");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_RunningRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_RunningRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received run status]"));

					// Get running, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						TQ_INT16 status;
						ds >> status;
						m_running = (status != 0);
					}
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						// Update display widget(s)
						updateGraticule();
					}

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
						SET_NEXT_STATE(LogicAnalyzerState_TraceRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_TraceRequest) {
				// Get trace, step 1
				ds << TQString("GETLOGICTRACES");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				m_lastChangesRequireFullUpdate = false;
				SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_TraceRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_TraceRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Running [Received traces]"));

					// Get trace, step 2
					TQString result;
					ds >> result;

					if (result == "ACK") {
						int traceno;
						for (traceno=0; traceno<m_maxNumberOfTraces; traceno++) {
							TQDoubleArray trace;
							TQDoubleArray positions;

							// Get trace data
							ds >> trace;
							ds >> positions;
	
							// Set trace widgets
							m_traceWidget->setSamples(traceno, trace, true);
							m_traceWidget->setPositions(traceno, positions, (traceno<(m_maxNumberOfTraces-1))?true:false);
						}
					}
					m_socket->clearFrameTail();

					// Update display widget(s)
					postProcessTrace();
					m_traceWidget->repaint(false);

					if (result == "ACK") {
						if ((m_channelActiveSet[m_currentOpChannel] == false)
							&& (m_voltsDivSet[m_currentOpChannel] == false)
							&& (m_runningSet == false)
						) {
							SET_NEXT_STATE(LogicAnalyzerState_TraceRequest)
						}
						else {
							m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
							SET_NEXT_STATE(LogicAnalyzerState_ChannelActiveStateUpdate)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_ChannelActiveStateUpdate) {
				if (m_channelActiveSet[m_currentOpChannel]) {
					// Set channel active, step 1
					ds << TQString("SETCHANNELACTIVE");
					ds << m_currentOpChannel;
					TQ_INT16 active = (m_channelActive[m_currentOpChannel])?1:0;
					ds << active;
					m_socket->writeEndOfFrame();

					m_lastChangesRequireFullUpdate = true;
					m_channelActiveSet[m_currentOpChannel] = false;
					SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_ChannelActiveStateUpdate+1)
				}
				else {
					if (m_currentOpChannel < (m_maxNumberOfTraces-1)) {
						m_currentOpChannel++;
						SET_NEXT_STATE(LogicAnalyzerState_ChannelActiveStateUpdate)
					}
					else {
						m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
						if (m_lastChangesRequireFullUpdate) {
							SET_NEXT_STATE(LogicAnalyzerState_TraceSecondsDivRequest)
						}
						else {
							SET_NEXT_STATE(LogicAnalyzerState_TraceVoltsDivUpdate)
						}
					}
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_ChannelActiveStateUpdate+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Updating [Set channel %1 activity status]").arg(m_currentOpChannel));
	
					// Set channel active, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
						if (m_currentOpChannel > 0) {
							SET_NEXT_STATE(LogicAnalyzerState_ChannelActiveStateUpdate)
						}
						else {
							m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
							if (m_lastChangesRequireFullUpdate) {
								SET_NEXT_STATE(LogicAnalyzerState_TraceSecondsDivRequest)
							}
							else {
								SET_NEXT_STATE(LogicAnalyzerState_TraceVoltsDivUpdate)
							}
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_TraceVoltsDivUpdate) {
				if (m_voltsDivSet[m_currentOpChannel]) {
					// Set volts per division, step 1
					ds << TQString("SETVOLTSDIV");
					ds << m_currentOpChannel;
					ds << m_voltsDiv[m_currentOpChannel];
					m_socket->writeEndOfFrame();

					m_voltsDivSet[m_currentOpChannel] = false;
					SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_TraceVoltsDivUpdate+1)
				}
				else {
					m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
					if (m_currentOpChannel > 0) {
						SET_NEXT_STATE(LogicAnalyzerState_TraceVoltsDivUpdate)
					}
					else {
						SET_NEXT_STATE(LogicAnalyzerState_RunningUpdate)
					}
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_TraceVoltsDivUpdate+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Updating [Set volts/div for channel %1]").arg(m_currentOpChannel));
	
					// Set volts per division, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
						if (m_currentOpChannel > 0) {
							SET_NEXT_STATE(LogicAnalyzerState_TraceVoltsDivUpdate)
						}
						else {
							SET_NEXT_STATE(LogicAnalyzerState_RunningUpdate)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_RunningUpdate) {
				if (m_runningSet) {
					// Set running, step 1
					ds << TQString("SETRUNNING");
					TQ_INT16 running = (m_running)?1:0;
					ds << running;
					m_socket->writeEndOfFrame();

					m_runningSet = false;
					SET_NEXT_STATE_DATA_WAITING(LogicAnalyzerState_RunningUpdate+1)
				}
				else {
					m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
					SET_NEXT_STATE(LogicAnalyzerState_TraceRequest)
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == LogicAnalyzerState_RunningUpdate+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Updating [Set run status]"));
	
					// Set running, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
						SET_NEXT_STATE(LogicAnalyzerState_TraceRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == LogicAnalyzerState_ExternalCommandRequest) {
				// Execute pending command
				m_commHandlerMode = 2;
				m_socket->clearIncomingData();
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			SET_WATCHDOG_TIMER
		}
		else if (m_commHandlerMode == 2) {
			if (m_commHandlerCommandState == 0) {
				m_commHandlerMode = 0;
				m_commHandlerState = LogicAnalyzerState_ChannelActiveStateRequest;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerCommandState == 1) {
				// Set channel active
				ds << TQString("SETCHANNELACTIVE");
				ds << m_nextOpChannel;
				ds << m_nextOpParameter16;
				m_socket->writeEndOfFrame();

				m_commHandlerCommandState = 2;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerCommandState == 2) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Connected"));

					// Set channel active, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();
	
					if (result == "ACK") {
						m_commHandlerCommandState = 0;
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerCommandState == 3) {
				if (stopTraceUpdate == false) {
					m_commHandlerCommandState = 0;
					EXEC_NEXT_STATE_IMMEDIATELY
				}
				else {
					setTickerMessage(i18n("Data acquisition stopped"));
				}
			}
		}
	}
	else {
		m_commHandlerState = LogicAnalyzerState_ResetRequest;
		m_commHandlerCommandState = 0;
	}

	processLockouts();

	m_instrumentMutex->unlock();
}

void LogicAnalyzerPart::postProcessTrace() {
	return;
}

void LogicAnalyzerPart::startDAQ() {
	stopTraceUpdate = false;
	if (m_socket) m_socket->clearIncomingData();
	EXEC_NEXT_STATE_IMMEDIATELY
}

void LogicAnalyzerPart::stopDAQ() {
	if (m_commHandlerMode < 2) {
		stopTraceUpdate = true;
		for (int i=0; i<=MAXTRACES;i++) {
			m_channelActiveSet[i] = false;
			m_voltsDivSet[i] = false;
		}
		m_runningSet = false;
		m_commHandlerMode = 1;
		m_commHandlerCommandState = 3;
		mainEventLoop();
	}
}

#define WAVEFORM_MAGIC_NUMBER 1
#define WAVEFORM_FILE_VERSION 1

void LogicAnalyzerPart::saveWaveforms() {
	TQString saveFileName = KFileDialog::getSaveFileName(TQString::null, "*.wfm|Waveform Files (*.wfm)", 0, i18n("Save waveforms..."));
	if (saveFileName != "") {
		TQFile file(saveFileName);
		file.open(IO_WriteOnly);
		TQDataStream ds(&file);
		TQ_INT32 magicNumber = WAVEFORM_MAGIC_NUMBER;
		TQ_INT32 version = WAVEFORM_FILE_VERSION;
		ds << magicNumber;
		ds << version;
		ds << m_hdivs;
		ds << m_vdivs;
		ds << m_maxNumberOfTraces;
		for (int traceno=1; traceno<=m_maxNumberOfTraces; traceno++) {
			TQ_UINT8 boolValue;
			boolValue = m_channelActive[traceno];
			ds << boolValue;
			ds << m_samplesInTrace[traceno];
			ds << m_voltsDiv[traceno];
			ds << m_secsDiv[traceno];
			ds << m_traceWidget->samples(traceno-1);
			ds << m_traceWidget->positions(traceno-1);
		}
		for (int cursorno=0; cursorno<5; cursorno++) {
			ds << m_traceWidget->cursorPosition(cursorno);
		}
	}
}

void LogicAnalyzerPart::recallWaveforms() {
	TQString openFileName = KFileDialog::getOpenFileName(TQString::null, "*.wfm|Waveform Files (*.wfm)", 0, i18n("Open waveforms..."));
	if (openFileName != "") {
		TQFile file(openFileName);
		file.open(IO_ReadOnly);
		TQDataStream ds(&file);
		TQ_INT32 magicNumber;
		TQ_INT32 version;
		ds >> magicNumber;
		if (magicNumber == WAVEFORM_MAGIC_NUMBER) {
			ds >> version;
			if (version == WAVEFORM_FILE_VERSION) {
				ds >> m_hdivs;
				ds >> m_vdivs;
				ds >> m_maxNumberOfTraces;
				for (int traceno=1; traceno<=m_maxNumberOfTraces; traceno++) {
					TQ_UINT8 boolValue;
					ds >> boolValue;
					m_channelActive[traceno] = (boolValue!=0)?true:false;
					ds >> m_samplesInTrace[traceno];
					ds >> m_voltsDiv[traceno];
					ds >> m_secsDiv[traceno];
					double offset;
					TQDoubleArray values;
					TQDoubleArray positions;
					ds >> offset;
					ds >> values;
					ds >> positions;
					m_traceWidget->setNumberOfSamples(traceno-1, m_samplesInTrace[traceno], true);
					m_traceWidget->setSamples(traceno-1, values);
					m_traceWidget->setPositions(traceno-1, positions);
					m_traceWidget->setTraceOffset(traceno-1, offset);
				}
				for (int cursorno=0; cursorno<5; cursorno++) {
					double cursorPos;
					ds >> cursorPos;
					m_traceWidget->setCursorPosition(cursorno, cursorPos);
				}
				updateGraticule();
				postProcessTrace();
				m_traceWidget->repaint(false);
			}
			else {
				KMessageBox::error(0, i18n("<qt>The selected waveform file version does not match this client</qt>"), i18n("Invalid File"));
			}
		}
		else {
			KMessageBox::error(0, i18n("<qt>Invalid waveform file selected</qt>"), i18n("Invalid File"));
		}
	}
}

void LogicAnalyzerPart::updateGraticule() {
	m_traceWidget->setNumberOfHorizontalDivisions(m_hdivs);
	m_traceWidget->setNumberOfVerticalDivisions(m_vdivs);

	for (int traceno=1; traceno<=m_maxNumberOfTraces; traceno++) {
		m_traceWidget->setTraceEnabled(traceno-1, m_channelActive[traceno], TraceWidget::NoText, true);
		m_traceWidget->setTraceName(traceno-1, m_channelName[traceno], true);
		m_traceWidget->setTraceHorizontalUnits(traceno-1, "s", true);
		m_traceWidget->setTraceVerticalUnits(traceno-1, "", true);

		m_traceWidget->setNumberOfSamples(traceno-1, m_samplesInTrace[traceno], true);
		m_traceWidget->setDigitalTraceMode(traceno-1, true, true);
		m_traceWidget->suppressNameInCursorText(traceno-1, true, true);

		m_traceWidget->setDisplayLimits(traceno-1, TQRectF(0.0, (m_voltsDiv[traceno]*m_vdivs)/2.0, (m_secsDiv[traceno]*m_hdivs), (m_voltsDiv[traceno]*m_vdivs)/-2.0), (traceno<m_maxNumberOfTraces)?true:false);
	}
}

void LogicAnalyzerPart::startLogicAnalyzer() {
	m_running = true;
	m_runningSet = true;
}

void LogicAnalyzerPart::stopLogicAnalyzer() {
	m_running = false;
	m_runningSet = true;
}

TDEAboutData* LogicAnalyzerPart::createAboutData() {
	return new TDEAboutData( APP_NAME, I18N_NOOP( APP_PRETTYNAME ), APP_VERSION );
}

} //namespace RemoteLab

#include "part.moc"
