NemoInterface.cpp 11.7 KB
Newer Older
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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
#include "NemoInterface.h"

#include "QGCApplication.h"
#include "QGCToolbox.h"
#include "SettingsFact.h"
#include "SettingsManager.h"
#include "WimaSettings.h"

#include <shared_mutex>

#include <QTimer>

#include "QNemoHeartbeat.h"
#include "QNemoProgress.h"

#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"
#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"

#define EVENT_TIMER_INTERVAL 100 // ms
auto static timeoutInterval = std::chrono::milliseconds(3000);

using ROSBridgePtr = std::unique_ptr<ros_bridge::ROSBridge>;
using JsonDocUPtr = ros_bridge::com_private::JsonDocUPtr;
using UniqueLock = std::unique_lock<std::shared_timed_mutex>;
using SharedLock = std::shared_lock<std::shared_timed_mutex>;
using JsonDocUPtr = ros_bridge::com_private::JsonDocUPtr;

class NemoInterface::Impl {
  using TimePoint = std::chrono::time_point<std::chrono::high_resolution_clock>;

public:
  Impl(NemoInterface *p);

  void start();
  void stop();
  void setTilesENU(const SnakeTilesLocal &tilesENU);
  void setENUOrigin(const QGeoCoordinate &ENUOrigin);
  NemoInterface::NemoStatus status();
  QVector<int> progress();

private:
  bool doTopicServiceSetup();
  void loop();
  //!
  //! \brief Publishes tilesENU
  //! \pre this->tilesENUMutex must be locked
  //!
  void publishTilesENU();
  //!
  //! \brief Publishes ENUOrigin
  //! \pre this->ENUOriginMutex must be locked
  //!
  void publishENUOrigin();

  // Data.
  SnakeTilesLocal tilesENU;
  mutable std::shared_timed_mutex tilesENUMutex;
  QGeoCoordinate ENUOrigin;
  mutable std::shared_timed_mutex ENUOriginMutex;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
66
  QNemoProgress qProgress;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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
  mutable std::shared_timed_mutex progressMutex;
  QNemoHeartbeat heartbeat;
  TimePoint nextTimeout;
  mutable std::shared_timed_mutex heartbeatMutex;

  // Internals
  bool running;
  std::atomic_bool topicServiceSetupDone;
  ROSBridgePtr pRosBridge;
  QTimer loopTimer;
  NemoInterface *parent;
};

NemoInterface::Impl::Impl(NemoInterface *p)
    : nextTimeout(TimePoint::max()), running(false),
      topicServiceSetupDone(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();

  // Periodic.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
108
  connect(&this->loopTimer, &QTimer::timeout, [this] { this->loop(); });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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
  this->loopTimer.start(EVENT_TIMER_INTERVAL);
}

void NemoInterface::Impl::start() { this->running = true; }

void NemoInterface::Impl::stop() { this->running = false; }

void NemoInterface::Impl::setTilesENU(const SnakeTilesLocal &tilesENU) {
  UniqueLock lk(this->tilesENUMutex);
  this->tilesENU = tilesENU;
  lk.unlock();
  if (this->running && this->topicServiceSetupDone) {
    lk.lock();
    this->publishTilesENU();
  }
}

void NemoInterface::Impl::setENUOrigin(const QGeoCoordinate &ENUOrigin) {
  UniqueLock lk(this->ENUOriginMutex);
  this->ENUOrigin = ENUOrigin;
  lk.unlock();
  if (this->running && this->topicServiceSetupDone) {
    lk.lock();
    this->publishENUOrigin();
  }
}

NemoInterface::NemoStatus NemoInterface::Impl::status() {
  SharedLock lk(this->heartbeatMutex);
  return NemoInterface::NemoStatus(heartbeat.status());
}

QVector<int> NemoInterface::Impl::progress() {
  SharedLock lk(this->progressMutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
143
  return this->qProgress.progress();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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
}

bool NemoInterface::Impl::doTopicServiceSetup() {
  using namespace ros_bridge::messages;

  // Publish snake tiles.
  {
    SharedLock lk(this->tilesENUMutex);

    if (this->tilesENU.polygons().size() == 0)
      return false;
    this->pRosBridge->advertiseTopic(
        "/snake/tiles",
        jsk_recognition_msgs::polygon_array::messageType().c_str());
    this->publishTilesENU();
  }

  // Publish snake origin.
  {
    SharedLock lk(this->ENUOriginMutex);

    this->pRosBridge->advertiseTopic(
        "/snake/origin", geographic_msgs::geo_point::messageType().c_str());
    this->publishENUOrigin();
  }

  // Subscribe nemo progress.
  this->pRosBridge->subscribe(
      "/nemo/progress",
      /* callback */ [this](JsonDocUPtr pDoc) {
        std::lock(this->progressMutex, this->tilesENUMutex,
                  this->ENUOriginMutex);
        UniqueLock lk1(this->progressMutex, std::adopt_lock);
        UniqueLock lk2(this->tilesENUMutex, std::adopt_lock);
        UniqueLock lk3(this->ENUOriginMutex, std::adopt_lock);

        int requiredSize = this->tilesENU.polygons().size();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
181
        auto &progressMsg = this->qProgress;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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
        if (!nemo_msgs::progress::fromJson(*pDoc, progressMsg) ||
            progressMsg.progress().size() !=
                requiredSize) { // Some error occured.
          progressMsg.progress().clear();

          // 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");
        }
        lk1.unlock();
        lk2.unlock();
        lk3.unlock();

Valentin Platzgummer's avatar
Valentin Platzgummer committed
209
        emit this->parent->progressChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
210 211 212 213 214 215
      });

  // Subscribe /nemo/heartbeat.
  this->pRosBridge->subscribe(
      "/nemo/heartbeat",
      /* callback */ [this](JsonDocUPtr pDoc) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
216
        //        auto start = std::chrono::high_resolution_clock::now();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
217 218 219 220 221 222 223 224 225 226
        UniqueLock lk(this->heartbeatMutex);

        auto &heartbeatMsg = this->heartbeat;
        if (!nemo_msgs::heartbeat::fromJson(*pDoc, heartbeatMsg)) {
          heartbeatMsg.setStatus(integral(NemoStatus::InvalidHeartbeat));
          this->nextTimeout = TimePoint::max();
        } else {
          this->nextTimeout =
              std::chrono::high_resolution_clock::now() + timeoutInterval;
        }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
227
        lk.unlock();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
228

Valentin Platzgummer's avatar
Valentin Platzgummer committed
229
        emit this->parent->statusChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
230 231 232 233 234 235
        //        auto delta =
        //        std::chrono::duration_cast<std::chrono::milliseconds>(
        //            std::chrono::high_resolution_clock::now() - start);
        //        std::cout << "/nemo/heartbeat callback time: " <<
        //        delta.count() << " ms"
        //                  << std::endl;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
236 237 238 239 240 241 242
      });

  // Advertise /snake/get_origin.
  this->pRosBridge->advertiseService(
      "/snake/get_origin", "snake_msgs/GetOrigin",
      [this](JsonDocUPtr) -> JsonDocUPtr {
        using namespace ros_bridge::messages;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
243
        SharedLock lk(this->ENUOriginMutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

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

  // Advertise /snake/get_tiles.
  this->pRosBridge->advertiseService(
      "/snake/get_tiles", "snake_msgs/GetTiles",
      [this](JsonDocUPtr) -> JsonDocUPtr {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
262
        SharedLock lk(this->tilesENUMutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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

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

  return true;
}

void NemoInterface::Impl::loop() {

  // Check ROS Bridge status and do setup if necessary.
  if (this->running) {
    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;
  }

  // Check if heartbeat timeout occured.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
300 301 302 303
  if (this->running && this->topicServiceSetupDone) {
    UniqueLock lk(this->heartbeatMutex);
    if (this->nextTimeout != TimePoint::max() &&
        this->nextTimeout < std::chrono::high_resolution_clock::now()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
304
      this->heartbeat.setStatus(integral(NemoStatus::Timeout));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
305
      lk.unlock();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
306 307 308 309 310 311
      emit this->parent->statusChanged();
    }
  }
}

void NemoInterface::Impl::publishTilesENU() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
312
  using namespace ros_bridge::messages;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
313 314
  JsonDocUPtr jSnakeTiles(
      std::make_unique<rapidjson::Document>(rapidjson::kObjectType));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
315
  bool ret = jsk_recognition_msgs::polygon_array::toJson(
Valentin Platzgummer's avatar
Valentin Platzgummer committed
316 317 318 319 320 321 322
      this->tilesENU, *jSnakeTiles, jSnakeTiles->GetAllocator());
  Q_ASSERT(ret);
  (void)ret;
  this->pRosBridge->publish(std::move(jSnakeTiles), "/snake/tiles");
}

void NemoInterface::Impl::publishENUOrigin() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
323
  using namespace ros_bridge::messages;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
324 325 326 327 328 329 330 331 332
  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");
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
333 334 335 336 337 338 339
// ===============================================================
// NemoInterface
NemoInterface::NemoInterface(QObject *parent)
    : QObject(parent), pImpl(std::make_unique<NemoInterface::Impl>(this)) {}

NemoInterface::~NemoInterface() {}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
340 341 342 343 344 345 346 347 348 349 350 351
void NemoInterface::start() { this->pImpl->start(); }

void NemoInterface::stop() { this->pImpl->stop(); }

void NemoInterface::setTilesENU(const SnakeTilesLocal &tilesENU) {
  this->pImpl->setTilesENU(tilesENU);
}

void NemoInterface::setENUOrigin(const QGeoCoordinate &ENUOrigin) {
  this->pImpl->setENUOrigin(ENUOrigin);
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
352
NemoInterface::NemoStatus NemoInterface::status() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
353 354 355
  return this->pImpl->status();
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
356
QVector<int> NemoInterface::progress() const { return this->pImpl->progress(); }