summaryrefslogtreecommitdiffstats
path: root/clients/tde/src/part/fpgaprogram/part.cpp
blob: bf7e46a78af039062455356e96b9a26a40acce80 (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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/*
 * Remote Laboratory FPGA Programming 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) 2012 Timothy Pearson
 * Raptor Engineering
 * http://www.raptorengineeringinc.com
 */

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

#include <kaboutdata.h>   //::createAboutData()
#include <kaction.h>
#include <klocale.h>
#include <kmessagebox.h>  //::start()
#include <kparts/genericfactory.h>
#include <kstatusbar.h>
#include <kstdaction.h>
#include <knuminput.h>
#include <kmdcodec.h>
#include <kurlrequester.h>
#include <tqfile.h>        //encodeName()
#include <tqtimer.h>       //postInit() hack
#include <tqvbox.h>
#include <tqsocket.h>
#include <tqmutex.h>
#include <tqeventloop.h>
#include <tqapplication.h>
#include <tqgroupbox.h>
#include <tqcheckbox.h>
#include <tqpushbutton.h>
#include <tqprogressbar.h>
#include <unistd.h>       //access()
#include <stdint.h>

#include <tqpainter.h>

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

// RAJA UNCOMMENT ME
//#define SERVER_TIMEOUT_MS 10000
// RAJA DEBUG ONLY
#define SERVER_TIMEOUT_MS 100000
#define FPGA_COMM_TIMEOUT_MS 500
#define FPGA_DATA_PROCESSING_TIMEOUT_MS 2500

namespace RemoteLab {

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

FPGAProgramPart::FPGAProgramPart(TQWidget *parentWidget, const char *widgetName, TQObject *parent, const char *name, const TQStringList&)
	: RemoteInstrumentPart( parent, name ), m_socket(0), m_base(0), connToServerConnecting(false), connToServerState(-1), connToServerTimeoutTimer(NULL),
	m_commHandlerState(0), m_connectionActiveAndValid(false), m_tickerState(0)
{
	// Initialize mutex
	m_connectionMutex = new TQMutex(false);

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

	// Create timers
	m_updateTimer = new TQTimer(this);

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

	// Initialize widgets
	connect(m_base->programRunButton, SIGNAL(clicked()), this, SLOT(programRunButtonClicked()));

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

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

	disconnectFromServer();
	delete m_connectionMutex;
}

void FPGAProgramPart::processLockouts() {
	TQWidget* mainWidget = widget();
	if (mainWidget) {
		if ((m_socket) && (m_socket->state() == TQSocket::Connected) && (connToServerState > 0) && (connToServerConnecting == false)) {
			mainWidget->setEnabled(true);
		}
		else {
			mainWidget->setEnabled(false);
		}
	}

	if ((m_base->programmingInputFile->url() != "") && (m_commHandlerMode == 0) && (m_connectionActiveAndValid == true)) {
		m_base->programRunButton->setEnabled(true);
	}
	else {
		m_base->programRunButton->setEnabled(false);
	}

	if (m_commHandlerMode == 1) {
		m_base->programmingInputFile->setEnabled(false);
	}
	else {
		m_base->programmingInputFile->setEnabled(true);
	}

	if ((m_connectionActiveAndValid == true) && (m_commHandlerMode == 0)) {
		m_base->programmingStatusLabel->setText(i18n("Ready"));
	}
}

void FPGAProgramPart::resizeToHint() {
	resize(widget()->sizeHint());
}

void FPGAProgramPart::connectionClosed() {
	closeURL();
}

void FPGAProgramPart::postInit() {
	connect(m_updateTimer, SIGNAL(timeout()), this, SLOT(updateDisplay()));
}

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

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

void FPGAProgramPart::disconnectFromServer() {
	if (m_socket) {
		m_socket->clearPendingData();
		m_socket->close();
		delete m_socket;
		m_socket = NULL;
	}
	processLockouts();
}

void FPGAProgramPart::finishConnectingToServer() {
	if (!m_socket) {
		connToServerState = -1;
		connToServerConnecting = false;
		processLockouts();
		return;
	}

	if (connToServerConnecting) {
		switch(connToServerState) {
			case 0:
				if (!connToServerTimeoutTimer) {
					connToServerTimeoutTimer = new TQTimer;
					connToServerTimeoutTimer->start(SERVER_TIMEOUT_MS, TRUE);
				}
				if ((m_socket->state() == TQSocket::Connecting) || (m_socket->state() == TQSocket::HostLookup)) {
					if (!connToServerTimeoutTimer->isActive()) {
						connToServerState = -3;
						connToServerConnecting = false;
						disconnectFromServer();
						KMessageBox::error(0, i18n("<qt>Unable to establish connection to remote server</qt>"), i18n("Connection Failed"));
					}
				}
				else {
					if (m_socket->state() == TQSocket::Connected) {
						printf("[DEBUG] Initial connection established...\n\r"); fflush(stdout);
						m_socket->setDataTimeout(SERVER_TIMEOUT_MS);
						m_socket->setUsingKerberos(true);
						connToServerState = 1;
					}
					else {
						connToServerState = -1;
						connToServerConnecting = false;
						disconnectFromServer();
						KMessageBox::error(0, i18n("<qt>Unable to establish connection to remote server</qt>"), i18n("Connection Failed"));
					}
				}
				break;
			case 1:
				if (m_socket->kerberosStatus() == TDEKerberosClientSocket::KerberosInitializing) {
					// Do nothing
				}
				else {
					if (m_socket->kerberosStatus() != TDEKerberosClientSocket::KerberosInUse) {
						connToServerState = -1;
						connToServerConnecting = false;
						disconnectFromServer();
						KMessageBox::error(0, i18n("<qt>Unable to establish Kerberos protocol with remote server<p>Please verify that you currently hold a valid Kerberos ticket</qt>"), i18n("Connection Failed"));
					}
					else {
						connToServerState = 2;
					}
				}
				break;
			case 2:
				// Connection established!
				// Read magic number and proto version from server
				TQDataStream ds(m_socket);
				TQ_UINT32 magicnum;
				TQ_UINT32 protover;
				ds >> magicnum;
				ds >> protover;
				printf("[DEBUG] Got magic number %d and protocol version %d\n\r", magicnum, protover); fflush(stdout);

				// Request connection to backend server
				TQString response;
				ds << TQString("SERV");
				ds << TQString(CLIENT_LIBRARY);
				ds >> response;
printf("[RAJA DEBUG 400.0] Got '%s' from the server\n\r", response.ascii()); fflush(stdout);
				if (response == "OK") {
					connToServerState = 3;
					connToServerConnecting = false;
					connect(m_socket, SIGNAL(readyRead()), m_socket, SLOT(processPendingData()));
					connect(m_socket, SIGNAL(newDataReceived()), this, SLOT(updateDisplay()));
					m_tickerState = 0;
					m_commHandlerState = 0;
					m_commHandlerMode = 0;
					m_updateTimer->start(FPGA_COMM_TIMEOUT_MS, FALSE);
					processLockouts();
					updateDisplay();
					return;
				}
				else if (response == "ERRNOCONN") {
					connToServerState = -1;
					connToServerConnecting = false;
					disconnectFromServer();
					KMessageBox::error(0, i18n("<qt>Unable to establish connection with backend server<p>Please verify that you are currently connected to a workspace</qt>"), i18n("Connection Failed"));
					close();
					return;
				}
				else if (response == "ERRNOTAVL") {
					connToServerState = -1;
					connToServerConnecting = false;
					disconnectFromServer();
					KMessageBox::error(0, i18n("<qt>The backend server is not available at this time<p>Please try a different workspace, or try again later</qt>"), i18n("Connection Failed"));
					close();
					return;
				}
				else if (response == "ERRNOSERV") {
					connToServerState = -1;
					connToServerConnecting = false;
					disconnectFromServer();
					KMessageBox::error(0, i18n("<qt>The active laboratory workspace does not support the requested service</qt>"), i18n("Service Unavailable"));
					close();
					return;
				}
				else {
					connToServerState = -1;
					connToServerConnecting = false;
					disconnectFromServer();
					KMessageBox::error(0, i18n("<qt>Unable to establish connection with remote server</qt>"), i18n("Connection Failed"));
					close();
					return;
				}
				break;
		}

		TQTimer::singleShot(0, this, SLOT(finishConnectingToServer()));
	}
}

int FPGAProgramPart::connectToServer(TQString server) {
	if (m_socket) {
		return -1;
	}
	if (!m_socket) {
		m_socket = new TDEKerberosClientSocket(this);
		connect(m_socket, TQT_SIGNAL(statusMessageUpdated(const TQString&)), this, TQT_SLOT(setStatusMessage(const TQString&) ));
	}
	m_socket->setServiceName("remotefpga");
	m_socket->setServerFQDN(server);
	m_socket->connectToHost(server, 4004);

	// Finish connecting when appropriate
	connToServerState = 0;
	connToServerConnecting = true;
	TQTimer::singleShot(0, this, SLOT(finishConnectingToServer()));

	return 0;
}

void FPGAProgramPart::programRunButtonClicked() {
	m_commHandlerState = 0;
	m_commHandlerMode = 1;
	processLockouts();
}

#define UPDATEDISPLAY_TIMEOUT	m_connectionActiveAndValid = false;														\
				m_tickerState = 0;																\
				m_commHandlerState = 0;																\
				m_commHandlerMode = 0;																\
				while (m_socket->bytesAvailable() > 0) {													\
					m_socket->readBlock(data, 64);														\
				}																		\
				setStatusMessage(i18n("Debug interface timeout, still waiting for data.  Please verify that the FPGA is properly configured."));		\
				m_updateTimer->start(FPGA_COMM_TIMEOUT_MS, FALSE);												\
				return;

void FPGAProgramPart::updateDisplay() {
	m_updateTimer->stop();
	TQDataStream ds(m_socket);

	if (m_socket) {
		char data[64];

		if (m_commHandlerMode == 0) {
			// Normal operation
			switch (m_commHandlerState) {
				case 0:
					// Get status of remote system
					// RAJA FIXME

					ds << TQString("STATUS");
					m_updateTimer->start(FPGA_COMM_TIMEOUT_MS, FALSE);

					m_commHandlerState = 1;
					break;
				case 1:
					// Get all data
					if (m_socket->bytesAvailable() > 0) {
						// RAJA FIXME
						TQStringList statusDetails;
						ds >> statusDetails;

						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(i18n("Running") + TQString("... %1").arg(tickerChar));
						m_tickerState++;
						if (m_tickerState > 3) {
							m_tickerState = 0;
						}
						m_updateTimer->start(FPGA_COMM_TIMEOUT_MS, FALSE);

						m_commHandlerState = 0;
					}
					else {
						if (!m_updateTimer->isActive()) {
							UPDATEDISPLAY_TIMEOUT
						}
					}
	
					break;
			}
		}
		else if (m_commHandlerMode == 1) {
			// Program mode!
			// RAJA FIXME
			if (m_commHandlerState == 0) {
				m_base->programmingStatusLabel->setText(i18n("Reading input file") + "...");
				TQFile file(m_base->programmingInputFile->url());
				if (file.open(IO_ReadOnly)) {
					m_programmingFileData = file.readAll();
					file.close();

					m_base->programmingProgressBar->setTotalSteps(0);
					m_base->programmingProgressBar->setProgress(0);
					m_base->programmingStatusLabel->setText(i18n("Sending data to server") + "...");

					ds << TQString("FILE");
					// RAJA FIXME
					// Transmit file to remote server...
					ds << m_programmingFileData;

					m_base->programmingStatusLabel->setText(i18n("Programming device") + "...");
					ds << TQString("PROGRAM");

					m_commHandlerState = 1;
				}
				else {
					KMessageBox::error(0, i18n("<qt>Unable to open selected programming file</qt>"), i18n("Program Failed"));
					m_commHandlerMode = 0;
					m_commHandlerState = 0;
					m_base->programmingProgressBar->setTotalSteps(1);
					m_base->programmingProgressBar->setProgress(0);
					processLockouts();
				}
			}
			else if (m_commHandlerState == 1) {
				// Get response
				if (m_socket->bytesAvailable() > 0) {
					// RAJA FIXME
					TQString result;
					ds >> result;

					if (result == "PROGRAMMING") {
						// RAJA FIXME
					}
					else if (result == "DONE") {
						int retCode;
						TQString log;

						ds >> retCode;
						ds >> log;

						// RAJA FIXME
						// Handle errors

						// Done!
						m_commHandlerMode = 0;
						m_commHandlerState = 0;
						m_base->programmingProgressBar->setTotalSteps(1);
						m_base->programmingProgressBar->setProgress(0);
						processLockouts();
					}
				}
				else {
					if (!m_updateTimer->isActive()) {
						m_base->programmingProgressBar->setTotalSteps(1);
						m_base->programmingProgressBar->setProgress(0);
						m_commHandlerMode = 0;
						m_commHandlerState = 0;
						processLockouts();
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
		}
	}
	else {
		m_commHandlerState = 0;
		m_commHandlerMode = 0;
	}
}

KAboutData* FPGAProgramPart::createAboutData() {
	return new KAboutData( APP_NAME, I18N_NOOP( APP_PRETTYNAME ), APP_VERSION );
}

} //namespace RemoteLab

#include "part.moc"