-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathqtWeatherStations.cxx
601 lines (519 loc) · 18.1 KB
/
qtWeatherStations.cxx
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/*=========================================================================
Program: Visualization Toolkit
Module: vtkMap
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "qtWeatherStations.h"
#include "ui_qtWeatherStations.h"
#include "vtkGeoMapSelection.h"
#include "vtkMap.h"
#include "vtkMapMarkerSet.h"
#include "vtkOsmLayer.h"
#include <QVTKWidget.h>
#include <vtkCallbackCommand.h>
#include <vtkIdList.h>
#include <vtkInteractorStyleGeoMap.h>
#include <vtkNew.h>
#include <vtkObject.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <QAction>
#include <QCheckBox>
#include <QDebug>
#include <QMenu>
#include <QMessageBox>
#include <QPoint>
#include <QString>
#include <QVBoxLayout>
#include <curl/curl.h>
#include <sstream>
#include <stdlib.h> // for sprintf
namespace
{
// ------------------------------------------------------------
// [static] Handles callbacks from curl_easy_perform()
// Writes input buffer to stream (last argument)
size_t handle_curl_input(void* buffer, size_t size, size_t nmemb, void* stream)
{
(void) size;
//std::cout << "handle_input() nmemb: " << nmemb << std::endl
//std::cout << static_cast<char *>(buffer) << std::endl;
std::stringstream* ss = static_cast<std::stringstream*>(stream);
*ss << static_cast<char*>(buffer);
return nmemb;
}
} // namespace
// ------------------------------------------------------------
// Callback command for handling interactor mouse events
// In the future, will be replaced by interactor style
class MapCallback : public vtkCallbackCommand
{
public:
MapCallback(qtWeatherStations* app)
: App(app)
{
}
void Execute(vtkObject* caller, unsigned long eventId, void* data) override
{
(void) caller;
switch (eventId)
{
case vtkInteractorStyleGeoMap::SelectionCompleteEvent:
{
vtkObject* object = static_cast<vtkObject*>(data);
vtkGeoMapSelection* selection =
vtkGeoMapSelection::SafeDownCast(object);
this->App->displaySelectionInfo(selection);
}
break;
case vtkInteractorStyleGeoMap::RightButtonCompleteEvent:
{
int* mapDisplayCoords = static_cast<int*>(data);
// Convert to QWidget coords
// * VTK origin is bottom-left
// * Qt origin is top-right
// * Ignore widget margins for now
int* displaySize = this->App->getRenderer()->GetSize();
QPoint widgetCoords;
widgetCoords.setX(mapDisplayCoords[0]);
widgetCoords.setY(displaySize[1] - mapDisplayCoords[1]);
// Get global coords, used below to display context menu
QPoint globalCoords = this->App->mapWidget()->mapToGlobal(widgetCoords);
std::cout << "Right Mouse Event at map xy " << mapDisplayCoords[0]
<< "," << mapDisplayCoords[1] << ", widget xy "
<< widgetCoords.x() << "," << widgetCoords.y()
<< ", global xy " << globalCoords.x() << ","
<< globalCoords.y() << std::endl;
QMenu menu(this->App);
menu.addAction("Context Menu Goes Here");
menu.addSeparator();
menu.addAction("Action #1");
menu.addAction("Action #2");
menu.addAction("et cetera");
menu.exec(globalCoords);
}
break;
default:
std::cout << "Mouse event " << eventId << " "
<< vtkCommand::GetStringFromEventId(eventId) << std::endl;
break;
}
}
protected:
qtWeatherStations* App;
};
// ------------------------------------------------------------
qtWeatherStations::qtWeatherStations(QWidget* parent)
: QMainWindow(parent)
{
// Initialize Qt UI (generated from .ui file)
this->UI = new Ui_qtWeatherStations;
this->UI->setupUi(this);
// Manually set label invisible at startup
this->UI->RetrievingStationsLabel->setVisible(false);
// Initialize map widget
this->MapWidget = new QVTKWidget(this->UI->MapFrame);
this->MapWidget->resize(640, 480);
this->MapWidget->setSizePolicy(
QSizePolicy::Expanding, QSizePolicy::Expanding);
// Initialize Map instance
this->Map = vtkMap::New();
// Always set map's renderer *before* adding layers
this->Renderer = vtkRenderer::New();
this->Map->SetRenderer(this->Renderer);
vtkNew<vtkOsmLayer> osmLayer;
this->Map->AddLayer(osmLayer.GetPointer());
//this->resetMapCoords();
//this->Map->SetCenter(32.2, -90.9); // approx ERDC coords
double centerLatLon[2] = { 42.849604, -73.758345 }; // KHQ coords
int zoom = 5;
this->Map->SetCenter(centerLatLon);
this->Map->SetZoom(zoom);
this->UI->MapCoordinatesWidget->setCoordinates(centerLatLon, zoom);
// Initialize map marker set
vtkNew<vtkFeatureLayer> markerLayer;
markerLayer->SetName("markers");
this->Map->AddLayer(markerLayer.GetPointer());
this->MapMarkers = vtkMapMarkerSet::New();
this->MapMarkers->ClusteringOn();
markerLayer->AddFeature(this->MapMarkers);
vtkNew<vtkRenderWindow> mapRenderWindow;
mapRenderWindow->SetMultiSamples(0);
mapRenderWindow->AddRenderer(this->Renderer);
this->MapWidget->SetRenderWindow(mapRenderWindow.GetPointer());
vtkRenderWindowInteractor* intr = mapRenderWindow->GetInteractor();
this->Map->SetInteractor(intr);
intr->Initialize();
//intr->Start();
// Watch for selection callback from map
this->InteractorCallback = new MapCallback(this);
this->Map->AddObserver(
vtkInteractorStyleGeoMap::SelectionCompleteEvent, this->InteractorCallback);
this->Map->AddObserver(vtkInteractorStyleGeoMap::RightButtonCompleteEvent,
this->InteractorCallback);
// Connect UI controls
QObject::connect(
this->UI->MoveButton, SIGNAL(clicked()), this, SLOT(moveToCoords()));
QObject::connect(this->UI->UpdateCoordsWidgetButton, SIGNAL(clicked()), this,
SLOT(onUpdateCoordsWidget()));
QObject::connect(this->UI->ShowStationsButton, SIGNAL(clicked()), this,
SLOT(showStations()));
QObject::connect(this->UI->ClusteringCheckbox, SIGNAL(stateChanged(int)),
this, SLOT(toggleClustering(int)));
QObject::connect(this->UI->ClusterRecomputeButton, SIGNAL(clicked(bool)),
this, SLOT(recomputeClusters()));
QObject::connect(this->UI->ClusterDistanceSpinBox, SIGNAL(valueChanged(int)),
this, SLOT(onClusterDistanceChanged(int)));
// Initialize curl
curl_global_init(CURL_GLOBAL_DEFAULT);
}
// ------------------------------------------------------------
qtWeatherStations::~qtWeatherStations()
{
curl_global_cleanup();
if (this->Map)
{
this->Map->Delete();
}
if (this->MapMarkers)
{
this->MapMarkers->Delete();
}
if (this->Renderer)
{
this->Renderer->Delete();
}
if (this->InteractorCallback)
{
this->InteractorCallback->Delete();
}
delete this->UI;
}
// ------------------------------------------------------------
void qtWeatherStations::moveToCoords()
{
if (this->Map)
{
double center[2] = { 0.0, 0.0 };
int zoom = 1;
this->UI->MapCoordinatesWidget->getCoordinates(center, zoom);
// Set zoom first
this->Map->SetZoom(zoom);
this->Map->SetCenter(center);
this->updateMap();
this->drawMap();
}
}
// ------------------------------------------------------------
void qtWeatherStations::onUpdateCoordsWidget()
{
double center[2] = { 0.0, 0.0 };
this->Map->GetCenter(center);
int zoom = this->Map->GetZoom();
this->UI->MapCoordinatesWidget->setCoordinates(center, zoom);
}
// ------------------------------------------------------------
// Retrieves list of weather stations and displays on map
void qtWeatherStations::showStations()
{
this->UI->StationText->setFontFamily("Courier New");
// Clear out current station data
this->UI->StationText->clear();
this->UI->StationText->setText("Retrieving station data.");
// Todo is there any way to update StationText (QTextEdit) *now* ???
// remove old markers
// testing DeleteMarker
for (const auto& id : StationMap)
{
if (!this->MapMarkers->DeleteMarker(id.first))
{
std::cout << "Error: unable to delete marker "
<< id.first << std::endl;
}
}
//this->MapMarkers->DeleteAllMarkers();
this->StationMap.clear();
// Request weather station data
Json::Value json = this->RequestStationData();
if (json.isNull())
{
return;
}
std::vector<StationReport> stationList = this->ParseStationData(json);
this->DisplayStationData(stationList);
this->DisplayStationMarkers(stationList);
}
// ------------------------------------------------------------
void qtWeatherStations::toggleClustering(int checkboxState)
{
if (this->Map)
{
bool mapClusteringState = checkboxState == Qt::Checked;
this->MapMarkers->SetClustering(mapClusteringState);
//qDebug() << "toggle clustering to: " << mapClusteringState;
this->Map->Draw();
}
}
// ------------------------------------------------------------
void qtWeatherStations::onClusterDistanceChanged(int value)
{
// Enable "Recompute" button if distance has changed
int currentDistance = this->MapMarkers->GetClusterDistance();
bool enabled = value != currentDistance;
this->UI->ClusterRecomputeButton->setEnabled(enabled);
}
// ------------------------------------------------------------
void qtWeatherStations::recomputeClusters()
{
//qDebug() << "recompute clustering";
if (this->Map)
{
int distance = this->UI->ClusterDistanceSpinBox->value();
this->MapMarkers->SetClusterDistance(distance);
this->MapMarkers->RecomputeClusters();
this->Map->Draw();
this->UI->ClusterRecomputeButton->setEnabled(false);
}
}
// ------------------------------------------------------------
Json::Value qtWeatherStations::RequestStationData()
{
Json::Value json; // return value
std::stringstream ss;
// Get current map coordinates
double center[2];
this->Map->GetCenter(center);
int zoom = this->Map->GetZoom();
this->UI->MapCoordinatesWidget->setCoordinates(center, zoom);
double lat = center[0];
double lon = center[1];
ss << "Map coordinates (lat, lon) are"
<< " (" << lat << ", " << lon << ")"
", zoom "
<< zoom;
// Construct openweathermaps request
int count = this->UI->StationCountSpinBox->value();
const char* appId = "14cdc51cab181f8848f43497c58f1a96";
char url[256];
snprintf(url, 256, "http://api.openweathermap.org/data/2.5/find"
"?lat=%f&lon=%f&cnt=%d&units=imperial&APPID=%s",
lat, lon, count, appId);
std::cout << "url " << url << std::endl;
// Initialize curl & send request
CURL* curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, handle_curl_input);
std::stringstream curlStream;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &curlStream);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "wsmap");
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
//std::cout << "Start request" << std::endl;
// Use blocking IO for now
curl_easy_perform(curl);
//std::cout << "Request end, return value " << res << std::endl;
curl_easy_cleanup(curl);
// Parse input string (json)
curlStream.seekp(0L);
//std::string curlData = curlStream.str();
//std::cout << curlData << std::endl;
Json::Reader reader;
if (!reader.parse(curlStream, json, false))
{
ss << "\n"
<< "Error parsing input data - see console for more info.";
std::cerr << reader.getFormattedErrorMessages() << std::endl;
}
this->UI->StationText->append(QString::fromStdString(ss.str()));
//std::cout << "json.type() " << json.type() << std::endl;
//std::cout << json.asString() << std::endl;
return json;
}
// ------------------------------------------------------------
// Parses json object and returns list of station reports
std::vector<StationReport> qtWeatherStations::ParseStationData(Json::Value json)
{
std::vector<StationReport> stationList; // return value
Json::Value stationListNode = json["list"];
if (stationListNode.isNull())
{
return stationList;
}
for (int i = 0; i < int(stationListNode.size()); ++i)
{
StationReport station;
// Station ID & name
Json::Value stationNode = stationListNode[i];
Json::Value idNode = stationNode["id"];
station.id = idNode.asInt();
Json::Value nameNode = stationNode["name"];
station.name = nameNode.asString();
// Geo coords
Json::Value coordNode = stationNode["coord"];
Json::Value latNode = coordNode["lat"];
Json::Value lonNode = coordNode["lon"];
station.latitude = latNode.asDouble();
station.longitude = lonNode.asDouble();
// Datetime
Json::Value dtNode = stationNode["dt"];
station.datetime = time_t(dtNode.asInt()); // dt units are seconds
// Current temp
Json::Value mainNode = stationNode["main"];
Json::Value tempNode = mainNode["temp"];
station.temperature = tempNode.asDouble();
stationList.push_back(station);
}
return stationList;
}
// ------------------------------------------------------------
// Writes station info to StationText (QTextEdit)
void qtWeatherStations::DisplayStationData(
std::vector<StationReport> stationList)
{
std::stringstream ss;
for (size_t i = 0; i < stationList.size(); ++i)
{
StationReport station = stationList[i];
ss << std::setw(3) << i + 1 << ". " << station.id << " " << std::setw(20)
<< station.name
<< " " << std::setiosflags(std::ios_base::fixed) << std::setprecision(1)
<< station.temperature << "F"
<< " (" << std::setiosflags(std::ios_base::fixed)
<< std::setprecision(6) << station.latitude << " "
<< std::setiosflags(std::ios_base::fixed) << std::setprecision(6)
<< station.longitude << ")"
<< " " << ctime(&station.datetime);
}
this->UI->StationText->append(QString::fromStdString(ss.str()));
}
// ------------------------------------------------------------
// Updates display to show marker for each station in input list
// Updates internal Stations dictionary
void qtWeatherStations::DisplayStationMarkers(
std::vector<StationReport> stationList)
{
// Create map markers for each station
for (size_t i = 0; i < stationList.size(); ++i)
{
StationReport station = stationList[i];
vtkIdType id =
this->MapMarkers->AddMarker(station.latitude, station.longitude);
if (id >= 0)
this->StationMap[id] = station;
}
this->drawMap();
}
// ------------------------------------------------------------
// Calls map Draw() method
void qtWeatherStations::drawMap()
{
if (this->Map)
{
this->Map->Draw();
}
}
// ------------------------------------------------------------
// Calls map Update() method
void qtWeatherStations::updateMap()
{
if (this->Map)
{
// Call Map->Update to update marker display positions
this->Map->Update();
// Also update displayed lat/lon coords
double center[2];
this->Map->GetCenter(center);
//std::cout << "GetCenter " << center[0] << ", " << center[1] << std::endl;
int zoom = this->Map->GetZoom();
this->UI->MapCoordinatesWidget->setCoordinates(center, zoom);
}
}
// ------------------------------------------------------------
// Returns vtkRenderer
vtkRenderer* qtWeatherStations::getRenderer() const
{
return this->Renderer;
}
// ------------------------------------------------------------
void qtWeatherStations::displaySelectionInfo(
vtkGeoMapSelection* selection) const
{
vtkCollection* collection = selection->GetSelectedFeatures();
std::cout << "Selected collection size: " << collection->GetNumberOfItems()
<< std::endl;
if (collection->GetNumberOfItems() < 1)
{
return;
}
// Display "first" thing selected
vtkObject* firstObject = collection->GetItemAsObject(0);
vtkMapMarkerSet* markerSet = vtkMapMarkerSet::SafeDownCast(firstObject);
if (!markerSet)
{
std::cout << "First selected item type " << firstObject->GetClassName()
<< ", which was not expected." << std::endl;
return;
}
std::stringstream ss;
vtkNew<vtkIdList> markerIds;
vtkNew<vtkIdList> clusterIds;
selection->GetMapMarkerIds(
markerSet, markerIds.GetPointer(), clusterIds.GetPointer());
std::cout << "Selection marker count: " << markerIds->GetNumberOfIds()
<< ", cluster count " << clusterIds->GetNumberOfIds() << std::endl;
// Single marker case
if (markerIds->GetNumberOfIds() == 1)
{
vtkIdType markerId = markerIds->GetId(0);
std::map<vtkIdType, StationReport>::const_iterator stationIter =
this->StationMap.find(markerId);
if (stationIter != this->StationMap.end())
{
StationReport station = stationIter->second;
ss.str("");
ss << "Station: " << station.name << "\n"
<< "Current Temp: " << std::setiosflags(std::ios_base::fixed)
<< std::setprecision(1) << station.temperature << "F";
QMessageBox::information(
this->MapWidget, "Marker clicked", QString::fromStdString(ss.str()));
} // if (station)
} // if (1 marker)
// Single cluster case
if (clusterIds->GetNumberOfIds() == 1)
{
vtkIdType clusterId = clusterIds->GetId(0);
vtkNew<vtkIdList> allMarkerIds;
this->MapMarkers->GetAllMarkerIds(clusterId, allMarkerIds.GetPointer());
ss.str("");
ss << "Cluster of " << allMarkerIds->GetNumberOfIds() << " stations.";
QMessageBox::information(
this->MapWidget, "Cluster clicked", QString::fromStdString(ss.str()));
}
}
// ------------------------------------------------------------
QWidget* qtWeatherStations::mapWidget() const
{
return this->MapWidget;
}
// ------------------------------------------------------------
// Overrides base class method
void qtWeatherStations::resizeEvent(QResizeEvent* event)
{
QMainWindow::resizeEvent(event);
// Resize map widget if it's been initialized
if (this->MapWidget)
{
int margin = 4;
QSize sz = this->UI->MapFrame->size();
int w = sz.width() - 2 * margin;
int h = sz.height() - 2 * margin;
this->MapWidget->resize(w, h);
this->MapWidget->move(margin, margin);
this->drawMap();
}
}