NemoInterface.cpp 54.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
#include "NemoInterface.h"

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

10
#include <mutex>
11

12 13
#include <QJsonArray>
#include <QJsonObject>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
14
#include <QQmlEngine>
15
#include <QTimer>
16
#include <QUrl>
17

18
#include "GenericSingelton.h"
19
#include "geometry/MeasurementArea.h"
20
#include "geometry/geometry.h"
21
#include "nemo_interface/MeasurementTile.h"
22
#include "nemo_interface/QNemoHeartbeat.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
23 24
#include "nemo_interface/TaskDispatcher.h"

25 26
#include "ros_bridge/include/messages/geographic_msgs/geopoint.h"
#include "ros_bridge/include/messages/nemo_msgs/heartbeat.h"
27
#include "ros_bridge/include/messages/nemo_msgs/progress_array.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
28
#include "ros_bridge/include/messages/nemo_msgs/tile.h"
29
#include "ros_bridge/include/messages/nemo_msgs/tile_array.h"
30
#include "rosbridge/rosbridge.h"
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
/*
 * Here some rules:
 * * not threas safe functions are marked with *NotSafe(...)
 * * If a function is not safe:
 *     * the call to it must be protected with a Lock.
 *     * not safe functions are not allowed to emit signals directly (danger of
 * deadlock).
 *     * if a not safe function needs to emit a signal, defere it with
 *       QTimer::singleShot().
 *     * not safe functions are allowed to call other not safe functions
 *     * it is a bad idea to wait inside a not safe function for a asynchronous
 * operation (potential deadlock)
 * * Functions that are not marked with *NotSafe(...) must be thread safe!
 */

#define INVM(context, fun)                                                     \
  {                                                                            \
    auto value = QMetaObject::invokeMethod(context, fun);                      \
    Q_ASSERT(value == true);                                                   \
    Q_UNUSED(value);                                                           \
  }

Q_DECLARE_METATYPE(ProgressArray)

Valentin Platzgummer's avatar
Valentin Platzgummer committed
56
QGC_LOGGING_CATEGORY(NemointerfaceLog, "NemointerfaceLog")
57

58 59 60 61 62
#define NO_HEARTBEAT_TIMEOUT 5000   // ms
#define RESTART_INTERVAl 600000     // ms == 10 min
#define RESTART_RETRY_INTERVAl 2000 // ms
#define SYNC_INTERVAL 10000         // ms
#define SYNC_RETRY_INTERVAL 2000    // ms
63

64
static constexpr auto maxResponseTime = std::chrono::milliseconds(20000);
65

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
static char const *progressTopic = "/nemo/progress";
static char const *heartbeatTopic = "/nemo/heartbeat";

static char const *addTilesService = "/nemo/add_tiles";
static char const *removeTilesService = "/nemo/remove_tiles";
static char const *clearTilesService = "/nemo/clear_tiles";
static char const *getAllTilesService = "/nemo/get_all_tiles";
// static char const *getTilesService = "/nemo/get_tiles";
// static char const *containsTilesService = "/nemo/contains_tiles";
// static char const *extractTilesService = "/nemo/extract_tiles";
// static char const *sizeService = "/nemo/size";
// static char const *emptyService = "/nemo/empty";
static char const *getProgressService = "/nemo/get_progress";
static char const *getAllProgressService = "/nemo/get_all_progress";
static char const *getVersionService = "/nemo/get_version";

static const std::vector<char const *> requiredServices{
    addTilesService,    removeTilesService,    clearTilesService,
    getAllTilesService, getAllProgressService, getProgressService,
    getVersionService};

static const std::vector<char const *> requiredTopics{progressTopic,
                                                      heartbeatTopic};
89

Valentin Platzgummer's avatar
Valentin Platzgummer committed
90
using hrc = std::chrono::high_resolution_clock;
91
using ROSBridgePtr = std::shared_ptr<Rosbridge>;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
92 93 94 95

typedef ros_bridge::messages::nemo_msgs::tile::GenericTile<QGeoCoordinate,
                                                           QList>
    Tile;
96 97
typedef std::map<QString, std::shared_ptr<Tile>> TileMap;
typedef std::map<QString, std::shared_ptr<const Tile>> TileMapConst;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
98 99
typedef ros_bridge::messages::nemo_msgs::heartbeat::Heartbeat Heartbeat;
typedef nemo_interface::TaskDispatcher Dispatcher;
100
typedef std::unique_lock<std::mutex> Lock;
101

Valentin Platzgummer's avatar
Valentin Platzgummer committed
102
class Nemointerface::Impl {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
103 104
  enum class STATE {
    STOPPED,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
105
    START_BRIDGE,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
106
    WEBSOCKET_DETECTED,
107
    TRY_SETUP,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
108 109
    USER_SYNC,
    SYS_SYNC,
110
    SYNC_ERROR,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
111
    READY,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
112 113
    WEBSOCKET_TIMEOUT,
    HEARTBEAT_TIMEOUT
Valentin Platzgummer's avatar
Valentin Platzgummer committed
114
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
115

Valentin Platzgummer's avatar
Valentin Platzgummer committed
116
public:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
117
  Impl(const QString &connectionString, Nemointerface *p);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
118
  ~Impl();
119 120 121 122

  void start();
  void stop();

Valentin Platzgummer's avatar
Valentin Platzgummer committed
123 124
  // Tile editing.
  // 	Functions that require communication to device.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
125 126 127
  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
128 129

  // 	Functions that don't require communication to device.
130 131 132 133 134
  TileArray getTiles(const IDArray &idArray) const;
  TileArray getAllTiles() const;
  LogicalArray containsTiles(const IDArray &idArray) const;
  std::size_t size() const;
  bool empty() const;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
135 136

  // Progress.
137 138
  ProgressArray getProgress() const;
  ProgressArray getProgress(const IDArray &idArray) const;
139

Valentin Platzgummer's avatar
Valentin Platzgummer committed
140
  Nemointerface::STATUS status() const;
141 142
  bool running() const; // thread safe
  bool ready() const;   // thread safe
Valentin Platzgummer's avatar
Valentin Platzgummer committed
143

144 145
  const QString &infoString() const;
  const QString &warningString() const;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
146
  const QString &connectionString() const;
147 148

private:
149 150 151
  void _doSetup();
  void _doActionNotSafe();
  void _synchronize();
152
  void _tryRestart();
153
  bool _isSynchronizedNotSafe() const;
154
  bool _isSynchronized() const;
155
  void _onHeartbeatTimeout();
156
  void _onRosbridgeStateChanged();
157 158 159 160
  bool _updateProgress(const ProgressArray &pArray);
  void _onHeartbeatReceived(const QNemoHeartbeat &hb);
  void _setInfoStringNotSafe(const QString &info);
  void _setWarningStringNotSafe(const QString &warning);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
161 162
  void _setInfoString(const QString &info);
  void _setWarningString(const QString &warning);
163

164 165 166 167 168 169 170 171
  // state suff
  bool _userSync() const;
  bool _sysSync() const;
  bool _setStateNotSafe(STATE newState);
  static bool _readyNotSafe(STATE s);
  static bool _userSyncNotSafe(STATE s);
  static bool _sysSyncNotSafe(STATE s);
  static bool _runningNotSafe(STATE s);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
172
  static Nemointerface::STATUS _status(STATE state);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
173
  static QString _toString(STATE s);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
174
  static QString _toString(Nemointerface::STATUS s);
175

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
  // impl functions
  bool _addTilesImpl(
      std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray,
      std::shared_ptr<const IDArray> pIdArray);
  bool _removeTilesImpl(std::shared_ptr<const IDArray> pIdArray);
  bool _clearTilesImpl();

  // Worker functions.
  static bool
  _callAddTiles(const QVector<std::shared_ptr<const Tile>> &tileArray,
                Dispatcher &d, Rosbridge &rb);
  static bool _callClearTiles(Dispatcher &d, Rosbridge &rb);
  static ProgressArray _callGetProgress(const IDArray &pIdArray, Dispatcher &d,
                                        Rosbridge &rb);
  static ProgressArray _callGetAllProgress(Dispatcher &d, Rosbridge &rb);
  static QVector<std::shared_ptr<Tile>> _callGetAllTiles(Dispatcher &d,
                                                         Rosbridge &rb);
  static QString _callGetVersion(Dispatcher &d, Rosbridge &rb);
  static bool _callRemoveTiles(const IDArray &pIdArray, Dispatcher &d,
                               Rosbridge &rb);

  // functions to manipulate _remoteTiles
  bool _addTilesRemote(const QVector<std::shared_ptr<const Tile>> tileArray);
  bool _addTilesRemote(const QVector<std::shared_ptr<Tile>> &tileArray);
  void _removeTilesRemote(const IDArray &idArray);
  void _clearTilesRemote();
  void _clearTilesRemoteNotSafe();

  // static and const members
  static const char *_localVersion;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
206 207
  Nemointerface *const _parent;
  const QString _connectionString;
208

209
  // thread safe members
Valentin Platzgummer's avatar
Valentin Platzgummer committed
210
  Rosbridge _rosbridge;
211 212 213 214 215
  Dispatcher _dispatcher;

  // protected by mutex
  mutable std::mutex _m;
  STATE _state;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
216 217
  TileMap _remoteTiles;
  TileMapConst _localTiles;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
218 219
  QString _infoString;
  QString _warningString;
220 221

  // Members belonging to _parent->thread()
Valentin Platzgummer's avatar
Valentin Platzgummer committed
222
  QTimer _timeoutTimer;
223 224
  QTimer _syncTimer;
  QTimer _restartTimer;
225 226
};

Valentin Platzgummer's avatar
Valentin Platzgummer committed
227
const char *Nemointerface::Impl::_localVersion("V_1.0");
228

Valentin Platzgummer's avatar
Valentin Platzgummer committed
229
using StatusMap = std::map<Nemointerface::STATUS, QString>;
230
static StatusMap statusMap{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
231 232 233
    std::make_pair<Nemointerface::STATUS, QString>(
        Nemointerface::STATUS::NOT_CONNECTED, "Not Connected"),
    std::make_pair<Nemointerface::STATUS, QString>(Nemointerface::STATUS::ERROR,
234
                                                   "ERROR"),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
235
    std::make_pair<Nemointerface::STATUS, QString>(Nemointerface::STATUS::SYNC,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
236
                                                   "Synchronizing"),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
237
    std::make_pair<Nemointerface::STATUS, QString>(Nemointerface::STATUS::READY,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
238
                                                   "Ready"),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
239 240 241 242
    std::make_pair<Nemointerface::STATUS, QString>(
        Nemointerface::STATUS::TIMEOUT, "Timeout"),
    std::make_pair<Nemointerface::STATUS, QString>(
        Nemointerface::STATUS::WEBSOCKET_DETECTED, "Websocket Detected")};
243

Valentin Platzgummer's avatar
Valentin Platzgummer committed
244 245 246 247
Nemointerface::Impl::Impl(const QString &connectionString, Nemointerface *p)
    : _parent(p), _connectionString(connectionString),
      _rosbridge(QUrl(QString("ws://") + connectionString)),
      _state(STATE::STOPPED) {
248

Valentin Platzgummer's avatar
Valentin Platzgummer committed
249
  // Heartbeat timeout.
250 251
  connect(&this->_timeoutTimer, &QTimer::timeout,
          std::bind(&Impl::_onHeartbeatTimeout, this));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
252

Valentin Platzgummer's avatar
Valentin Platzgummer committed
253
  connect(&this->_rosbridge, &Rosbridge::stateChanged, this->_parent,
254
          [this] { this->_onRosbridgeStateChanged(); });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
255

256 257 258 259
  connect(&this->_restartTimer, &QTimer::timeout, this->_parent,
          [this] { this->_tryRestart(); });

  connect(&this->_syncTimer, &QTimer::timeout, this->_parent,
260 261 262 263
          [this] { this->_synchronize(); });

  static std::once_flag flag;
  std::call_once(flag, [] { qRegisterMetaType<ProgressArray>(); });
264 265
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
266
Nemointerface::Impl::~Impl() { this->_rosbridge.stop(); }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
267

Valentin Platzgummer's avatar
Valentin Platzgummer committed
268
void Nemointerface::Impl::start() {
269 270 271 272
  Lock lk(this->_m);
  if (!_runningNotSafe(this->_state)) {
    this->_setStateNotSafe(STATE::START_BRIDGE);
    this->_doActionNotSafe();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
273
  }
274 275
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
276
void Nemointerface::Impl::stop() {
277 278 279 280
  Lock lk(this->_m);
  if (_runningNotSafe(this->_state)) {
    this->_setStateNotSafe(STATE::STOPPED);
    this->_doActionNotSafe();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
281
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
282 283
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
284
std::shared_future<QVariant>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
285
Nemointerface::Impl::addTiles(const TilePtrArray &tileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
286 287
  using namespace nemo_interface;

288
  // qDebug() << "addTiles called";
289

Valentin Platzgummer's avatar
Valentin Platzgummer committed
290 291 292 293
  if (tileArray.size() > 0) {

    // copy unknown tiles
    auto pTileArray = std::make_shared<QVector<std::shared_ptr<const Tile>>>();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
294
    auto pIdArray = std::make_shared<IDArray>();
295 296

    Lock lk(this->_m);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
297 298 299 300 301 302 303 304 305
    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);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
306
        pIdArray->push_back(id);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
307
      } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
308
        qCDebug(NemointerfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
309 310 311
            << "addTiles(): tile with id: " << pTile->id() << "already added.";
      }
    }
312
    if (pTileArray->size() > 0) {
313
      lk.unlock();
314
      emit this->_parent->tilesChanged();
315
      lk.lock();
316
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
317

Valentin Platzgummer's avatar
Valentin Platzgummer committed
318
    // ready for send?
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    if (pTileArray->size() > 0 && (this->_readyNotSafe(this->_state) ||
                                   this->_userSyncNotSafe(this->_state))) {

      this->_setStateNotSafe(STATE::USER_SYNC);
      this->_doActionNotSafe();
      lk.unlock();

      // create task.
      auto pTask = std::make_unique<Task>([this, pTileArray, pIdArray] {
        auto ret = this->_addTilesImpl(pTileArray, pIdArray);

        if (ret) {
          Lock lk(this->_m);
          if (this->_isSynchronizedNotSafe()) {
            this->_setStateNotSafe(STATE::READY);
            this->_doActionNotSafe();
          }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
336
        }
337
        return ret;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
338 339 340
      });

      // dispatch command.
341 342
      auto ret = _dispatcher.dispatch(std::move(pTask));
      return ret.share();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
343 344 345 346 347 348 349 350 351
    }
  }

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

std::shared_future<QVariant>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
352
Nemointerface::Impl::removeTiles(const IDArray &idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
353 354
  using namespace nemo_interface;

355
  // qDebug() << "removeTiles called";
356

Valentin Platzgummer's avatar
Valentin Platzgummer committed
357 358 359 360
  if (idArray.size() > 0) {

    // copy known ids
    auto pIdArray = std::make_shared<IDArray>();
361 362

    Lock lk(this->_m);
363
    for (const auto &id : idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
364 365 366 367 368 369
      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 {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
370
        qCDebug(NemointerfaceLog) << "removeTiles(): unknown id: " << id << ".";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
371
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
372
    }
373
    if (pIdArray->size() > 0) {
374
      lk.unlock();
375
      emit this->_parent->tilesChanged();
376
      lk.lock();
377
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
378 379

    // ready for send?
380 381
    if (pIdArray->size() > 0 && (this->_readyNotSafe(this->_state) ||
                                 this->_userSyncNotSafe(this->_state))) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
382

383 384 385
      this->_setStateNotSafe(STATE::USER_SYNC);
      this->_doActionNotSafe();
      lk.unlock();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
386 387

      // create command.
388 389 390 391 392 393 394 395 396 397 398 399 400
      auto cmd = std::make_unique<Task>([this, pIdArray] {
        auto ret = this->_removeTilesImpl(pIdArray);

        if (ret) {
          Lock lk(this->_m);
          if (this->_isSynchronizedNotSafe()) {
            this->_setStateNotSafe(STATE::READY);
            this->_doActionNotSafe();
          }
        }

        return ret;
      });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
401 402 403 404 405 406 407 408 409 410 411 412

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

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
414
std::shared_future<QVariant> Nemointerface::Impl::clearTiles() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
415
  using namespace nemo_interface;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
416

417
  // qDebug() << "clearTiles called";
418

Valentin Platzgummer's avatar
Valentin Platzgummer committed
419
  // clear local tiles (_localTiles)
420
  Lock lk(this->_m);
421 422
  if (!_localTiles.empty()) {
    this->_localTiles.clear();
423
    lk.unlock();
424
    emit this->_parent->tilesChanged();
425
    lk.lock();
426
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
427

428
  if (this->_readyNotSafe(this->_state) || this->_readyNotSafe(this->_state)) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
429

430 431 432
    this->_setStateNotSafe(STATE::USER_SYNC);
    this->_doActionNotSafe();
    lk.unlock();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
433

Valentin Platzgummer's avatar
Valentin Platzgummer committed
434
    // create command.
435 436 437 438 439 440 441 442 443 444 445 446 447
    auto pTask = std::make_unique<Task>([this] {
      auto ret = this->_clearTilesImpl();

      if (ret) {
        Lock lk(this->_m);
        if (this->_isSynchronizedNotSafe()) {
          this->_setStateNotSafe(STATE::READY);
          this->_doActionNotSafe();
        }
      }

      return QVariant(ret);
    });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
448 449

    // dispatch command and return.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
450
    auto ret = _dispatcher.dispatch(std::move(pTask));
451
    return ret.share();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
452
  } else {
453
    lk.unlock();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
454 455 456 457 458
    std::promise<QVariant> p;
    p.set_value(QVariant(false));
    return p.get_future();
  }
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
459

Valentin Platzgummer's avatar
Valentin Platzgummer committed
460
TileArray Nemointerface::Impl::getTiles(const IDArray &idArray) const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
461 462
  TileArray tileArray;

463
  Lock lk(this->_m);
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
  if (this->ready()) {
    for (const auto &id : idArray) {
      const auto it = _remoteTiles.find(id);
      if (it != _remoteTiles.end()) {
        MeasurementTile copy;
        copy.setId(it->second->id());
        copy.setProgress(it->second->progress());
        copy.setPath(it->second->tile());
        tileArray.append(std::move(copy));
      }
    }
  } else {
    for (const auto &id : idArray) {
      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
485 486 487 488 489 490
    }
  }

  return tileArray;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
491
TileArray Nemointerface::Impl::getAllTiles() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
492 493
  TileArray tileArray;

494
  Lock lk(this->_m);
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
  if (this->ready()) {
    for (const auto &entry : _remoteTiles) {
      auto pTile = entry.second;
      MeasurementTile copy;
      copy.setId(pTile->id());
      copy.setProgress(pTile->progress());
      copy.setPath(pTile->tile());
      tileArray.append(std::move(copy));
    }

  } else {
    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
514 515 516 517 518
  }

  return tileArray;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
519
LogicalArray Nemointerface::Impl::containsTiles(const IDArray &idArray) const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
520 521
  LogicalArray logicalArray;

522
  Lock lk(this->_m);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
523
  for (const auto &id : idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
524 525
    const auto &it = _localTiles.find(id);
    logicalArray.append(it != _localTiles.end());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
526 527 528 529 530
  }

  return logicalArray;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
531
std::size_t Nemointerface::Impl::size() const {
532 533 534 535

  Lock lk(this->_m);
  return _localTiles.size();
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
536

Valentin Platzgummer's avatar
Valentin Platzgummer committed
537
bool Nemointerface::Impl::empty() const {
538 539 540
  Lock lk(this->_m);
  return _localTiles.empty();
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
541

Valentin Platzgummer's avatar
Valentin Platzgummer committed
542
ProgressArray Nemointerface::Impl::getProgress() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
543 544
  ProgressArray progressArray;

545 546
  Lock lk(this->_m);
  if (this->_isSynchronizedNotSafe()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
547 548 549 550 551 552 553 554 555
    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
556 557 558 559 560
  }

  return progressArray;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
561
ProgressArray Nemointerface::Impl::getProgress(const IDArray &idArray) const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
562 563
  ProgressArray progressArray;

564 565
  Lock lk(this->_m);
  if (this->_isSynchronizedNotSafe()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
566 567 568 569 570 571 572 573 574 575 576 577 578 579
    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
580 581 582 583
    }
  }

  return progressArray;
584 585
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
586
Nemointerface::STATUS Nemointerface::Impl::status() const {
587
  Lock lk(this->_m);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
588
  return _status(this->_state);
589 590
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
591
bool Nemointerface::Impl::running() const {
592 593 594
  Lock lk1(this->_m);
  return _runningNotSafe(this->_state);
}
595

Valentin Platzgummer's avatar
Valentin Platzgummer committed
596
bool Nemointerface::Impl::ready() const {
597 598 599
  Lock lk1(this->_m);
  return _readyNotSafe(this->_state);
}
600

Valentin Platzgummer's avatar
Valentin Platzgummer committed
601
bool Nemointerface::Impl::_sysSync() const {
602 603
  Lock lk1(this->_m);
  return _sysSyncNotSafe(this->_state);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
604 605
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
606
void Nemointerface::Impl::_onHeartbeatTimeout() {
607 608 609
  Lock lk1(this->_m);
  this->_setStateNotSafe(STATE::HEARTBEAT_TIMEOUT);
  this->_doActionNotSafe();
610 611
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
612 613
void Nemointerface::Impl::_onRosbridgeStateChanged() {
  auto rbState = this->_rosbridge.state();
614 615
  if (rbState == Rosbridge::STATE::CONNECTED) {
    Lock lk1(this->_m);
616 617
    if (this->_state == STATE::START_BRIDGE ||
        this->_state == STATE::WEBSOCKET_TIMEOUT) {
618 619
      this->_setStateNotSafe(STATE::WEBSOCKET_DETECTED);
      this->_doActionNotSafe();
620
    }
621 622
  } else if (rbState == Rosbridge::STATE::TIMEOUT) {
    Lock lk1(this->_m);
623
    if (this->_state == STATE::TRY_SETUP || this->_state == STATE::READY ||
624 625
        this->_state == STATE::WEBSOCKET_DETECTED ||
        this->_state == STATE::HEARTBEAT_TIMEOUT) {
626 627
      this->_setStateNotSafe(STATE::WEBSOCKET_TIMEOUT);
      this->_doActionNotSafe();
628 629 630 631
    }
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
632
bool Nemointerface::Impl::_userSync() const {
633 634 635
  Lock lk1(this->_m);
  return _userSyncNotSafe(this->_state);
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
636

Valentin Platzgummer's avatar
Valentin Platzgummer committed
637
const QString &Nemointerface::Impl::infoString() const {
638 639 640
  Lock lk1(this->_m);
  return _infoString;
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
641

Valentin Platzgummer's avatar
Valentin Platzgummer committed
642
const QString &Nemointerface::Impl::warningString() const {
643
  Lock lk1(this->_m);
644 645
  return _warningString;
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
646

Valentin Platzgummer's avatar
Valentin Platzgummer committed
647 648 649 650 651
const QString &Nemointerface::Impl::connectionString() const {
  return this->_connectionString;
}

bool Nemointerface::Impl::_updateProgress(const ProgressArray &pArray) {
652

653
  ProgressArray copy;
654
  bool error = false;
655 656 657

  Lock lk1(this->_m);
  for (auto itLP = pArray.begin(); itLP != pArray.end(); ++itLP) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
658

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
661 662
    if (Q_LIKELY(it != _remoteTiles.end())) {
      it->second->setProgress(itLP->progress());
663
      copy.push_back(*itLP);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
664
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
665
      qCDebug(NemointerfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
666
          << "_updateProgress(): tile with id " << itLP->id() << " not found.";
667
      error = true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
668 669
    }
  }
670
  lk1.unlock();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
671

672 673
  if (copy.size() > 0) {
    emit _parent->progressChanged(copy);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
674
  }
675

676
  return !error;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
677 678
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
679
void Nemointerface::Impl::_onHeartbeatReceived(const QNemoHeartbeat &) {
680 681 682 683 684 685 686 687
  INVM(this->_parent,
       ([this]() mutable { this->_timeoutTimer.start(NO_HEARTBEAT_TIMEOUT); }))

  Lock lk(this->_m);
  if (this->_state == STATE::TRY_SETUP ||
      this->_state == STATE::HEARTBEAT_TIMEOUT) {
    this->_setStateNotSafe(STATE::READY);
    this->_doActionNotSafe();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
688 689 690
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
691
void Nemointerface::Impl::_setInfoStringNotSafe(const QString &info) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
692 693
  if (_infoString != info) {
    _infoString = info;
694 695 696 697

    // emit signal later, can't emit while mutex locked!
    QTimer::singleShot(5, this->_parent,
                       [this] { emit this->_parent->infoStringChanged(); });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
698 699 700
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
701
void Nemointerface::Impl::_setWarningStringNotSafe(const QString &warning) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
702 703
  if (_warningString != warning) {
    _warningString = warning;
704 705 706 707

    // emit signal later, can't emit while mutex locked!
    QTimer::singleShot(5, this->_parent,
                       [this] { emit this->_parent->warningStringChanged(); });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
708 709 710
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
711
void Nemointerface::Impl::_setInfoString(const QString &info) {
712 713 714 715
  Lock lk(this->_m);
  _setInfoStringNotSafe(info);
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
716
void Nemointerface::Impl::_setWarningString(const QString &warning) {
717 718 719
  Lock lk(this->_m);
  _setWarningStringNotSafe(warning);
}
720

Valentin Platzgummer's avatar
Valentin Platzgummer committed
721
void Nemointerface::Impl::_doSetup() {
722
  // create task
723
  auto pTask = std::make_unique<nemo_interface::Task>([this] {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
724
    auto &rb = this->_rosbridge;
725
    auto &disp = this->_dispatcher;
726

727 728 729 730
    // check if required services are available
    auto cond = [&disp] { return !disp.isInterruptionRequested(); };
    for (const auto &cc : requiredServices) {
      QString s(cc);
731

732
      this->_setInfoString("Waiting for required service " + s);
733

Valentin Platzgummer's avatar
Valentin Platzgummer committed
734
      auto available = rb.waitForService(cc, cond);
735 736
      if (!available) {
        return QVariant(false);
737
      }
738
    }
739

740 741
    // check if version is compatible{
    this->_setInfoString("Checking version.");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
742
    auto version = _callGetVersion(disp, rb);
743 744 745 746 747 748 749 750 751 752 753 754
    if (version != _localVersion) {
      this->_setWarningString(
          "Version checking failed. Local protocol version (" +
          QString(_localVersion) + ") does not match remote version (" +
          version + ").");
      return QVariant(false);
    }

    // check if required topics are available
    for (const auto &cc : requiredTopics) {
      QString s(cc);
      this->_setInfoString("Waiting for required topic " + s);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
755
      auto available = rb.waitForTopic(cc, cond);
756 757 758 759 760 761
      if (!available) {
        return QVariant(false);
      }
    }

    // subscribe topics
Valentin Platzgummer's avatar
Valentin Platzgummer committed
762
    rb.subscribeTopic(progressTopic, [this](const QJsonObject &o) {
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
      ros_bridge::messages::nemo_msgs::progress_array::ProgressArray
          progressArray;
      if (ros_bridge::messages::nemo_msgs::progress_array::fromJson(
              o, 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;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
778
          }
779

780
          if (rangeError) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
781
            qCWarning(NemointerfaceLog) << progressTopic
782
                                        << " progress out "
783 784 785
                                           "of range, value was set to: "
                                        << lp.progress();
          }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
786
        }
787 788 789
        auto ret = this->_updateProgress(progressArray.progress_array());
        if (!ret)
          this->_setWarningString("Progress update failed.");
790
      } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
791
        qCWarning(NemointerfaceLog) << progressTopic
792
                                    << " not able to "
793 794 795 796 797 798
                                       "create ProgressArray form json: "
                                    << o;
      }
    });

    using namespace ros_bridge::messages;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
799
    rb.subscribeTopic(heartbeatTopic, [this](const QJsonObject &o) {
800 801 802 803
      nemo_msgs::heartbeat::Heartbeat heartbeat;
      if (nemo_msgs::heartbeat::fromJson(o, heartbeat)) {
        this->_onHeartbeatReceived(heartbeat);
      } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
804
        qCWarning(NemointerfaceLog) << heartbeatTopic
805 806 807 808 809
                                    << " not able to "
                                       "create Heartbeat form json: "
                                    << o;
      }
    });
810

811 812 813 814 815 816
    // now ready
    INVM(this->_parent, ([this]() mutable {
           this->_timeoutTimer.start(NO_HEARTBEAT_TIMEOUT);
         }))
    _setInfoString("");
    _setWarningString("");
817 818 819
    return QVariant(true);
  });

820 821
  auto f = _dispatcher.dispatch(std::move(pTask));
  Q_UNUSED(f);
822 823
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
824
void Nemointerface::Impl::_synchronize() {
825 826
  Lock lk(this->_m);
  if (this->_state == STATE::READY || this->_state == STATE::SYNC_ERROR) {
827

828 829
    _setStateNotSafe(STATE::SYS_SYNC);
    _doActionNotSafe();
830

831 832 833 834 835 836 837 838 839
    // copy tiles.
    auto pTileArray = std::make_shared<QVector<std::shared_ptr<const Tile>>>();
    for (auto it = _localTiles.begin(); it != _localTiles.end(); ++it) {
      pTileArray->push_back(it->second);
    }
    lk.unlock();

    // create cmd.
    auto pTask = std::make_unique<nemo_interface::Task>([this, pTileArray] {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
840
      auto &rb = this->_rosbridge;
841 842 843
      auto &disp = this->_dispatcher;
      // are _localTiles and _remoteTiles synced?

Valentin Platzgummer's avatar
Valentin Platzgummer committed
844
      auto remoteTiles = this->_callGetAllTiles(disp, rb);
845 846 847 848 849 850 851 852

      // create tile map;
      std::map<QString, std::shared_ptr<Tile>> tempMap;
      for (auto &&pTile : remoteTiles) {
        auto it = tempMap.find(pTile->id());
        if (Q_LIKELY(it == tempMap.end())) {
          tempMap.insert(std::make_pair(pTile->id(), pTile));
        } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
853
          qCDebug(NemointerfaceLog)
854 855 856 857
              << "_synchronizeIfNeccessary(): remoteTiles contains "
                 "duplicate id";
        }
      }
858

859 860 861 862 863 864 865 866 867
      // compare with pTileArray
      bool synced = true;
      for (auto &&pTile : *pTileArray) {
        auto it = tempMap.find(pTile->id());
        if (it == tempMap.end() || it->second->tile() != pTile->tile()) {
          synced = false;
          break;
        }
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
868

869 870 871 872 873 874 875 876
      if (!synced) {
        auto success = this->_clearTilesImpl();
        if (!success) {
          Lock lk(this->_m);
          _setStateNotSafe(STATE::SYNC_ERROR);
          _doActionNotSafe();
          return QVariant(false);
        }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
877

878 879 880 881
        auto pIdArray = std::make_shared<IDArray>();
        for (auto &&pTile : *pTileArray) {
          pIdArray->push_back(pTile->id());
        }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
882

883
        success = this->_addTilesImpl(pTileArray, pIdArray);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
884

885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
        if (!success) {
          Lock lk(this->_m);
          _setStateNotSafe(STATE::SYNC_ERROR);
          _doActionNotSafe();
          return QVariant(false);
        }
      } else {
        // update progress
        this->_clearTilesRemote();
        auto ret = this->_addTilesRemote(*pTileArray);

        if (ret) {
          ProgressArray progress;
          for (auto &&pTile : remoteTiles) {
            progress.push_back(LabeledProgress(pTile->progress(), pTile->id()));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
900
          }
901 902
          ret = _updateProgress(progress);
        }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
903

904 905 906 907 908 909
        if (!ret) {
          Lock lk(this->_m);
          this->_setStateNotSafe(STATE::SYNC_ERROR);
          this->_doActionNotSafe();
          lk.unlock();
          this->_setWarningString("Getting progress failed.");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
910
          qCDebug(NemointerfaceLog)
911 912 913
              << "_addTilesImpl(): _updateProgress failed: unknown id.";
          return QVariant(false);
        }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
914
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
915

916 917 918 919 920 921 922 923 924 925
      // check if local versions are still synced (user could habe modified
      // _localTiles).
      Lock lk(this->_m);
      if (_isSynchronizedNotSafe()) {
        _setStateNotSafe(STATE::READY);
        _doActionNotSafe();
      } else {
        INVM(this->_parent, [this] { this->_synchronize(); })
      }
      lk.unlock();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
926

927 928
      return QVariant(true);
    });
929 930 931

    // dispatch command.
    auto ret = _dispatcher.dispatch(std::move(pTask));
932 933
    Q_UNUSED(ret);
    INVM(this->_parent, [this] { this->_syncTimer.start(SYNC_INTERVAL); })
934
  } else {
935
    INVM(this->_parent, [this] { this->_syncTimer.start(SYNC_RETRY_INTERVAL); })
936 937 938
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
939
void Nemointerface::Impl::_tryRestart() {
940 941 942 943 944 945 946 947 948 949 950 951
  if (this->running()) {
    if (_dispatcher.idle()) {
      qDebug() << "_tryRestart: restarting";
      this->stop();
      this->start();
      _restartTimer.start(RESTART_INTERVAl);
    } else {
      _restartTimer.start(RESTART_RETRY_INTERVAl);
    }
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
952
bool Nemointerface::Impl::_isSynchronizedNotSafe() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
953
  return _localTiles.size() == _remoteTiles.size() &&
Valentin Platzgummer's avatar
Valentin Platzgummer committed
954 955 956 957 958
         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
959
bool Nemointerface::Impl::_isSynchronized() const {
960 961 962 963
  Lock lk(this->_m);
  return _isSynchronizedNotSafe();
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
964
void Nemointerface::Impl::_doActionNotSafe() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
965
  static bool resetDone = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
966
  switch (this->_state) {
967 968 969 970 971 972 973 974
  case STATE::STOPPED: {
    std::promise<void> p;
    INVM(this->_parent, ([this]() mutable {
           this->_timeoutTimer.stop();
           this->_restartTimer.stop();
           this->_syncTimer.stop();
         }))

Valentin Platzgummer's avatar
Valentin Platzgummer committed
975 976
    if (this->_rosbridge.state() != Rosbridge::STATE::STOPPED) {
      this->_rosbridge.stop();
977
    }
978 979 980 981 982 983 984 985 986 987 988
    _dispatcher.stop();
    _dispatcher.clear();

    _setInfoStringNotSafe("");
    _setWarningStringNotSafe("");

  } break;

  case STATE::START_BRIDGE: {
    INVM(this->_parent,
         ([this]() mutable { this->_restartTimer.start(RESTART_INTERVAl); }))
989

Valentin Platzgummer's avatar
Valentin Platzgummer committed
990
    this->_rosbridge.start();
991
  } break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
992
  case STATE::WEBSOCKET_DETECTED:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
993
    resetDone = false;
994 995
    this->_setStateNotSafe(STATE::TRY_SETUP);
    this->_doActionNotSafe();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
996
    break;
997
  case STATE::TRY_SETUP:
998
    this->_doSetup();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
999
    break;
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
  case STATE::READY: {
    INVM(this->_parent,
         ([this]() mutable { this->_syncTimer.start(SYNC_INTERVAL); }))

    if (!_isSynchronizedNotSafe()) {
      // can't call this here directly.
      QTimer::singleShot(100, this->_parent, [this] { this->_synchronize(); });
    }

    _setInfoStringNotSafe("");
    _setWarningStringNotSafe("");
  } break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1012 1013
  case STATE::USER_SYNC:
  case STATE::SYS_SYNC:
1014
  case STATE::SYNC_ERROR:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1015
    break;
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  case STATE::HEARTBEAT_TIMEOUT: {
    INVM(this->_parent, ([this]() mutable { this->_syncTimer.stop(); }))

  } break;
  case STATE::WEBSOCKET_TIMEOUT: {
    INVM(this->_parent, ([this]() mutable {
           this->_timeoutTimer.stop();
           this->_syncTimer.stop();
         }))

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1026 1027
    if (!resetDone) {
      resetDone = true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1028 1029
      this->_rosbridge.stop();
      this->_rosbridge.start();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1030
    }
1031 1032 1033 1034 1035 1036
    _dispatcher.stop();
    _dispatcher.clear();

    _setInfoStringNotSafe("");
    _setWarningStringNotSafe("");
  } break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1037
  };
1038 1039
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1040
bool Nemointerface::Impl::_callAddTiles(
1041 1042
    const QVector<std::shared_ptr<const Tile>> &tileArray, Dispatcher &d,
    Rosbridge &rb) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1043

1044
  // qDebug() << "_callAddTiles called";
1045

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1046
  // create json object
1047
  QJsonArray jsonTileArray;
1048
  for (auto &&tile : tileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1049
    using namespace ros_bridge::messages;
1050 1051
    QJsonObject jsonTile;
    if (!nemo_msgs::tile::toJson(*tile, jsonTile)) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1052
      qCDebug(NemointerfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1053 1054 1055 1056
          << "addTiles(): not able to create json object: tile id: "
          << tile->id() << " progress: " << tile->progress()
          << " points: " << tile->tile();
    }
1057
    jsonTileArray.append(std::move(jsonTile));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1058
  } // for
1059

1060 1061
  QJsonObject req;
  req["in_tile_array"] = std::move(jsonTileArray);
1062

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1063 1064 1065
  // create response handler.
  auto promise_response = std::make_shared<std::promise<bool>>();
  auto future_response = promise_response->get_future();
1066 1067
  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
    // check if transaction was successfull
1068 1069
    if (o.contains("success") && o["success"].isBool()) {
      promise_response->set_value(o["success"].toBool());
1070
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1071
      qCWarning(NemointerfaceLog)
1072
          << addTilesService << " no \"success\" key or wrong type: " << o;
1073 1074 1075
      promise_response->set_value(false);
    }
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1076 1077

  // call service.
1078
  rb.callService(addTilesService, responseHandler, req);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089

  // 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 ||
1090
           d.isInterruptionRequested());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1091 1092

  if (abort) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1093
    qCWarning(NemointerfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1094
        << "addTiles(): Websocket not responding to request.";
1095
    return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1096 1097 1098 1099
  }

  // transaction error?
  if (!future_response.get()) {
1100
    return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1101 1102 1103
  }

  // return success
1104
  return true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1105 1106
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1107
bool Nemointerface::Impl::_callRemoveTiles(const IDArray &pIdArray,
1108
                                           Dispatcher &disp, Rosbridge &rb) {
1109
  // qDebug() << "_callRemoveTiles called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1110

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1111
  // create json object
1112
  QJsonArray jsonIdArray;
1113
  for (auto &&id : pIdArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1114
    using namespace ros_bridge::messages;
1115
    jsonIdArray.append(id);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1116
  } // for
1117 1118
  QJsonObject req;
  req["ids"] = std::move(jsonIdArray);
1119

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1120 1121 1122
  // create response handler.
  auto promise_response = std::make_shared<std::promise<bool>>();
  auto future_response = promise_response->get_future();
1123 1124 1125
  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
    // check if transaction was successfull
    QString msg = QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
1126 1127
    if (o.contains("success") && o["success"].isBool()) {
      promise_response->set_value(o["success"].toBool());
1128
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1129
      qCWarning(NemointerfaceLog)
1130
          << removeTilesService << " no \"success\" key or wrong type: " << msg;
1131 1132 1133
      promise_response->set_value(false);
    }
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1134 1135

  // call service.
1136
  rb.callService(removeTilesService, responseHandler, req);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147

  // 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 ||
1148
           disp.isInterruptionRequested());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1149 1150

  if (abort) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1151
    qCWarning(NemointerfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1152
        << "remove_tiles(): Websocket not responding to request.";
1153
    return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1154 1155 1156 1157
  }

  // transaction error?
  if (!future_response.get()) {
1158
    return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1159 1160
  }

1161
  return true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1162 1163
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1164
bool Nemointerface::Impl::_callClearTiles(Dispatcher &disp, Rosbridge &rb) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1165

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1166 1167 1168
  // create response handler.
  auto promise_response = std::make_shared<std::promise<bool>>();
  auto future_response = promise_response->get_future();
1169
  auto responseHandler = [promise_response](const QJsonObject &) mutable {
1170
    // check if transaction was successfull
1171
    promise_response->set_value(true);
1172
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1173 1174

  // call service.
1175
  rb.callService(clearTilesService, responseHandler, QJsonObject());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186

  // 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 ||
1187
           disp.isInterruptionRequested());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1188 1189

  if (abort) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1190
    qCWarning(NemointerfaceLog) << "Websocket not responding to request.";
1191
    return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1192 1193 1194 1195
  }

  // transaction failed?
  if (!future_response.get()) {
1196
    return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1197 1198
  }

1199
  return true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1200 1201
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1202
ProgressArray Nemointerface::Impl::_callGetProgress(const IDArray &pIdArray,
1203 1204
                                                    Dispatcher &disp,
                                                    Rosbridge &rb) {
1205
  // qDebug() << "_callGetProgress called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1206