-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmainwindow.cpp
480 lines (422 loc) · 18.2 KB
/
mainwindow.cpp
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
472
473
474
475
476
477
478
479
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ipdialog.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QTimer>
//#include <QtMultimedia/QMediaPlayer>
//#include <QSound>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
va(this)
{
ui->setupUi(this);
ui->password->setEchoMode(QLineEdit::Password);
QSettings settings("OAAE", "OAACARS", this);
QFile loginFile("login.txt");
if (loginFile.exists() && loginFile.open(QFile::ReadOnly)) {
QTextStream in(&loginFile);
settings.setValue("callsign", in.readLine().trimmed());
settings.setValue("password", in.readLine().trimmed());
loginFile.remove();
}
ui->callsign->setText(settings.value("callsign").toString());
ui->password->setText(settings.value("password").toString());
ui->applyWeight->setChecked(settings.value("applyWeight", true).toBool());
myip = strdup(settings.value("myip", "127.0.0.1").toByteArray().data());
remoteip = strdup(settings.value("remoteip", "127.0.0.1").toByteArray().data());
qInfo() << "myip=" << myip << ", remoteip=" << remoteip;
connect(&timer, SIGNAL(timeout()), this, SLOT(sendUpdate()));
connect(&uiTimer, SIGNAL(timeout()), this, SLOT(uiUpdate()));
sock = new QUdpSocket(this);
if (!sock->bind(32123)) {
QMessageBox::critical(this, "Error", "Error: Could not bind to port 32123.", QMessageBox::Ok);
exit(1);
}
connect(sock, SIGNAL(readyRead()), this, SLOT(gotUpdate()));
state = OFFLINE;
startFuel = 0.0f;
startTime = 0;
maxG = 0.0f;
memset(&cur, 0, sizeof(cur));
onTakeoff = onLanding = cur;
sRealTime = new QLabel(this);
sRealTime->hide();
ui->statusBar->addPermanentWidget(sRealTime);
sFlightTime = new QLabel(this);
sFlightTime->hide();
ui->statusBar->addPermanentWidget(sFlightTime);
uiTimer.start(1000);
}
MainWindow::~MainWindow()
{
sock->close();
delete sock;
delete ui;
}
void MainWindow::remindOf(QString reason)
{
if(reason=="Flight not started")
{
//--- MessageBox
//QMessageBox::critical(this, "Flight Tracking", "\nStarting up the engines already ... ?\n\nYou should also start the flight tracking now!\n", QMessageBox::Ok);
//--- get window to the foreground
setWindowState( (windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
raise(); // for MacOS
activateWindow(); // for Windows
//--- play sound using MediaPlayer
//QMediaPlayer *player = new QMediaPlayer;
//player->setMedia(QUrl::fromLocalFile("sounds//57806__guitarguy1985__aircraftalarm.wav"));
//player->play();
//--- play sound using Qsound
//QSound::play("sounds/57806__guitarguy1985__aircraftalarm.wav");
}
}
void MainWindow::on_connectButton_clicked()
{
timer.stop();
ui->statusBar->showMessage("Connecting...");
QString ret = va.login(ui->callsign->text(), ui->password->text());
if (ret == "FAIL") {
QMessageBox::warning(this, "Warning", "Login failed.", QMessageBox::Ok);
ui->connectButton->setStyleSheet("QPushButton { color: rgb(255,0,0); }");
return;
}
ret = va.getAircraft();
if (ret == "FAIL") {
ui->aircraft->setText("");
} else if (ret != "") {
// Need to see what this actually looks like.
QMessageBox::information(this, "GetAircraft", "I couldn't get that to work in my testing, but apparently it did for you!\n"
"Please send me this text:\n"+ret, QMessageBox::Ok);
}
ret = va.pilotConnection();
QJsonParseError parseErr;
QJsonDocument pc = QJsonDocument::fromJson(ret.toUtf8(), &parseErr);
QJsonArray ja = pc.array();
QJsonValue jv = ja.first();
QJsonObject data = jv.toObject();
pilot = data["id"].toString().toInt();
if (pilot == 0) {
ui->connectButton->setStyleSheet("QPushButton { color: rgb(255,0,0); }");
return;
}
ui->connectButton->setStyleSheet("QPushButton { color: rgb(0,255,0); }");
if (data.find("departure") != data.end() && data["departure"] != "") {
int yn = QMessageBox::question(this, "Flight Plan", "A flight plan was found. Load it?", QMessageBox::Yes, QMessageBox::No);
if (yn == QMessageBox::Yes) {
ui->depIcao->setText(data["departure"].toString());
ui->arrIcao->setText(data["arrival"].toString());
ui->alt1->setText(data["alternative"].toString());
ui->route->setPlainText(data["route"].toString());
ui->flightNo->setText(data["callsign"].toString());
ui->depTime->setText(data["etd"].toString());
ui->acIcao->setText(data["plane_icao"].toString());
ui->eet->setText(data["duration"].toString());
ui->tailNumber->setText(data["registry"].toString());
ui->pax->setText(data["pax"].toString());
ui->cargo->setText(data["cargo"].toString());
}
}
state = CONNECTED;
ui->statusBar->clearMessage();
ui->statusBar->showMessage("Connected.");
ui->startButton->setEnabled(true);
ui->endButton->setEnabled(false);
}
void MainWindow::on_loadJsonButton_clicked()
{
QSettings settings("OAAE", "OAACARS", this);
//get the saved filename and check if file still exists
QString fpFile=settings.value("lastJsonFpFile").toString();
QFileInfo check_file(fpFile);
if (!check_file.exists() || !check_file.isFile())
fpFile="";
//reload saved file?
if(fpFile!="")
{
int yn = QMessageBox::question(this, "Flight Plan", "Reload last used JSON Flightplan?\n"+fpFile, QMessageBox::Yes, QMessageBox::No);
if (yn == QMessageBox::No)
fpFile="";
}
//Still no valid file? Pick one now ...
if(fpFile=="")
{
fpFile = QFileDialog::getOpenFileName(this,
tr("Open JSON Flightplan"), "", tr("JSON Files (*.json)"));
}
//if we have a filename, remember filename and try to load file
if(fpFile!="")
{
settings.setValue("lastJsonFpFile", fpFile);
//load JSON data ...
QFile file(fpFile);
file.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray jsonData = file.readAll();
file.close();
QJsonDocument document = QJsonDocument::fromJson(jsonData);
QJsonObject json = document.object();
//QJsonValue value = json.value("LEG");
//QJsonArray array = value.toArray();
//foreach (const QJsonValue & v, array)
// qDebug() << v.toObject().value("NAME").toString();
//apply data, if valid
if(json["Data Format Version"].toString()=="V1.0")
{
ui->depIcao->setText(json["DEP"].toString());
ui->arrIcao->setText(json["ARR"].toString());
ui->alt1->setText(json["ARR"].toString());
ui->route->setPlainText(json["RTE"].toString());
ui->flightNo->setText(json["FLT"].toString());
ui->cruiseAlt->setText("FL"+json["CRZ"].toString());
ui->acIcao->setText(json["A/C"].toString());
ui->remarks->setPlainText("Data created by route2plane "+json["route2plane Version"].toString()+" on "+json["DATE"].toString()+" "+json["TIME"].toString());
ui->depTime->setText(QTime::currentTime().toString("hh:mm"));
ui->eet->setText("");
ui->tailNumber->setText("");
ui->pax->setText("");
ui->cargo->setText("");
//maybe later ... has to be changed also when data are loaded "on connect" and also if data are entered manually
//setWindowTitle("OAACARS ["+json["DEP"].toString()+">"+json["ARR"].toString()+"]");
}
}
}
void MainWindow::on_startButton_clicked()
{
qint64 tNow = time(NULL);
qint32 ret;
if (cur.time < tNow - 5 || cur.rref < tNow - 5) {
ret = QMessageBox::warning(this, "X-Plane Not Connected",
QString("I don't seem to be getting all the needed data from X-Plane.\nThis flight may not work properly.\n"
"Continue anyhow?"),
QMessageBox::Yes, QMessageBox::No);
if (ret == QMessageBox::No) return;
}
if (cur.agl > 20.0) {
ret = QMessageBox::warning(this, "High Ground AGL",
QString("Your AGL altitude of %1 seems a little too high.\nAre you sure you're on the ground?").arg(cur.agl),
QMessageBox::Yes, QMessageBox::No);
if (ret == QMessageBox::No) return;
}
groundAGL = cur.agl;
ui->depIcao->setText(ui->depIcao->text().toUpper());
QPair<double,double>* point = airports.get(ui->depIcao->text());
if (!point) {
ret = QMessageBox::critical(this, "Airport Not Found",
QString("Could not find the departure airport '%1' in the database.\n"
"Would you like to re-download the airports list?").arg(ui->depIcao->text()),
QMessageBox::Yes, QMessageBox::No);
if (ret == QMessageBox::Yes) airports.refresh();
return;
}
dep = *point;
ui->arrIcao->setText(ui->arrIcao->text().toUpper());
point = airports.get(ui->arrIcao->text());
if (!point) {
ret = QMessageBox::critical(this, "Airport Not Found",
QString("Could not find the destination airport '%1' in the database.\n"
"Would you like to re-download the airports list?").arg(ui->arrIcao->text()),
QMessageBox::Yes, QMessageBox::No);
if (ret == QMessageBox::Yes) airports.refresh();
return;
}
arr = *point;
double depDist = greatcircle(cur.lat, cur.lon, dep);
if (depDist > 10.0) {
ret = QMessageBox::warning(this, "Not At Departure Airport",
QString("Your distance of %1 nmi from the departure airport %2 seems a little too high.\n"
"Are you sure you're at the right place?").arg(depDist).arg(ui->depIcao->text()),
QMessageBox::Yes, QMessageBox::No);
if (ret == QMessageBox::No) return;
}
if (ui->applyWeight->isChecked()) {
float totalWeight = ui->pax->text().toFloat() * 80.0 + ui->cargo->text().toFloat();
setDRef(sock, "sim/flightmodel/weight/m_fixed", totalWeight);
}
// 2017222102431964OPA1115
// 2017-2-22 10:24:31.964 OPA1115
flight = QDateTime::currentDateTime().toString("yyyyMdhhmmsszzz")+ui->flightNo->text();
startTime = time(NULL);
startLat = cur.lat;
startLon = cur.lon;
trackId = eventId = 1;
critEvents = 0;
state = PREFLIGHT;
cur.flaps = 0;
cur.gear = 1;
for (int x = 0; x < 8; x++) cur.engine[x] = 0;
mistakes.reset();
newEvent("FLIGHT STARTED");
setDRef(sock, "oaacars/tracking", 1);
sendUpdate();
timer.start(60000);
ui->tabWidget->setCurrentWidget(ui->dataTab);
ui->startButton->setEnabled(false);
sRealTime->show();
sFlightTime->show();
}
void MainWindow::on_endButton_clicked()
{
double arrDist = greatcircle(cur.lat, cur.lon, arr);
if (arrDist > 10.0) {
qint32 ret = QMessageBox::warning(this, "Not At Arrival Airport",
QString("Your distance of %1 nmi from the arrival airport %2 seems a little too high.\n"
"Are you sure you're at the right place?").arg(arrDist).arg(ui->arrIcao->text()),
QMessageBox::Yes, QMessageBox::No);
if (ret == QMessageBox::No) return;
}
timer.stop();
ui->statusBar->showMessage("Submitting...");
QJsonObject msg;
msg["flightId"] = flight;
msg["weight_unit"] = "Lbs";
msg["departure"] = ui->depIcao->text();
msg["arrival"] = ui->arrIcao->text();
msg["gvauserId"] = QString::number(pilot);
msg["callsign"] = ui->flightNo->text();
msg["departure_time"] = ui->depTime->text();
msg["cruise_speed"] = ui->cruiseSpeed->text();
msg["flight_level"] = ui->cruiseAlt->text();
msg["pax"] = ui->pax->text();
msg["cargo"] = ui->cargo->text();
msg["eet"] = ui->eet->text();
msg["endurance"] = ui->endurance->text();
msg["alt1"] = ui->alt1->text();
msg["alt2"] = ui->alt2->text();
msg["route"] = ui->route->toPlainText();
msg["remarks"] = ui->remarks->toPlainText();
msg["flight_type"] = ui->flightType->currentText();
msg["aircraft"] = ui->aircraft->text();
msg["aircraft_type"] = ui->acIcao->text();
msg["aircraft_registry"] = ui->tailNumber->text();
msg["flight_status"] = "FLIGHT FINISHED";
msg["flight_duration"] = QString::number((onLanding.time-onTakeoff.time-onLanding.pauseTime) / 3600.0, 'f', 2);
msg["flight_fuel"] = QString::number(onTakeoff.fuel-onLanding.fuel, 'f', 0);
msg["block_fuel"] = QString::number(startFuel-cur.fuel, 'f', 0);
msg["final_fuel"] = QString::number(cur.fuel, 'f', 0);
msg["zfw"] = ui->zfw->text();
msg["flight_date"] = QDateTime::currentDateTime().toString("yyyy-M-d hh:mm:ss");
msg["distance"] = greatcircle(dep, arr);
msg["landing_vs"] = QString::number(onLanding.vs);
msg["landing_ias"] = QString::number(onLanding.ias);
msg["landing_forceg"] = QString::number(maxG);
msg["landing_bank"] = QString::number(onLanding.bank);
msg["landing_pitch"] = QString::number(onLanding.pitch);
msg["landing_hdg"] = QString::number(onLanding.heading);
msg["landing_winddeg"] = QString::number(onLanding.winddeg);
msg["landing_windknots"] = QString::number(onLanding.windknots);
msg["landing_oat"] = QString::number(onLanding.oat);
msg["landing_flaps"] = QString::number(onLanding.flaps);
msg["landing_light_bea"] = QString::number(onLanding.bea);
msg["landing_light_nav"] = QString::number(onLanding.nav);
msg["landing_light_ldn"] = QString::number(onLanding.ldn);
msg["landing_light_str"] = QString::number(onLanding.str);
msg["log_start"] = QDateTime::fromTime_t(startTime).toString("yyyy-M-d hh:mm:ss");
msg["flight_start"] = QDateTime::fromTime_t(onTakeoff.time).toString("yyyy-M-d hh:mm:ss");
msg["flight_end"] = QDateTime::fromTime_t(onLanding.time).toString("yyyy-M-d hh:mm:ss");
msg["log_end"] = QDateTime::currentDateTime().toString("yyyy-M-d hh:mm:ss");
msg["departure_metar"] = "";
msg["arrival_metar"] = "";
msg["network"] = "UNSUPPORTED";
msg["comments"] = "";
msg["pause_time"] = QString::number(onLanding.pauseTime, 'f', 1);
msg["crash"] = QString::number(mistakes.crash);
msg["beacon_off"] = QString::number(mistakes.beaconOff);
msg["ias_below_10000_ft"] = QString::number(mistakes.iasLow);
msg["lights_below_10000_ft"] = QString::number(mistakes.lightsLow);
msg["lights_above_10000_ft"] = QString::number(mistakes.lightsHigh);
msg["overspeed"] = QString::number(mistakes.overspeed);
msg["pause"] = QString::number(mistakes.pause);
msg["refuel"] = QString::number(mistakes.refuel);
msg["slew"] = QString::number(mistakes.slew);
msg["taxi_no_lights"] = QString::number(mistakes.taxiLights);
msg["takeoff_ldn_lights_off"] = QString::number(mistakes.takeoffLights);
msg["landing_ldn_lights_off"] = QString::number(mistakes.landingLights);
msg["landed_not_in_planned"] = QString::number(mistakes.landingAirport);
msg["stall"] = QString::number(mistakes.stall);
msg["taxi_speed"] = QString::number(mistakes.taxiSpeed);
msg["qnh_takeoff"] = QString::number(mistakes.qnhTakeoff);
msg["qnh_landing"] = QString::number(mistakes.qnhLanding);
QJsonArray ja;
ja.append(msg);
QJsonDocument json;
json.setArray(ja);
va.sendPirep(json);
va.sendEvents();
va.sendTracks();
setDRef(sock, "oaacars/tracking", 0);
state = OFFLINE;
startFuel = 0.0f;
startTime = 0;
maxG = 0.0f;
memset(&cur, 0, sizeof(cur));
onTakeoff = onLanding = cur;
ui->endButton->setEnabled(false);
ui->statusBar->clearMessage();
ui->statusBar->showMessage("Flight submitted.", 10000);
}
void MainWindow::on_callsign_textChanged(const QString &arg1)
{
QSettings settings("OAAE", "OAACARS", this);
settings.setValue("callsign", arg1);
}
void MainWindow::on_password_textChanged(const QString &arg1)
{
QSettings settings("OAAE", "OAACARS", this);
settings.setValue("password", arg1);
}
void MainWindow::on_applyWeight_stateChanged(int arg1)
{
QSettings settings("OAAE", "OAACARS", this);
settings.setValue("applyWeight", arg1);
}
static QTime conSimPressStart;
void MainWindow::on_conSim_pressed()
{
conSimPressStart = QTime::currentTime();
}
void MainWindow::on_conSim_released()
{
if (fabs(QTime::currentTime().msecsTo(conSimPressStart)) > 2000) {
IPDialog* ipd = new IPDialog(this);
ipd->show();
} else {
connectToSim();
}
}
void MainWindow::connectToSim() {
char buffer[1024];
char* pos = buffer;
memcat(&pos, "DSEL", 5);
memcat(&pos, 1); // times
memcat(&pos, 3); // speeds
memcat(&pos, 4); // Mach, VVI, G-load
memcat(&pos, 5); // atmosphere: weather
memcat(&pos, 6); // atmosphere: aircraft
memcat(&pos, 7); // system pressures
memcat(&pos, 13); // trim/flap/slat/s-brakes
memcat(&pos, 14); // gear/brakes
memcat(&pos, 17); // pitch, roll, headings
memcat(&pos, 20); // lat, lon, altitude
memcat(&pos, 21); // loc, vel, dist traveled
memcat(&pos, 45); // FF
memcat(&pos, 63); // payload weights and CG
memcat(&pos, 66); // landing gear vert force
memcat(&pos, 106); // switches 1: electrical
memcat(&pos, 114); // annunciators: general #2
memcat(&pos, 127); // warning status
sock->writeDatagram(buffer, (pos-buffer), remoteip, 49000);
char addr[16];
memset(addr, 0, 16);
strncpy(addr, myip.toString().toUtf8().data(), 16);
memset(buffer, 0, 1024);
pos = buffer;
memcat(&pos, "ISET", 5);
memcat(&pos, 64);
memcat(&pos, addr, 16);
memcat(&pos, "32123", 6); pos += 2;
memcat(&pos, 1);
sock->writeDatagram(buffer, (pos-buffer), remoteip, 49000);
sendDRef(sock, "sim/flightmodel/forces/fnrml_gear", 1);
}