summaryrefslogtreecommitdiffstats
path: root/clients/tde/src/part/prototerminal/part.cpp
blob: 78189884fed9b297d70423eaa748130a699f7ed7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
 * Remote Laboratory Protocol Terminal 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 <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 <tqeventloop.h>
#include <tqapplication.h>
#include <tqpushbutton.h>
#include <klineedit.h>
#include <ktextedit.h>
#include <unistd.h>       //access()
#include <stdint.h>
#include <cmath>

#include "layout.h"

#define NETWORK_COMM_TIMEOUT_MS 15000

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

namespace RemoteLab {

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


ProtoTerminalPart::ProtoTerminalPart( TQWidget *parentWidget, const char *widgetName, TQObject *parent, const char *name, const TQStringList& )
	: RemoteInstrumentPart( parent, name ), m_commHandlerState(-1), m_commHandlerMode(0), m_commHandlerCommandState(0), m_connectionActiveAndValid(false), m_base(0)
{
	// 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()));

	// Create widgets
	m_base = new ProtoTerminalBase(widget());

	// Initialize widgets
	m_base->setMinimumSize(500,350);

	connect(m_base->sendText, SIGNAL(clicked()), this, SLOT(sendTextClicked()));
	connect(m_base->textInput, SIGNAL(returnPressed()), m_base->sendText, SIGNAL(clicked()));

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

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

	disconnectFromServer();
	delete m_instrumentMutex;
}

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

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

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

void ProtoTerminalPart::processLockouts() {
	if (m_connectionActiveAndValid) {
		m_base->setEnabled(true);
	}
	else {
		m_base->setEnabled(false);
	}
}

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

void ProtoTerminalPart::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 ProtoTerminalPart::connectionStatusChangedCallback() {
	processLockouts();
}

void ProtoTerminalPart::setTickerMessage(TQString message) {
	m_connectionActiveAndValid = true;
	TQString tickerChar;
	switch (m_tickerState) {
		case 0:
			tickerChar = "-";
			break;
		case 1:
			tickerChar = "\\";
			break;
		case 2:
			tickerChar = "|";
			break;
		case 3:
			tickerChar = "/";
			break;
	}
	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 = 2;																\
					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 = 2;																\
					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);							\
					setTickerMessage(i18n("Connected"));

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

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

void ProtoTerminalPart::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 == 0) {
				// Setup functions go here
				setTickerMessage("Connection established");

				m_commHandlerState = 1;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == 1) {
				// Receive data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER

					// Get command status
					TQString input;
					while (!ds.atEnd()) {
						ds >> input;

						if (input != "") {
							input.replace("\r", "\n");
							m_base->textOutput->append(">>>" + input);
						}
					}
					m_socket->clearFrameTail();
					EXEC_NEXT_STATE_IMMEDIATELY
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}

				// Send data
				if (m_TextToSend != "") {
					ds << m_TextToSend;
					m_socket->writeEndOfFrame();

					m_base->textOutput->append("<<<" + m_TextToSend);
					m_TextToSend = "";

					EXEC_NEXT_STATE_IMMEDIATELY
				}

				// Never time out
				PAT_WATCHDOG_TIMER
			}
			else if (m_commHandlerState == 2) {
				// Ignore timeouts
				m_commHandlerState = 1;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			SET_WATCHDOG_TIMER
		}
	}
	else {
		m_commHandlerState = 0;
		m_commHandlerCommandState = 0;
	}

	processLockouts();

	m_instrumentMutex->unlock();
}

void ProtoTerminalPart::sendTextClicked() {
	m_TextToSend = m_TextToSend + m_base->textInput->text();
	m_base->textInput->setText("");

	// Transmit!
	EXEC_NEXT_STATE_IMMEDIATELY
}

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

} //namespace RemoteLab

#include "part.moc"