NemoInterface.cpp 40.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#include "NemoInterface.h"

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

#include <shared_mutex>

#include <QTimer>

14
#include "GenericSingelton.h"
15
#include "geometry/MeasurementArea.h"
16
#include "geometry/geometry.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
17
#include "nemo_interface/FutureWatcher.h"
18
#include "nemo_interface/MeasurementTile.h"
19
#include "nemo_interface/QNemoHeartbeat.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
20 21 22
#include "nemo_interface/TaskDispatcher.h"

#include "ros_bridge/include/messages/nemo_msgs/progress_array.h"
23

Valentin Platzgummer's avatar
Valentin Platzgummer committed
24
#include "ros_bridge/include/RosBridgeClient.h"
25 26
#include "ros_bridge/include/messages/geographic_msgs/geopoint.h"
#include "ros_bridge/include/messages/nemo_msgs/heartbeat.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
27
#include "ros_bridge/include/messages/nemo_msgs/tile.h"
28 29 30 31 32 33 34
#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"

QGC_LOGGING_CATEGORY(NemoInterfaceLog, "NemoInterfaceLog")

Valentin Platzgummer's avatar
Valentin Platzgummer committed
35 36 37 38
#define SYNC_INTERVAL 1000             // ms
#define NO_HEARTBEAT_TIMEOUT 10000     // ms
#define CONNECTION_TIMER_INTERVAL 1000 // ms
static constexpr auto maxResponseTime = std::chrono::milliseconds(10000);
39

Valentin Platzgummer's avatar
Valentin Platzgummer committed
40
using hrc = std::chrono::high_resolution_clock;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
41
using ROSBridgePtr = std::shared_ptr<RosbridgeWsClient>;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
42 43 44 45 46 47 48 49 50 51

typedef ros_bridge::messages::nemo_msgs::tile::GenericTile<QGeoCoordinate,
                                                           QList>
    Tile;
typedef std::map<std::int64_t, std::shared_ptr<Tile>> TileMap;
typedef std::map<std::int64_t, std::shared_ptr<const Tile>> TileMapConst;
typedef ros_bridge::messages::nemo_msgs::heartbeat::Heartbeat Heartbeat;
typedef nemo_interface::TaskDispatcher Dispatcher;
typedef nemo_interface::FutureWatcher<QVariant, std::shared_future>
    FutureWatcher;
52 53

class NemoInterface::Impl {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
54 55
  enum class STATE {
    STOPPED,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
56
    START_BRIDGE,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
57 58
    WEBSOCKET_DETECTED,
    TRY_TOPIC_SERVICE_SETUP,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
59 60
    SYNC_USER,
    SYNC_SYS,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
61
    READY,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
62 63
    WEBSOCKET_TIMEOUT,
    HEARTBEAT_TIMEOUT
Valentin Platzgummer's avatar
Valentin Platzgummer committed
64
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
65

Valentin Platzgummer's avatar
Valentin Platzgummer committed
66
public:
67
  Impl(NemoInterface *p);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
68
  ~Impl();
69 70 71 72

  void start();
  void stop();

Valentin Platzgummer's avatar
Valentin Platzgummer committed
73 74
  // Tile editing.
  // 	Functions that require communication to device.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
75 76 77
  std::shared_future<QVariant> addTiles(const TilePtrArray &tileArray);
  std::shared_future<QVariant> removeTiles(const IDArray &idArray);
  std::shared_future<QVariant> clearTiles();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
78 79

  // 	Functions that don't require communication to device.
80 81 82 83 84
  TileArray getTiles(const IDArray &idArray);
  TileArray getAllTiles();
  LogicalArray containsTiles(const IDArray &idArray);
  std::size_t size();
  bool empty();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
85 86 87 88

  // Progress.
  ProgressArray getProgress();
  ProgressArray getProgress(const IDArray &idArray);
89 90

  NemoInterface::STATUS status();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
91 92 93 94 95
  bool running(); // thread safe
  bool ready();   // thread safe

  const QString &infoString();
  const QString &warningString();
96 97

private:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
98
  void _doTopicServiceSetup();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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
  void _doAction();
  void _trySynchronize();
  bool _isSynchronized();
  bool _userSync();                // thread safe
  bool _sysSync();                 // thread safe
  void _onFutureWatcherFinished(); // thread safe

  // called from dispatcher thread!
  QVariant _callAddTiles(
      std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray);
  // called from dispatcher thread!
  QVariant _callRemoveTiles(std::shared_ptr<IDArray> pIdArray);
  // called from dispatcher thread!
  QVariant _callClearTiles();
  // called from dispatcher thread!
  QVariant _callGetProgress(std::shared_ptr<IDArray> pIdArray);

  void _addTilesRemote(
      std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray);
  void
  _addTilesRemote(std::shared_ptr<QVector<std::shared_ptr<Tile>>> pTileArray);
  void _removeTilesRemote(std::shared_ptr<IDArray> idArray);
  void _clearTilesRemote();
  void _updateProgress(std::shared_ptr<ProgressArray> pArray);
  void _onHeartbeatReceived(const QNemoHeartbeat &hb);
  void _setInfoString(const QString &info);
  void _setWarningString(const QString &warning);
126

Valentin Platzgummer's avatar
Valentin Platzgummer committed
127
  bool _setState(STATE newState); // not thread safe
Valentin Platzgummer's avatar
Valentin Platzgummer committed
128
  static bool _ready(STATE s);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
129 130
  static bool _userSync(STATE s);
  static bool _sysSync(STATE s);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
131
  static bool _running(STATE s);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
132 133 134
  static NemoInterface::STATUS _status(STATE state);
  static QString _toString(STATE s);
  static QString _toString(NemoInterface::STATUS s);
135

Valentin Platzgummer's avatar
Valentin Platzgummer committed
136
  std::atomic<STATE> _state;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
137
  ROSBridgePtr _pRosBridge;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
138 139 140
  TileMap _remoteTiles;
  TileMapConst _localTiles;
  NemoInterface *const _parent;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
141 142 143 144 145 146
  Dispatcher _dispatcher;
  QString _infoString;
  QString _warningString;
  QTimer _timeoutTimer;
  QTimer _connectionTimer;
  QNemoHeartbeat _lastHeartbeat;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
147
  FutureWatcher _futureWatcher;
148 149 150 151 152 153
};

using StatusMap = std::map<NemoInterface::STATUS, QString>;
static StatusMap statusMap{
    std::make_pair<NemoInterface::STATUS, QString>(
        NemoInterface::STATUS::NOT_CONNECTED, "Not Connected"),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
154 155
    std::make_pair<NemoInterface::STATUS, QString>(NemoInterface::STATUS::SYNC,
                                                   "Synchronizing"),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
156 157
    std::make_pair<NemoInterface::STATUS, QString>(NemoInterface::STATUS::READY,
                                                   "Ready"),
158 159 160 161 162 163
    std::make_pair<NemoInterface::STATUS, QString>(
        NemoInterface::STATUS::TIMEOUT, "Timeout"),
    std::make_pair<NemoInterface::STATUS, QString>(
        NemoInterface::STATUS::WEBSOCKET_DETECTED, "Websocket Detected")};

NemoInterface::Impl::Impl(NemoInterface *p)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
164
    : _state(STATE::STOPPED), _parent(p) {
165 166 167 168 169 170 171

  // ROS Bridge.
  WimaSettings *wimaSettings =
      qgcApp()->toolbox()->settingsManager()->wimaSettings();
  auto connectionStringFact = wimaSettings->rosbridgeConnectionString();
  auto setConnectionString = [connectionStringFact, this] {
    auto connectionString = connectionStringFact->rawValue().toString();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
172
    if (is_valid_port_path(connectionString.toLocal8Bit().data())) {
173 174 175 176 177 178
    } else {
      qgcApp()->warningMessageBoxOnMainThread(
          "Nemo Interface",
          "Websocket connection string possibly invalid: " + connectionString +
              ". Trying to connect anyways.");
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
179 180 181 182 183 184 185

    if (this->_pRosBridge) {
      this->_pRosBridge->reset();
    }
    this->_pRosBridge = std::make_shared<RosbridgeWsClient>(
        connectionString.toLocal8Bit().data());
    this->_pRosBridge->reset();
186 187 188 189 190
  };
  connect(connectionStringFact, &SettingsFact::rawValueChanged,
          setConnectionString);
  setConnectionString();

Valentin Platzgummer's avatar
Valentin Platzgummer committed
191
  // Heartbeat timeout.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
192 193 194 195
  connect(&this->_timeoutTimer, &QTimer::timeout, [this] {
    this->_setState(STATE::HEARTBEAT_TIMEOUT);
    this->_doAction();
  });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
196 197 198 199 200

  // Connection timer (temporary workaround)
  connect(&this->_connectionTimer, &QTimer::timeout, [this] {
    if (this->_pRosBridge->connected()) {
      if (this->_state == STATE::START_BRIDGE ||
Valentin Platzgummer's avatar
Valentin Platzgummer committed
201
          this->_state == STATE::WEBSOCKET_TIMEOUT) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
202 203 204 205 206
        this->_setState(STATE::WEBSOCKET_DETECTED);
        this->_doAction();
      }
    } else {
      if (this->_state == STATE::TRY_TOPIC_SERVICE_SETUP ||
Valentin Platzgummer's avatar
Valentin Platzgummer committed
207 208 209 210
          this->_state == STATE::READY ||
          this->_state == STATE::WEBSOCKET_DETECTED ||
          this->_state == STATE::HEARTBEAT_TIMEOUT) {
        this->_setState(STATE::WEBSOCKET_TIMEOUT);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
211 212 213 214
        this->_doAction();
      }
    }
  });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
215 216 217

  connect(&this->_futureWatcher, &FutureWatcher::finished,
          [this] { this->_onFutureWatcherFinished(); });
218 219
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
220 221
NemoInterface::Impl::~Impl() {}

222
void NemoInterface::Impl::start() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
223 224 225 226
  if (!running()) {
    this->_setState(STATE::START_BRIDGE);
    this->_doAction();
  }
227 228 229
}

void NemoInterface::Impl::stop() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
230 231 232 233
  if (running()) {
    this->_setState(STATE::STOPPED);
    this->_doAction();
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
234 235
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
236 237
std::shared_future<QVariant>
NemoInterface::Impl::addTiles(const TilePtrArray &tileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
238 239
  using namespace nemo_interface;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
  if (tileArray.size() > 0) {

    // copy unknown tiles
    auto pTileArray = std::make_shared<QVector<std::shared_ptr<const Tile>>>();
    for (const auto *pTile : tileArray) {
      auto id = pTile->id();
      const auto it = this->_localTiles.find(id);
      Q_ASSERT(it == _localTiles.end());
      if (Q_LIKELY(it == _localTiles.end())) {
        auto pTileCopy =
            std::make_shared<const Tile>(pTile->coordinateList(), 0.0, id);
        _localTiles.insert(std::make_pair(id, pTileCopy));
        pTileArray->push_back(pTileCopy);
      } else {
        qCDebug(NemoInterfaceLog)
            << "addTiles(): tile with id: " << pTile->id() << "already added.";
      }
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
258

Valentin Platzgummer's avatar
Valentin Platzgummer committed
259 260 261 262 263
    // ready for send?
    if (pTileArray->size() > 0 && (this->ready() || this->_userSync())) {

      this->_setState(STATE::SYNC_USER);
      this->_doAction();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
264

Valentin Platzgummer's avatar
Valentin Platzgummer committed
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
      // create command.
      auto sendTilesCommand = std::make_unique<Task>(
          std::bind(&Impl::_callAddTiles, this, pTileArray));

      // dispatch command and return.
      auto ret = _dispatcher.dispatch(std::move(sendTilesCommand));
      auto sfut = ret.share();
      _futureWatcher.setFuture(sfut);
      return sfut;
    }
  }

  std::promise<QVariant> p;
  p.set_value(QVariant(false));
  return p.get_future();
}

std::shared_future<QVariant>
NemoInterface::Impl::removeTiles(const IDArray &idArray) {
  using namespace nemo_interface;

  if (idArray.size() > 0) {

    // copy known ids
    auto pIdArray = std::make_shared<IDArray>();
    for (const auto id : idArray) {
      const auto it = this->_localTiles.find(id);
      Q_ASSERT(it != _localTiles.end());
      if (Q_LIKELY(it != _localTiles.end())) {
        _localTiles.erase(it);
        pIdArray->push_back(id);
      } else {
        qCDebug(NemoInterfaceLog) << "removeTiles(): unknown id: " << id << ".";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
298
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    }

    // ready for send?
    if (pIdArray->size() > 0 && (this->ready() || this->_userSync())) {

      this->_setState(STATE::SYNC_USER);
      this->_doAction();

      // create command.
      auto cmd = std::make_unique<Task>(
          std::bind(&Impl::_callRemoveTiles, this, pIdArray));

      // dispatch command and return.
      auto ret = _dispatcher.dispatch(std::move(cmd));
      auto sfut = ret.share();
      _futureWatcher.setFuture(sfut);
      return sfut;
    }
  }

  std::promise<QVariant> p;
  p.set_value(QVariant(false));
  return p.get_future();
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
323

Valentin Platzgummer's avatar
Valentin Platzgummer committed
324 325
std::shared_future<QVariant> NemoInterface::Impl::clearTiles() {
  using namespace nemo_interface;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
326

Valentin Platzgummer's avatar
Valentin Platzgummer committed
327 328 329 330 331 332 333
  // clear local tiles (_localTiles)
  this->_localTiles.clear();

  if (this->_localTiles.size() > 0 && (this->ready() || this->_userSync())) {

    this->_setState(STATE::SYNC_USER);
    this->_doAction();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
334

Valentin Platzgummer's avatar
Valentin Platzgummer committed
335 336 337
    // create command.
    auto pTask =
        std::make_unique<Task>(std::bind(&Impl::_callClearTiles, this));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
338 339

    // dispatch command and return.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
340 341 342 343
    auto ret = _dispatcher.dispatch(std::move(pTask));
    auto sfut = ret.share();
    _futureWatcher.setFuture(sfut);
    return sfut;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
344 345 346 347 348 349
  } else {
    std::promise<QVariant> p;
    p.set_value(QVariant(false));
    return p.get_future();
  }
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
350

Valentin Platzgummer's avatar
Valentin Platzgummer committed
351 352 353 354
TileArray NemoInterface::Impl::getTiles(const IDArray &idArray) {
  TileArray tileArray;

  for (const auto &id : idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
355 356 357 358 359 360 361
    const auto it = _localTiles.find(id);
    if (it != _localTiles.end()) {
      MeasurementTile copy;
      copy.setId(it->second->id());
      copy.setProgress(it->second->progress());
      copy.setPath(it->second->tile());
      tileArray.append(std::move(copy));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
362 363 364 365 366 367 368 369 370
    }
  }

  return tileArray;
}

TileArray NemoInterface::Impl::getAllTiles() {
  TileArray tileArray;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
371 372 373 374 375 376 377
  for (const auto &entry : _localTiles) {
    auto pTile = entry.second;
    MeasurementTile copy;
    copy.setId(pTile->id());
    copy.setProgress(pTile->progress());
    copy.setPath(pTile->tile());
    tileArray.append(std::move(copy));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
378 379 380 381 382 383 384 385 386
  }

  return tileArray;
}

LogicalArray NemoInterface::Impl::containsTiles(const IDArray &idArray) {
  LogicalArray logicalArray;

  for (const auto &id : idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
387 388
    const auto &it = _localTiles.find(id);
    logicalArray.append(it != _localTiles.end());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
389 390 391 392 393
  }

  return logicalArray;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
394
std::size_t NemoInterface::Impl::size() { return _localTiles.size(); }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
395

Valentin Platzgummer's avatar
Valentin Platzgummer committed
396
bool NemoInterface::Impl::empty() { return _localTiles.empty(); }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
397 398 399 400

ProgressArray NemoInterface::Impl::getProgress() {
  ProgressArray progressArray;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
401 402 403 404 405 406 407 408 409 410
  if (this->_isSynchronized()) {
    for (const auto &entry : _remoteTiles) {
      progressArray.append(
          LabeledProgress{entry.second->progress(), entry.second->id()});
    }
  } else {
    for (const auto &entry : _localTiles) {
      progressArray.append(
          LabeledProgress{entry.second->progress(), entry.second->id()});
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
411 412 413 414 415 416 417 418
  }

  return progressArray;
}

ProgressArray NemoInterface::Impl::getProgress(const IDArray &idArray) {
  ProgressArray progressArray;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
  if (this->_isSynchronized()) {
    for (const auto &id : idArray) {
      const auto it = _remoteTiles.find(id);
      if (it != _remoteTiles.end()) {
        progressArray.append(
            LabeledProgress{it->second->progress(), it->second->id()});
      }
    }
  } else {
    for (const auto &id : idArray) {
      const auto it = _localTiles.find(id);
      if (it != _localTiles.end()) {
        progressArray.append(
            LabeledProgress{it->second->progress(), it->second->id()});
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
434 435 436 437
    }
  }

  return progressArray;
438 439
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
440
NemoInterface::STATUS NemoInterface::Impl::status() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
441
  return _status(this->_state);
442 443
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
444
bool NemoInterface::Impl::running() { return _running(this->_state); }
445

Valentin Platzgummer's avatar
Valentin Platzgummer committed
446
bool NemoInterface::Impl::ready() { return _ready(this->_state.load()); }
447

Valentin Platzgummer's avatar
Valentin Platzgummer committed
448
bool NemoInterface::Impl::_sysSync() { return _sysSync(this->_state); }
449

Valentin Platzgummer's avatar
Valentin Platzgummer committed
450 451 452 453 454 455 456 457 458 459
void NemoInterface::Impl::_onFutureWatcherFinished() {
  auto lastTransactionSuccessfull = _futureWatcher.result().toBool();
  if (!lastTransactionSuccessfull) {
    if (this->_userSync()) {
      _trySynchronize();
    } else if (this->_sysSync()) {
      QTimer::singleShot(1000, [this] { this->_trySynchronize(); });
    }
  } else {
    // fetch progress
460

Valentin Platzgummer's avatar
Valentin Platzgummer committed
461 462 463
    auto pIdArray = std::make_shared<IDArray>();
    for (const auto &pair : _remoteTiles) {
      pIdArray->push_back(pair.first);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
464
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
465 466
    auto pTask = std::make_unique<nemo_interface::Task>(
        std::bind(&Impl::_callGetProgress, this, pIdArray));
467

Valentin Platzgummer's avatar
Valentin Platzgummer committed
468 469 470 471
    // dispatch command.
    auto ret = _dispatcher.dispatch(std::move(pTask));
    Q_ASSERT(false);
    _futureWatcher.setFuture(ret.share());
472
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
473 474
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
475
bool NemoInterface::Impl::_userSync() { return _userSync(this->_state); }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
476

Valentin Platzgummer's avatar
Valentin Platzgummer committed
477
const QString &NemoInterface::Impl::infoString() { return _infoString; }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
478

Valentin Platzgummer's avatar
Valentin Platzgummer committed
479
const QString &NemoInterface::Impl::warningString() { return _warningString; }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
480

Valentin Platzgummer's avatar
Valentin Platzgummer committed
481 482 483
void NemoInterface::Impl::_updateProgress(
    std::shared_ptr<ProgressArray> pArray) {
  for (auto itLP = pArray->begin(); itLP != pArray->end();) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
484

Valentin Platzgummer's avatar
Valentin Platzgummer committed
485
    auto it = _remoteTiles.find(itLP->id());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
486

Valentin Platzgummer's avatar
Valentin Platzgummer committed
487 488 489
    if (Q_LIKELY(it != _remoteTiles.end())) {
      it->second->setProgress(itLP->progress());
      ++itLP;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
490 491
    } else {
      qCDebug(NemoInterfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
492 493
          << "_updateProgress(): tile with id " << itLP->id() << " not found.";
      itLP = pArray->erase(itLP);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
494 495 496
    }
  }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
497 498 499
  if (pArray->size() > 0) {
    emit _parent->progressChanged(*pArray);
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
500 501
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
502 503 504 505 506 507 508 509 510
void NemoInterface::Impl::_onHeartbeatReceived(const QNemoHeartbeat &hb) {
  _lastHeartbeat = hb;
  this->_timeoutTimer.start(NO_HEARTBEAT_TIMEOUT);
  if (this->_state == STATE::TRY_TOPIC_SERVICE_SETUP) {
    this->_setState(STATE::READY);
    this->_doAction();
  } else if (this->_state == STATE::HEARTBEAT_TIMEOUT) {
    this->_setState(STATE::READY);
    this->_doAction();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
  }
}

void NemoInterface::Impl::_setInfoString(const QString &info) {
  if (_infoString != info) {
    _infoString = info;
    emit this->_parent->infoStringChanged();
  }
}

void NemoInterface::Impl::_setWarningString(const QString &warning) {
  if (_warningString != warning) {
    _warningString = warning;
    emit this->_parent->warningStringChanged();
  }
}

void NemoInterface::Impl::_doTopicServiceSetup() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
529
  using namespace ros_bridge::messages;
530 531

  // Subscribe nemo progress.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
532 533
  const char *progressClient = "client:/nemo/progress";
  this->_pRosBridge->addClient(progressClient);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
534
  this->_pRosBridge->subscribe(
Valentin Platzgummer's avatar
Valentin Platzgummer committed
535
      progressClient, "/nemo/progress",
Valentin Platzgummer's avatar
Valentin Platzgummer committed
536
      [this](std::shared_ptr<WsClient::Connection>,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
537
             std::shared_ptr<WsClient::InMessage> in_message) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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
        auto msg = in_message->string();

        // parse in_message
        rapidjson::Document d;
        d.Parse(msg.c_str());
        if (!d.HasParseError()) {
          if (d.HasMember("msg") && d["msg"].IsObject()) {

            // create obj from json
            nemo_msgs::progress_array::ProgressArray progressArray;
            if (nemo_msgs::progress_array::fromJson(d["msg"], progressArray)) {

              // correct range errors of progress
              for (auto &lp : progressArray.progress_array()) {
                bool rangeError = false;
                if (lp.progress() < 0) {
                  lp.setProgress(0);
                  rangeError = true;
                }
                if (lp.progress() > 100) {
                  lp.setProgress(100);
                  rangeError = true;
                }

                if (rangeError) {
                  qCWarning(NemoInterfaceLog) << "/nemo/progress progress out "
                                                 "of range, value was set to: "
                                              << lp.progress();
                }
              }

              auto p = std::make_shared<ProgressArray>();
              *p = std::move(progressArray.progress_array());
              QMetaObject::invokeMethod(
                  this->_parent,
                  std::bind(&NemoInterface::Impl::_updateProgress, this, p));
            } else {
              qCWarning(NemoInterfaceLog) << "/nemo/progress not able to "
                                             "create ProgressArray form json: "
                                          << msg.c_str();
            }
          } else {
            qCWarning(NemoInterfaceLog)
                << "/nemo/progress no \"msg\" key or wrong type: "
                << msg.c_str();
          }
        } else {
          qCWarning(NemoInterfaceLog)
              << "/nemo/progress message parse error (" << d.GetParseError()
              << "): " << msg.c_str();
        }
589
      });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
590 591 592
  // Subscribe heartbeat msg.
  const char *heartbeatClient = "client:/nemo/heartbeat";
  this->_pRosBridge->addClient(heartbeatClient);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
593
  this->_pRosBridge->subscribe(
Valentin Platzgummer's avatar
Valentin Platzgummer committed
594
      heartbeatClient, "/nemo/heartbeat",
Valentin Platzgummer's avatar
Valentin Platzgummer committed
595
      [this](std::shared_ptr<WsClient::Connection>,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
596
             std::shared_ptr<WsClient::InMessage> in_message) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
        auto msg = in_message->string();

        // parse in_message
        rapidjson::Document d;
        d.Parse(msg.c_str());
        if (!d.HasParseError()) {
          if (d.HasMember("msg") && d["msg"].IsObject()) {

            // create obj from json
            nemo_msgs::heartbeat::Heartbeat heartbeat;
            if (nemo_msgs::heartbeat::fromJson(d["msg"], heartbeat)) {
              QMetaObject::invokeMethod(
                  this->_parent,
                  std::bind(&NemoInterface::Impl::_onHeartbeatReceived, this,
                            heartbeat));
            } else {
              qCWarning(NemoInterfaceLog) << "/nemo/heartbeat not able to "
                                             "create Heartbeat form json: "
                                          << msg.c_str();
            }
          } else {
            qCWarning(NemoInterfaceLog)
                << "/nemo/heartbeat no \"msg\" key or wrong type: "
                << msg.c_str();
          }
        } else {
          qCWarning(NemoInterfaceLog)
              << "/nemo/heartbeat message parse error (" << d.GetParseError()
              << "): " << msg.c_str();
        }
627 628 629
      });
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
void NemoInterface::Impl::_trySynchronize() {
  if (!_isSynchronized()) {
    this->_setState(STATE::SYNC_SYS);
    this->_doAction();

    // create clear cmd.
    auto pTask = std::make_unique<nemo_interface::Task>(
        std::bind(&Impl::_callClearTiles, this));

    // dispatch command.
    qCritical() << "this assert is triggered sometimes! sdf92894";
    Q_ASSERT(_dispatcher.pendingTasks() == 0);
    auto ret = _dispatcher.dispatch(std::move(pTask));

    // create tile array.
    auto pTileArray = std::make_shared<QVector<std::shared_ptr<const Tile>>>();
    for (auto pair : _localTiles) {
      pTileArray->push_back(pair.second);
    }

    // create addTiles cmd.
    auto sendTilesCommand = std::make_unique<nemo_interface::Task>(
        std::bind(&Impl::_callAddTiles, this, pTileArray));

    // dispatch command.
    ret = _dispatcher.dispatch(std::move(sendTilesCommand));
    _futureWatcher.setFuture(ret.share());
  }
}

bool NemoInterface::Impl::_isSynchronized() {
  return _localTiles.size() > 0 && _remoteTiles.size() > 0 &&
         std::equal(
             _localTiles.begin(), _localTiles.end(), _remoteTiles.begin(),
             [](const auto &a, const auto &b) { return a.first == b.first; });
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
667
void NemoInterface::Impl::_doAction() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
668
  static bool resetDone = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
669 670
  switch (this->_state) {
  case STATE::STOPPED:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
671 672 673
    this->_connectionTimer.stop();
    this->_timeoutTimer.stop();
    this->_clearTilesRemote();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
674
    if (this->_pRosBridge->running()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
675
      this->_pRosBridge->reset();
676
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
677
    break;
678

Valentin Platzgummer's avatar
Valentin Platzgummer committed
679 680
  case STATE::START_BRIDGE:
    this->_pRosBridge->run();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
681 682
    this->_connectionTimer.start(CONNECTION_TIMER_INTERVAL);
    break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
683 684
    break;
  case STATE::WEBSOCKET_DETECTED:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
685
    resetDone = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
686 687 688 689 690
    this->_setState(STATE::TRY_TOPIC_SERVICE_SETUP);
    this->_doAction();
    break;
  case STATE::TRY_TOPIC_SERVICE_SETUP:
    this->_doTopicServiceSetup();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
691
    this->_timeoutTimer.start(NO_HEARTBEAT_TIMEOUT);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
692 693
    break;
  case STATE::READY:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
    _trySynchronize();
    break;
  case STATE::SYNC_USER:
  case STATE::SYNC_SYS:
    break;
  case STATE::HEARTBEAT_TIMEOUT:
    this->_clearTilesRemote();
    break;
  case STATE::WEBSOCKET_TIMEOUT:
    if (!resetDone) {
      resetDone = true;
      this->_pRosBridge->reset();
      this->_pRosBridge->run();
    }
    this->_clearTilesRemote();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
709 710
    break;
  };
711 712
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
QVariant NemoInterface::Impl::_callAddTiles(

    std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray) {
  // create json object
  rapidjson::Document request(rapidjson::kObjectType);
  auto &allocator = request.GetAllocator();
  rapidjson::Value jsonTileArray(rapidjson::kArrayType);
  for (const auto &tile : *pTileArray) {
    using namespace ros_bridge::messages;
    rapidjson::Value jsonTile(rapidjson::kObjectType);
    if (!nemo_msgs::tile::toJson(*tile, jsonTile, allocator)) {
      qCDebug(NemoInterfaceLog)
          << "addTiles(): not able to create json object: tile id: "
          << tile->id() << " progress: " << tile->progress()
          << " points: " << tile->tile();
    }
    jsonTileArray.PushBack(jsonTile, allocator);
  } // for
  rapidjson::Value tileKey("in_tile_array");
  request.AddMember(tileKey, jsonTileArray, allocator);

  // create response handler.
  auto promise_response = std::make_shared<std::promise<bool>>();
  auto future_response = promise_response->get_future();
  auto responseHandler =
      [promise_response](
          std::shared_ptr<WsClient::Connection> connection,
          std::shared_ptr<WsClient::InMessage> in_message) mutable {
        // check if transaction was successfull
        auto msg = in_message->string();
        rapidjson::Document d;
        d.Parse(msg.c_str());
        if (!d.HasParseError()) {
          if (d.HasMember("values") && d["values"].IsObject()) {
            auto values = d["values"].GetObject();
            if (values.HasMember("success") && values["success"].IsBool()) {
              promise_response->set_value(values["success"].GetBool());
            } else {
              qCWarning(NemoInterfaceLog)
                  << "/nemo/add_tiles no \"success\" key or wrong type: "
                  << msg.c_str();
              promise_response->set_value(false);
            }
          } else {
            qCWarning(NemoInterfaceLog)
                << "/nemo/add_tiles no \"values\" key or wrong type: "
                << msg.c_str();
            promise_response->set_value(false);
          }
        } else {
          qCWarning(NemoInterfaceLog)
              << "/nemo/add_tiles message parse error (" << d.GetParseError()
              << "): " << msg.c_str();
          promise_response->set_value(false);
        }
        connection->send_close(1000);
      };

  // call service.
  this->_pRosBridge->callService("/nemo/add_tiles", responseHandler, request);

  // wait for response.
  auto tStart = hrc::now();
  bool abort = true;
  do {
    auto status = future_response.wait_for(std::chrono::milliseconds(100));
    if (status == std::future_status::ready) {
      abort = false;
      break;
    }
  } while (hrc::now() - tStart < maxResponseTime ||
           this->_dispatcher.isInterruptionRequested());

  if (abort) {
    qCWarning(NemoInterfaceLog)
        << "addTiles(): Websocket not responding to request.";
    return QVariant(false);
  }

  // transaction error?
  if (!future_response.get()) {
    return QVariant(false);
  }

  // add remote tiles (_remoteTiles)
  QMetaObject::invokeMethod(this->_parent /* context */, [this, pTileArray] {
    this->_addTilesRemote(pTileArray);
  });

  // return success
  return QVariant(true);
}

QVariant
NemoInterface::Impl::_callRemoveTiles(std::shared_ptr<IDArray> pIdArray) {
  // create json object
  rapidjson::Document request(rapidjson::kObjectType);
  auto &allocator = request.GetAllocator();
  rapidjson::Value jsonIdArray(rapidjson::kArrayType);
  for (const auto id : *pIdArray) {
    using namespace ros_bridge::messages;
    jsonIdArray.PushBack(rapidjson::Value(id), allocator);
  } // for
  rapidjson::Value tileKey("ids");
  request.AddMember(tileKey, jsonIdArray, allocator);

  // create response handler.
  auto promise_response = std::make_shared<std::promise<bool>>();
  auto future_response = promise_response->get_future();
  auto responseHandler =
      [promise_response](
          std::shared_ptr<WsClient::Connection> connection,
          std::shared_ptr<WsClient::InMessage> in_message) mutable {
        // check if transaction was successfull
        auto msg = in_message->string();
        rapidjson::Document d;
        d.Parse(msg.c_str());
        if (!d.HasParseError()) {
          if (d.HasMember("values") && d["values"].IsObject()) {
            auto values = d["values"].GetObject();
            if (values.HasMember("success") && values["success"].IsBool()) {
              promise_response->set_value(values["success"].GetBool());
            } else {
              qCWarning(NemoInterfaceLog)
                  << "/nemo/remove_tiles no \"success\" key or wrong type: "
                  << msg.c_str();
              promise_response->set_value(false);
            }
          } else {
            qCWarning(NemoInterfaceLog)
                << "/nemo/remove_tiles no \"values\" key or wrong type: "
                << msg.c_str();
            promise_response->set_value(false);
          }
        } else {
          qCWarning(NemoInterfaceLog)
              << "/nemo/remove_tiles message parse error (" << d.GetParseError()
              << "): " << msg.c_str();
          promise_response->set_value(false);
        }
        connection->send_close(1000);
      };

  // call service.
  this->_pRosBridge->callService("/nemo/remove_tiles", responseHandler,
                                 request);

  // wait for response.
  auto tStart = hrc::now();
  bool abort = true;
  do {
    auto status = future_response.wait_for(std::chrono::milliseconds(100));
    if (status == std::future_status::ready) {
      abort = false;
      break;
    }
  } while (hrc::now() - tStart < maxResponseTime ||
           this->_dispatcher.isInterruptionRequested());

  if (abort) {
    qCWarning(NemoInterfaceLog)
        << "remove_tiles(): Websocket not responding to request.";
    return QVariant(false);
  }

  // transaction error?
  if (!future_response.get()) {
    return QVariant(false);
  }

  // remove remote tiles (_remoteTiles)
  QMetaObject::invokeMethod(this->_parent /* context */, [this, pIdArray] {
    this->_removeTilesRemote(pIdArray);
  });

  // return success
  return QVariant(true);
}

QVariant NemoInterface::Impl::_callClearTiles() {
  // create response handler.
  auto promise_response = std::make_shared<std::promise<bool>>();
  auto future_response = promise_response->get_future();
  auto responseHandler =
      [promise_response](
          std::shared_ptr<WsClient::Connection> connection,
          std::shared_ptr<WsClient::InMessage> in_message) mutable {
        // check if transaction was successfull
        auto msg = in_message->string();
        rapidjson::Document d;
        d.Parse(msg.c_str());
        if (!d.HasParseError()) {
          if (d.HasMember("result") && d["result"].IsBool()) {
            promise_response->set_value(d["result"].GetBool());
          } else {
            qCWarning(NemoInterfaceLog)
                << "/nemo/clear_tiles no \"result\" key or wrong type: "
                << msg.c_str();
            promise_response->set_value(false);
          }
        } else {
          qCWarning(NemoInterfaceLog)
              << "/nemo/clear_tiles message parse error (" << d.GetParseError()
              << "): " << msg.c_str();
          promise_response->set_value(false);
        }
        connection->send_close(1000);
      };

  // call service.
  this->_pRosBridge->callService("/nemo/clear_tiles", responseHandler,
                                 rapidjson::Document(rapidjson::kObjectType));

  // wait for response.
  auto tStart = hrc::now();
  bool abort = true;
  do {
    auto status = future_response.wait_for(std::chrono::milliseconds(100));
    if (status == std::future_status::ready) {
      abort = false;
      break;
    }
  } while (hrc::now() - tStart < maxResponseTime ||
           this->_dispatcher.isInterruptionRequested());

  if (abort) {
    qCWarning(NemoInterfaceLog) << "Websocket not responding to request.";
    return QVariant(false);
  }

  // transaction failed?
  if (!future_response.get()) {
    return QVariant(false);
  }

  // clear remote tiles (_remoteTiles)
  QMetaObject::invokeMethod(this->_parent,
                            std::bind(&Impl::_clearTilesRemote, this));

  // return success
  return QVariant(true);
}

QVariant
NemoInterface::Impl::_callGetProgress(std::shared_ptr<IDArray> pIdArray) {
  // create json object
  rapidjson::Document request(rapidjson::kObjectType);
  auto &allocator = request.GetAllocator();
  rapidjson::Value jsonIdArray(rapidjson::kArrayType);
  for (const auto id : *pIdArray) {
    using namespace ros_bridge::messages;
    jsonIdArray.PushBack(rapidjson::Value(id), allocator);
  } // for
  rapidjson::Value tileKey("ids");
  request.AddMember(tileKey, jsonIdArray, allocator);

  // create response handler.
  typedef std::shared_ptr<ProgressArray> ResponseType;
  auto promise_response = std::make_shared<std::promise<ResponseType>>();
  auto future_response = promise_response->get_future();
  auto responseHandler =
      [promise_response](
          std::shared_ptr<WsClient::Connection> connection,
          std::shared_ptr<WsClient::InMessage> in_message) mutable {
        // check if transaction was successfull
        auto msg = in_message->string();
        rapidjson::Document d;
        d.Parse(msg.c_str());
        if (!d.HasParseError()) {
          if (d.HasMember("values") && d["values"].IsObject()) {
            auto values = d["values"].GetObject();
            ros_bridge::messages::nemo_msgs::progress_array::ProgressArray
                progressArrayMsg;
            if (ros_bridge::messages::nemo_msgs::progress_array::fromJson(
                    d["values"], progressArrayMsg)) {
              auto pArray = std::make_shared<ProgressArray>();
              *pArray = std::move(progressArrayMsg.progress_array());
              promise_response->set_value(pArray);
            } else {
              qCWarning(NemoInterfaceLog)
                  << "/nemo/get_progress error while creating ProgressArray "
                     "from json.";
              promise_response->set_value(nullptr);
            }
          } else {
            qCWarning(NemoInterfaceLog)
                << "/nemo/get_progress no \"values\" key or wrong type: "
                << msg.c_str();
            promise_response->set_value(nullptr);
          }
        } else {
          qCWarning(NemoInterfaceLog)
              << "/nemo/get_progress message parse error (" << d.GetParseError()
              << "): " << msg.c_str();
          promise_response->set_value(nullptr);
        }
        connection->send_close(1000);
      };

  // call service.
  this->_pRosBridge->callService("/nemo/get_progress", responseHandler,
                                 request);

  // wait for response.
  auto tStart = hrc::now();
  bool abort = true;
  do {
    auto status = future_response.wait_for(std::chrono::milliseconds(100));
    if (status == std::future_status::ready) {
      abort = false;
      break;
    }
  } while (hrc::now() - tStart < maxResponseTime ||
           this->_dispatcher.isInterruptionRequested());

  if (abort) {
    qCWarning(NemoInterfaceLog)
        << "remove_tiles(): Websocket not responding to request.";
    return QVariant(false);
  }

  // transaction error?
  auto pArray = future_response.get();
  if (pArray == nullptr) {
    return QVariant(false);
  }

  // remove remote tiles (_remoteTiles)
  QMetaObject::invokeMethod(this->_parent /* context */,
                            [this, pArray] { this->_updateProgress(pArray); });

  // return success
  return QVariant(true);
}

void NemoInterface::Impl::_addTilesRemote(
    std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray) {
  auto pArrayDup = std::make_shared<QVector<std::shared_ptr<Tile>>>();
  for (auto pTile : *pTileArray) {
    pArrayDup->push_back(std::make_shared<Tile>(*pTile));
  }
  _addTilesRemote(pArrayDup);
}

void NemoInterface::Impl::_addTilesRemote(
    std::shared_ptr<QVector<std::shared_ptr<Tile>>> pTileArray) {

  bool anyChange = false;

  for (auto pTile : *pTileArray) {
    auto id = pTile->id();
    auto it = _remoteTiles.find(id);
    qCritical() << "this assert is triggered sometimes! 1212341242";
    Q_ASSERT(it == _remoteTiles.end());
    if (Q_LIKELY(it == _remoteTiles.end())) {
      auto ret = _remoteTiles.insert(std::make_pair(id, pTile));
      Q_ASSERT(ret.second == true);
      Q_UNUSED(ret);
      anyChange = true;
    } else {
      qCWarning(NemoInterfaceLog)
          << "_addTilesRemote: tile with id " << id << " already added.";
    }
  }

  if (anyChange) {
    if (this->_isSynchronized()) {
      this->_setState(STATE::READY);
      this->_doAction();
    }
    this->_parent->tilesChanged();
  }
}

void NemoInterface::Impl::_removeTilesRemote(std::shared_ptr<IDArray> idArray) {
  bool anyChange = false;

  for (const auto id : *idArray) {
    auto it = _remoteTiles.find(id);
    Q_ASSERT(it != _remoteTiles.end());
    if (Q_LIKELY(it != _remoteTiles.end())) {
      _remoteTiles.erase(it);
      anyChange = true;
    } else {
      qCWarning(NemoInterfaceLog)
          << "_removeTilesRemote: tile with unknown id " << id << ".";
    }
  }

  if (anyChange) {
    if (this->_isSynchronized()) {
      this->_setState(STATE::READY);
      this->_doAction();
    }
    this->_parent->tilesChanged();
  }
}

void NemoInterface::Impl::_clearTilesRemote() {
  if (_remoteTiles.size() > 0) {
    _remoteTiles.clear();
    if (this->_isSynchronized()) {
      this->_setState(STATE::READY);
      this->_doAction();
    }
    this->_parent->tilesChanged();
  }
}

bool NemoInterface::Impl::_setState(STATE newState) {
  if (newState != this->_state) {
    auto oldState = this->_state.load();
    this->_state = newState;

    qCDebug(NemoInterfaceLog)
        << "state: " << _toString(oldState) << " -> " << _toString(newState);
    auto oldStatus = _status(oldState);
    auto newStatus = _status(newState);
    if (oldStatus != newStatus) {
      qCDebug(NemoInterfaceLog) << "status: " << _toString(oldStatus) << " -> "
                                << _toString(newStatus);
      emit this->_parent->statusChanged();
    }

    if (_running(oldState) != _running(newState)) {
      emit this->_parent->runningChanged();
    }

1141 1142 1143 1144 1145 1146
    return true;
  } else {
    return false;
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1147 1148 1149 1150
bool NemoInterface::Impl::_ready(NemoInterface::Impl::STATE s) {
  return s == STATE::READY;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1151 1152 1153 1154 1155 1156 1157 1158
bool NemoInterface::Impl::_userSync(NemoInterface::Impl::STATE s) {
  return s == STATE::SYNC_USER;
}

bool NemoInterface::Impl::_sysSync(NemoInterface::Impl::STATE s) {
  return s == STATE::SYNC_SYS;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1159 1160 1161 1162
bool NemoInterface::Impl::_running(NemoInterface::Impl::STATE s) {
  return s != STATE::STOPPED;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
NemoInterface::STATUS
NemoInterface::Impl::_status(NemoInterface::Impl::STATE state) {
  NemoInterface::STATUS status;
  switch (state) {
  case STATE::STOPPED:
    status = NemoInterface::STATUS::NOT_CONNECTED;
    break;
  case STATE::START_BRIDGE:
    status = NemoInterface::STATUS::NOT_CONNECTED;
    break;
  case STATE::WEBSOCKET_DETECTED:
    status = NemoInterface::STATUS::WEBSOCKET_DETECTED;
    break;
  case STATE::TRY_TOPIC_SERVICE_SETUP:
    status = NemoInterface::STATUS::WEBSOCKET_DETECTED;
    break;
  case STATE::READY:
    status = NemoInterface::STATUS::READY;
    break;
  case STATE::SYNC_USER:
  case STATE::SYNC_SYS:
    status = NemoInterface::STATUS::SYNC;
    break;
  case STATE::WEBSOCKET_TIMEOUT:
  case STATE::HEARTBEAT_TIMEOUT:
    status = NemoInterface::STATUS::TIMEOUT;
    break;
  }

  return status;
}

QString NemoInterface::Impl::_toString(NemoInterface::Impl::STATE s) {
  switch (s) {
  case STATE::STOPPED:
    return QString("STOPPED");
  case STATE::START_BRIDGE:
    return QString("START_BRIDGE");
  case STATE::WEBSOCKET_DETECTED:
    return QString("WEBSOCKET_DETECTED");
  case STATE::TRY_TOPIC_SERVICE_SETUP:
    return QString("TRY_TOPIC_SERVICE_SETUP");
  case STATE::READY:
    return QString("READY");
  case STATE::SYNC_USER:
    return QString("SYNC_USER");
  case STATE::SYNC_SYS:
    return QString("SYNC_SYS");
  case STATE::WEBSOCKET_TIMEOUT:
    return QString("WEBSOCKET_TIMEOUT");
  case STATE::HEARTBEAT_TIMEOUT:
    return QString("HEARTBEAT_TIMEOUT");
  }
  return "unknown state!";
}

QString NemoInterface::Impl::_toString(NemoInterface::STATUS s) {
  switch (s) {
  case NemoInterface::STATUS::NOT_CONNECTED:
    return QString("NOT_CONNECTED");
  case NemoInterface::STATUS::READY:
    return QString("READY");
  case NemoInterface::STATUS::TIMEOUT:
    return QString("TIMEOUT");
  case NemoInterface::STATUS::WEBSOCKET_DETECTED:
    return QString("WEBSOCKET_DETECTED");
  case NemoInterface::STATUS::SYNC:
    return QString("SYNC");
  }
  return "unknown state!";
}

1235 1236
// ===============================================================
// NemoInterface
1237 1238 1239 1240 1241 1242 1243 1244 1245
NemoInterface::NemoInterface()
    : QObject(), pImpl(std::make_unique<NemoInterface::Impl>(this)) {}

NemoInterface *NemoInterface::createInstance() { return new NemoInterface(); }

NemoInterface *NemoInterface::instance() {
  return GenericSingelton<NemoInterface>::instance(
      NemoInterface::createInstance);
}
1246 1247 1248 1249 1250 1251 1252

NemoInterface::~NemoInterface() {}

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

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1253 1254 1255 1256 1257 1258 1259
std::shared_future<QVariant>
NemoInterface::addTiles(const TileArray &tileArray) {
  TilePtrArray ptrArray;
  for (const auto &tile : tileArray) {
    ptrArray.push_back(const_cast<MeasurementTile *>(&tile));
  }
  return this->pImpl->addTiles(ptrArray);
1260 1261
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1262 1263 1264
std::shared_future<QVariant>
NemoInterface::addTiles(const TilePtrArray &tileArray) {
  return this->pImpl->addTiles(tileArray);
1265 1266
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1267 1268 1269 1270 1271 1272 1273 1274
std::shared_future<QVariant>
NemoInterface::removeTiles(const IDArray &idArray) {
  return this->pImpl->removeTiles(idArray);
}

std::shared_future<QVariant> NemoInterface::clearTiles() {
  return this->pImpl->clearTiles();
}
1275 1276 1277 1278 1279

TileArray NemoInterface::getTiles(const IDArray &idArray) {
  return this->pImpl->getTiles(idArray);
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1280
TileArray NemoInterface::getAllTiles() { return this->pImpl->getAllTiles(); }
1281 1282 1283 1284 1285 1286 1287 1288 1289

LogicalArray NemoInterface::containsTiles(const IDArray &idArray) {
  return this->pImpl->containsTiles(idArray);
}

std::size_t NemoInterface::size() { return this->pImpl->size(); }

bool NemoInterface::empty() { return this->pImpl->empty(); }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1290 1291 1292 1293 1294 1295 1296 1297
ProgressArray NemoInterface::getProgress() {
  return this->pImpl->getProgress();
}

ProgressArray NemoInterface::getProgress(const IDArray &idArray) {
  return this->pImpl->getProgress(idArray);
}

1298
NemoInterface::STATUS NemoInterface::status() const {
1299 1300 1301 1302 1303 1304 1305
  return this->pImpl->status();
}

QString NemoInterface::statusString() const {
  return statusMap.at(this->pImpl->status());
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1306 1307 1308 1309 1310
QString NemoInterface::infoString() const { return this->pImpl->infoString(); }

QString NemoInterface::warningString() const {
  return this->pImpl->warningString();
}
1311 1312 1313 1314 1315 1316

QString NemoInterface::editorQml() {
  return QStringLiteral("NemoInterface.qml");
}

bool NemoInterface::running() { return this->pImpl->running(); }