SnakeDataManager.cc 18.9 KB
Newer Older
1 2 3 4 5 6 7 8
#include "SnakeDataManager.h"

#include <QGeoCoordinate>
#include <QMutexLocker>

#include "QGCApplication.h"
#include "QGCToolbox.h"
#include "SettingsFact.h"
9 10
#include "SettingsManager.h"
#include "WimaSettings.h"
11 12 13

#include <memory>
#include <mutex>
14
#include <shared_mutex>
15 16 17

#include "Wima/Snake/SnakeTiles.h"
#include "Wima/Snake/SnakeTilesLocal.h"
18
#include "snake.h"
19

20 21 22
#include "ros_bridge/include/messages/geographic_msgs/geopoint.h"
#include "ros_bridge/include/messages/jsk_recognition_msgs/polygon_array.h"
#include "ros_bridge/include/messages/nemo_msgs/heartbeat.h"
23 24 25 26 27
#include "ros_bridge/include/messages/nemo_msgs/progress.h"
#include "ros_bridge/include/ros_bridge.h"
#include "ros_bridge/rapidjson/include/rapidjson/document.h"
#include "ros_bridge/rapidjson/include/rapidjson/ostreamwrapper.h"
#include "ros_bridge/rapidjson/include/rapidjson/writer.h"
28 29

#define EVENT_TIMER_INTERVAL 500 // ms
30
#define TIMEOUT 3000             // ms
31 32 33 34 35 36

using QVariantList = QList<QVariant>;
using ROSBridgePtr = std::unique_ptr<ros_bridge::ROSBridge>;

using UniqueLock = std::unique_lock<shared_timed_mutex>;
using SharedLock = std::shared_lock<shared_timed_mutex>;
37
using JsonDocUPtr = ros_bridge::com_private::JsonDocUPtr;
38

39
class SnakeDataManager::SnakeImpl {
40
public:
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
  SnakeImpl(SnakeDataManager *p)
      : rosBridgeEnabeled(false), topicServiceSetupDone(false),
        lineDistance(1 * si::meter), minTransectLength(1 * si::meter),
        calcInProgress(false), parent(p) {
    // ROS Bridge.
    WimaSettings *wimaSettings =
        qgcApp()->toolbox()->settingsManager()->wimaSettings();
    auto connectionStringFact = wimaSettings->rosbridgeConnectionString();
    auto setConnectionString = [connectionStringFact, this] {
      auto connectionString = connectionStringFact->rawValue().toString();
      if (ros_bridge::isValidConnectionString(
              connectionString.toLocal8Bit().data())) {
        this->pRosBridge.reset(
            new ros_bridge::ROSBridge(connectionString.toLocal8Bit().data()));
      } else {
        QString defaultString("localhost:9090");
        qgcApp()->showMessage("ROS Bridge connection string invalid: " +
                              connectionString);
        qgcApp()->showMessage("Resetting connection string to: " +
                              defaultString);
        connectionStringFact->setRawValue(
            QVariant(defaultString)); // calls this function recursively
      }
    };
    connect(connectionStringFact, &SettingsFact::rawValueChanged,
            setConnectionString);
    setConnectionString();
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
    // Periodic.
    connect(&this->eventTimer, &QTimer::timeout, [this] {
      if (this->rosBridgeEnabeled) {
        if (!this->pRosBridge->isRunning()) {
          this->pRosBridge->start();
        } else if (this->pRosBridge->isRunning() &&
                   this->pRosBridge->connected() &&
                   !this->topicServiceSetupDone) {
          if (this->doTopicServiceSetup())
            this->topicServiceSetupDone = true;
        } else if (this->pRosBridge->isRunning() &&
                   !this->pRosBridge->connected() &&
                   this->topicServiceSetupDone) {
          this->pRosBridge->reset();
          this->pRosBridge->start();
          this->topicServiceSetupDone = false;
        }
      } else if (this->pRosBridge->isRunning()) {
        this->pRosBridge->reset();
        this->topicServiceSetupDone = false;
      }
    });
    this->eventTimer.start(EVENT_TIMER_INTERVAL);
  }

  bool precondition() const;
  void resetOutput();
  bool doTopicServiceSetup();

  // Private data.
  ROSBridgePtr pRosBridge;
  bool rosBridgeEnabeled;
  bool topicServiceSetupDone;
  QTimer eventTimer;
  QTimer timeout;
  mutable std::shared_timed_mutex mutex;

  // Scenario
  snake::Scenario scenario;
  Length lineDistance;
  Length minTransectLength;
  QList<QGeoCoordinate> mArea;
  QList<QGeoCoordinate> sArea;
  QList<QGeoCoordinate> corridor;
  QGeoCoordinate ENUOrigin;
  SnakeTiles tiles;
  QmlObjectListModel tilesQml;
  QVariantList tileCenterPoints;
  SnakeTilesLocal tilesENU;
  QVector<QPointF> tileCenterPointsENU;

  // Waypoints
  QVector<QGeoCoordinate> waypoints;
  QVector<QGeoCoordinate> arrivalPath;
  QVector<QGeoCoordinate> returnPath;
  QVector<QPointF> waypointsENU;
  QVector<QPointF> arrivalPathENU;
  QVector<QPointF> returnPathENU;
  QString errorMessage;

  // Other
  std::atomic_bool calcInProgress;
  QNemoProgress qProgress;
  std::vector<int> progress;
  QNemoHeartbeat heartbeat;
  SnakeDataManager *parent;
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
bool SnakeDataManager::SnakeImpl::doTopicServiceSetup() {
  using namespace ros_bridge::messages;
  UniqueLock lk(this->mutex);

  if (this->tilesENU.polygons().size() == 0)
    return false;

  // Publish snake origin.
  this->pRosBridge->advertiseTopic(
      "/snake/origin", geographic_msgs::geo_point::messageType().c_str());
  JsonDocUPtr jOrigin(
      std::make_unique<rapidjson::Document>(rapidjson::kObjectType));
  bool ret = geographic_msgs::geo_point::toJson(this->ENUOrigin, *jOrigin,
                                                jOrigin->GetAllocator());
  Q_ASSERT(ret);
  (void)ret;
  this->pRosBridge->publish(std::move(jOrigin), "/snake/origin");

  // Publish snake tiles.
  this->pRosBridge->advertiseTopic(
      "/snake/tiles",
      jsk_recognition_msgs::polygon_array::messageType().c_str());
  JsonDocUPtr jSnakeTiles(
      std::make_unique<rapidjson::Document>(rapidjson::kObjectType));
  ret = jsk_recognition_msgs::polygon_array::toJson(
      this->tilesENU, *jSnakeTiles, jSnakeTiles->GetAllocator());
  Q_ASSERT(ret);
  (void)ret;
  this->pRosBridge->publish(std::move(jSnakeTiles), "/snake/tiles");

  // Subscribe nemo progress.
  this->pRosBridge->subscribe(
      "/nemo/progress",
      /* callback */ [this](JsonDocUPtr pDoc) {
        UniqueLock lk(this->mutex);
        int requiredSize = this->tilesENU.polygons().size();
        auto &progressMsg = this->qProgress;
        if (!nemo_msgs::progress::fromJson(*pDoc, progressMsg) ||
            progressMsg.progress().size() !=
                requiredSize) { // Some error occured.
          // Set progress to default.
          progressMsg.progress().fill(0, requiredSize);

          // Publish snake origin.
          JsonDocUPtr jOrigin(
              std::make_unique<rapidjson::Document>(rapidjson::kObjectType));
          bool ret = geographic_msgs::geo_point::toJson(
              this->ENUOrigin, *jOrigin, jOrigin->GetAllocator());
          Q_ASSERT(ret);
          (void)ret;
          this->pRosBridge->publish(std::move(jOrigin), "/snake/origin");

          // Publish snake tiles.
          JsonDocUPtr jSnakeTiles(
              std::make_unique<rapidjson::Document>(rapidjson::kObjectType));
          ret = jsk_recognition_msgs::polygon_array::toJson(
              this->tilesENU, *jSnakeTiles, jSnakeTiles->GetAllocator());
          Q_ASSERT(ret);
          (void)ret;
          this->pRosBridge->publish(std::move(jSnakeTiles), "/snake/tiles");
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
        this->progress.clear();
        for (const auto &p : progressMsg.progress()) {
          this->progress.push_back(p);
        }
        lk.unlock();

        emit this->parent->nemoProgressChanged();
      });

  // Subscribe /nemo/heartbeat.
  this->pRosBridge->subscribe(
      "/nemo/heartbeat",
      /* callback */ [this](JsonDocUPtr pDoc) {
        UniqueLock lk(this->mutex);
        if (this->timeout.isActive()) {
          this->timeout.stop();
        }
        auto &heartbeatMsg = this->heartbeat;
        if (!nemo_msgs::heartbeat::fromJson(*pDoc, heartbeatMsg)) {
          heartbeatMsg.setStatus(integral(NemoStatus::InvalidHeartbeat));
        }
        this->timeout.singleShot(TIMEOUT, [this] {
          UniqueLock lk(this->mutex);
          this->heartbeat.setStatus(integral(NemoStatus::Timeout));
          emit this->parent->nemoStatusChanged(integral(NemoStatus::Timeout));
        });
        emit this->parent->nemoStatusChanged(heartbeatMsg.status());
      });
226

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
  // Advertise /snake/get_origin.
  this->pRosBridge->advertiseService(
      "/snake/get_origin", "snake_msgs/GetOrigin",
      [this](JsonDocUPtr) -> JsonDocUPtr {
        using namespace ros_bridge::messages;
        SharedLock lk(this->mutex);

        JsonDocUPtr pDoc(
            std::make_unique<rapidjson::Document>(rapidjson::kObjectType));
        auto &origin = this->ENUOrigin;
        rapidjson::Value jOrigin(rapidjson::kObjectType);
        bool ret = geographic_msgs::geo_point::toJson(origin, jOrigin,
                                                      pDoc->GetAllocator());
        lk.unlock();
        Q_ASSERT(ret);
        (void)ret;
        pDoc->AddMember("origin", jOrigin, pDoc->GetAllocator());
        return pDoc;
      });
246

247 248 249 250 251
  // Advertise /snake/get_tiles.
  this->pRosBridge->advertiseService(
      "/snake/get_tiles", "snake_msgs/GetTiles",
      [this](JsonDocUPtr) -> JsonDocUPtr {
        SharedLock lk(this->mutex);
252

253 254 255 256 257 258 259 260 261 262
        JsonDocUPtr pDoc(
            std::make_unique<rapidjson::Document>(rapidjson::kObjectType));
        rapidjson::Value jSnakeTiles(rapidjson::kObjectType);
        bool ret = jsk_recognition_msgs::polygon_array::toJson(
            this->tilesENU, jSnakeTiles, pDoc->GetAllocator());
        Q_ASSERT(ret);
        (void)ret;
        pDoc->AddMember("tiles", jSnakeTiles, pDoc->GetAllocator());
        return pDoc;
      });
263

264
  return true;
265 266
}

267
bool SnakeDataManager::SnakeImpl::precondition() const { return true; }
268

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
//!
//! \brief Resets waypoint data.
//! \pre this->_pImpl->mutex must be locked.
void SnakeDataManager::SnakeImpl::resetOutput() {
  this->waypoints.clear();
  this->arrivalPath.clear();
  this->returnPath.clear();
  this->ENUOrigin = QGeoCoordinate(0.0, 0.0, 0.0);
  this->waypointsENU.clear();
  this->arrivalPathENU.clear();
  this->returnPathENU.clear();
  this->tilesQml.clearAndDeleteContents();
  this->tiles.polygons().clear();
  this->tileCenterPoints.clear();
  this->tilesENU.polygons().clear();
  this->tileCenterPointsENU.clear();
  this->errorMessage.clear();
286 287
}

288 289 290 291 292
template <class Callable> class CommandRAII {
public:
  CommandRAII(Callable &fun) : _fun(fun) {}

  ~CommandRAII() { _fun(); }
293

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
private:
  Callable _fun;
};

SnakeDataManager::SnakeDataManager(QObject *parent)
    : QThread(parent), pImpl(std::make_unique<SnakeImpl>(this))

{}

SnakeDataManager::~SnakeDataManager() {}

void SnakeDataManager::setMeasurementArea(
    const QList<QGeoCoordinate> &measurementArea) {
  UniqueLock lk(this->pImpl->mutex);
  this->pImpl->mArea = measurementArea;
309 310
}

311 312 313 314
void SnakeDataManager::setServiceArea(
    const QList<QGeoCoordinate> &serviceArea) {
  UniqueLock lk(this->pImpl->mutex);
  this->pImpl->sArea = serviceArea;
315 316
}

317 318 319
void SnakeDataManager::setCorridor(const QList<QGeoCoordinate> &corridor) {
  UniqueLock lk(this->pImpl->mutex);
  this->pImpl->corridor = corridor;
320 321
}

322 323 324
const QmlObjectListModel *SnakeDataManager::tiles() const {
  SharedLock lk(this->pImpl->mutex);
  return &this->pImpl->tilesQml;
325 326
}

327 328 329
QVariantList SnakeDataManager::tileCenterPoints() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->tileCenterPoints;
330 331
}

332 333 334
QNemoProgress SnakeDataManager::nemoProgress() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->qProgress;
335 336
}

337 338 339
int SnakeDataManager::nemoStatus() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->heartbeat.status();
340 341
}

342 343 344
bool SnakeDataManager::calcInProgress() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->calcInProgress.load();
345 346
}

347 348 349
QString SnakeDataManager::errorMessage() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->errorMessage;
350 351
}

352 353 354
bool SnakeDataManager::success() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->errorMessage.isEmpty() ? true : false;
355 356
}

357 358 359
QVector<QGeoCoordinate> SnakeDataManager::waypoints() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->waypoints;
360 361
}

362 363 364
QVector<QGeoCoordinate> SnakeDataManager::arrivalPath() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->arrivalPath;
365 366
}

367 368 369
QVector<QGeoCoordinate> SnakeDataManager::returnPath() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->returnPath;
370 371
}

372 373 374
Length SnakeDataManager::lineDistance() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->lineDistance;
375 376
}

377 378 379
void SnakeDataManager::setLineDistance(Length lineDistance) {
  UniqueLock lk(this->pImpl->mutex);
  this->pImpl->lineDistance = lineDistance;
380 381
}

382 383 384
Area SnakeDataManager::minTileArea() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->scenario.minTileArea();
385 386
}

387 388 389
void SnakeDataManager::setMinTileArea(Area minTileArea) {
  UniqueLock lk(this->pImpl->mutex);
  this->pImpl->scenario.setMinTileArea(minTileArea);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
390 391
}

392 393 394 395
Length SnakeDataManager::tileHeight() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->scenario.tileHeight();
}
396

397 398 399 400
void SnakeDataManager::setTileHeight(Length tileHeight) {
  UniqueLock lk(this->pImpl->mutex);
  this->pImpl->scenario.setTileHeight(tileHeight);
}
401

402 403 404 405
Length SnakeDataManager::tileWidth() const {
  SharedLock lk(this->pImpl->mutex);
  return this->pImpl->scenario.tileWidth();
}
406

407 408 409 410
void SnakeDataManager::setTileWidth(Length tileWidth) {
  UniqueLock lk(this->pImpl->mutex);
  this->pImpl->scenario.setTileWidth(tileWidth);
}
411

412 413 414
void SnakeDataManager::enableRosBridge() {
  this->pImpl->rosBridgeEnabeled = true;
}
415

416 417 418
void SnakeDataManager::disableRosBride() {
  this->pImpl->rosBridgeEnabeled = false;
}
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
void SnakeDataManager::run() {
  this->pImpl->calcInProgress.store(true);
  emit calcInProgressChanged(this->pImpl->calcInProgress.load());
  auto onExit = [this] {
    this->pImpl->calcInProgress.store(false);
    emit calcInProgressChanged(this->pImpl->calcInProgress.load());
  };
  CommandRAII<decltype(onExit)> onExitRAII(onExit);

  UniqueLock lk(this->pImpl->mutex);
  this->pImpl->resetOutput();

  if (!this->pImpl->precondition())
    return;

  if (this->pImpl->mArea.size() < 3) {
    this->pImpl->errorMessage = "Measurement area invalid: size < 3.";
    return;
  }
  if (this->pImpl->sArea.size() < 3) {
    this->pImpl->errorMessage = "Service area invalid: size < 3.";
    return;
  }

  this->pImpl->ENUOrigin = this->pImpl->mArea.front();
  auto &origin = this->pImpl->ENUOrigin;
  // Update measurement area.
  auto &mAreaEnu = this->pImpl->scenario.measurementArea();
  auto &mArea = this->pImpl->mArea;
  mAreaEnu.clear();
  for (auto geoVertex : mArea) {
    snake::BoostPoint p;
    snake::toENU(origin, geoVertex, p);
    mAreaEnu.outer().push_back(p);
  }

  // Update service area.
  auto &sAreaEnu = this->pImpl->scenario.serviceArea();
  auto &sArea = this->pImpl->sArea;
  sAreaEnu.clear();
  for (auto geoVertex : sArea) {
    snake::BoostPoint p;
    snake::toENU(origin, geoVertex, p);
    sAreaEnu.outer().push_back(p);
  }

  // Update corridor.
  auto &corridorEnu = this->pImpl->scenario.corridor();
  auto &corridor = this->pImpl->corridor;
  corridor.clear();
  for (auto geoVertex : corridor) {
    snake::BoostPoint p;
    snake::toENU(origin, geoVertex, p);
    corridorEnu.outer().push_back(p);
  }

  if (!this->pImpl->scenario.update()) {
    this->pImpl->errorMessage = this->pImpl->scenario.errorString.c_str();
    return;
  }

  // Asynchronously update flightplan.
  std::string errorString;
  auto future = std::async([this, &errorString, &origin] {
    snake::Angle alpha(-this->pImpl->scenario.mAreaBoundingBox().angle *
                       degree::degree);
    snake::flight_plan::Transects transects;
    transects.push_back(bg::model::linestring<snake::BoostPoint>{
        this->pImpl->scenario.homePositon()});
    bool value = snake::flight_plan::transectsFromScenario(
        this->pImpl->lineDistance, this->pImpl->minTransectLength, alpha,
        this->pImpl->scenario, this->pImpl->progress, transects, errorString);
    if (!value) {
      this->pImpl->errorMessage = "Not able to generate transects.";
      return value;
495
    }
496 497 498 499 500 501 502 503
    snake::flight_plan::Transects transectsRouted;
    snake::flight_plan::Route route;
    value =
        snake::flight_plan::route(this->pImpl->scenario.joinedArea(), transects,
                                  transectsRouted, route, errorString);
    if (!value) {
      this->pImpl->errorMessage = "Routing error.";
      return value;
504 505
    }

506 507 508 509 510 511 512 513 514 515 516 517 518 519
    // Store arrival path.
    const auto &firstWaypoint = transectsRouted.front().front();
    long startIdx = 0;
    for (long i = 0; i < long(route.size()); ++i) {
      const auto &boostVertex = route[i];
      if (boostVertex == firstWaypoint) {
        startIdx = i;
        break;
      }
      QPointF enuVertex{boostVertex.get<0>(), boostVertex.get<1>()};
      QGeoCoordinate geoVertex;
      snake::fromENU(origin, boostVertex, geoVertex);
      this->pImpl->arrivalPathENU.push_back(enuVertex);
      this->pImpl->arrivalPath.push_back(geoVertex);
520
    }
521 522 523 524 525 526 527 528 529 530 531 532 533 534
    // Store return path.
    long endIdx = 0;
    const auto &lastWaypoint = transectsRouted.back().back();
    for (long i = route.size() - 1; i >= 0; --i) {
      const auto &boostVertex = route[i];
      if (boostVertex == lastWaypoint) {
        endIdx = i;
        break;
      }
      QPointF enuVertex{boostVertex.get<0>(), boostVertex.get<1>()};
      QGeoCoordinate geoVertex;
      snake::fromENU(origin, boostVertex, geoVertex);
      this->pImpl->returnPathENU.push_back(enuVertex);
      this->pImpl->returnPath.push_back(geoVertex);
535
    }
536 537 538 539 540 541 542 543
    // Store waypoints.
    for (long i = startIdx; i <= endIdx; ++i) {
      const auto &boostVertex = route[i];
      QPointF enuVertex{boostVertex.get<0>(), boostVertex.get<1>()};
      QGeoCoordinate geoVertex;
      snake::fromENU(origin, boostVertex, geoVertex);
      this->pImpl->waypointsENU.push_back(enuVertex);
      this->pImpl->waypoints.push_back(geoVertex);
544
    }
545 546

    return true;
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
  });

  // Continue with storing scenario data in the mean time.
  {
    // Get tiles.
    const auto &tiles = this->pImpl->scenario.tiles();
    const auto &centerPoints = this->pImpl->scenario.tileCenterPoints();
    for (unsigned int i = 0; i < tiles.size(); ++i) {
      const auto &tile = tiles[i];
      SnakeTile geoTile;
      SnakeTileLocal enuTile;
      for (size_t i = tile.outer().size(); i < tile.outer().size() - 1; ++i) {
        auto &p = tile.outer()[i];
        QPointF enuVertex(p.get<0>(), p.get<1>());
        QGeoCoordinate geoVertex;
        snake::fromENU(origin, p, geoVertex);
        enuTile.polygon().points().push_back(enuVertex);
        geoTile.push_back(geoVertex);
      }
      const auto &boostPoint = centerPoints[i];
      QPointF enuVertex(boostPoint.get<0>(), boostPoint.get<1>());
      QGeoCoordinate geoVertex;
      snake::fromENU(origin, boostPoint, geoVertex);
      geoTile.setCenter(geoVertex);
      this->pImpl->tilesQml.append(new SnakeTile(geoTile));
      this->pImpl->tiles.polygons().push_back(geoTile);
      this->pImpl->tileCenterPoints.push_back(QVariant::fromValue(geoVertex));
      this->pImpl->tilesENU.polygons().push_back(enuTile);
      this->pImpl->tileCenterPointsENU.push_back(enuVertex);
    }
  }

  future.wait();
  // Trying to generate flight plan.
  if (!future.get()) {
    // error
    this->pImpl->errorMessage = errorString.c_str();
  } else {
    // Success!!!
  }
587
}