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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1207
  // create json object
1208
  QJsonArray jsonIdArray;
1209
  for (auto &&id : pIdArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1210
    using namespace ros_bridge::messages;
1211
    jsonIdArray.append(id);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1212
  } // for
1213 1214
  QJsonObject req;
  req["ids"] = std::move(jsonIdArray);
1215

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1216 1217 1218 1219
  // 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();
1220 1221
  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
    // check if transaction was successfull
1222 1223 1224 1225 1226 1227 1228
    ros_bridge::messages::nemo_msgs::progress_array::ProgressArray
        progressArrayMsg;
    if (ros_bridge::messages::nemo_msgs::progress_array::fromJson(
            o, progressArrayMsg)) {
      auto pArray = std::make_shared<ProgressArray>();
      *pArray = std::move(progressArrayMsg.progress_array());
      promise_response->set_value(pArray);
1229
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1230
      qCWarning(NemointerfaceLog) << getProgressService
1231 1232
                                  << " error while creating ProgressArray "
                                     "from json.";
1233 1234 1235
      promise_response->set_value(nullptr);
    }
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1236 1237

  // call service.
1238
  rb.callService(getProgressService, responseHandler, req);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249

  // 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 ||
1250
           disp.isInterruptionRequested());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1251 1252

  if (abort) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1253
    qCWarning(NemointerfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1254
        << "all_remove_tiles(): Websocket not responding to request.";
1255
    return ProgressArray();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1256 1257 1258
  }

  // return success
1259
  return *future_response.get();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1260 1261
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1262
ProgressArray Nemointerface::Impl::_callGetAllProgress(Dispatcher &disp,
1263
                                                       Rosbridge &rb) {
1264
  // qDebug() << "_callGetAllProgress called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1265 1266 1267 1268 1269

  // 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();
1270
  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1271
    // check if transaction was successfull
1272 1273 1274 1275 1276 1277 1278
    ros_bridge::messages::nemo_msgs::progress_array::ProgressArray
        progressArrayMsg;
    if (ros_bridge::messages::nemo_msgs::progress_array::fromJson(
            o, progressArrayMsg)) {
      auto pArray = std::make_shared<ProgressArray>();
      *pArray = std::move(progressArrayMsg.progress_array());
      promise_response->set_value(pArray);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1279
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1280
      qCWarning(NemointerfaceLog) << getAllProgressService
1281 1282 1283
                                  << " error while creating ProgressArray "
                                     "from json. msg: "
                                  << o;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1284 1285 1286 1287 1288
      promise_response->set_value(nullptr);
    }
  };

  // call service.
1289
  rb.callService(getAllProgressService, responseHandler, QJsonObject());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300

  // 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 ||
1301
           disp.isInterruptionRequested());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1302 1303

  if (abort) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1304
    qCWarning(NemointerfaceLog)
1305 1306
        << "_callGetAllProgress(): Websocket not responding to request.";
    return ProgressArray();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1307 1308 1309
  }

  // transaction error?
1310
  return *future_response.get();
1311 1312
}

1313
QVector<std::shared_ptr<Tile>>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1314
Nemointerface::Impl::_callGetAllTiles(Dispatcher &disp, Rosbridge &rb) {
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
  // qDebug() << "_callGetAllProgress called";

  // create response handler.
  typedef std::shared_ptr<QVector<std::shared_ptr<Tile>>> ResponseType;
  auto promise_response = std::make_shared<std::promise<ResponseType>>();
  auto future_response = promise_response->get_future();

  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
    const char *const tileArrayKey = "tile_array";
    // check if transaction was successfull
    if (o.contains(tileArrayKey) && o[tileArrayKey].isArray()) {
      auto pArray = std::make_shared<QVector<std::shared_ptr<Tile>>>();
      const auto jsonArray = o[tileArrayKey].toArray();
      for (int i = 0; i < jsonArray.size(); ++i) {
        if (jsonArray[i].isObject()) {
          QJsonObject o = jsonArray[i].toObject();
          auto tile = std::make_shared<Tile>();
          if (ros_bridge::messages::nemo_msgs::tile::fromJson(o, *tile)) {
            pArray->push_back(tile);
          } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1335
            qCWarning(NemointerfaceLog)
1336
                << getAllTilesService << " error while creating tile.";
1337 1338 1339
            promise_response->set_value(nullptr);
          }
        } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1340
          qCWarning(NemointerfaceLog)
1341
              << getAllTilesService << " json array does not contain objects.";
1342 1343 1344 1345 1346 1347
          promise_response->set_value(nullptr);
        }
      }
      // success!
      promise_response->set_value(pArray);
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1348
      qCWarning(NemointerfaceLog)
1349
          << getAllTilesService << " no tile_array key or wrong type.";
1350 1351 1352 1353 1354
      promise_response->set_value(nullptr);
    }
  };

  // call service.
1355
  rb.callService(getAllTilesService, responseHandler, QJsonObject());
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366

  // 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 ||
1367
           disp.isInterruptionRequested());
1368 1369

  if (abort) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1370
    qCWarning(NemointerfaceLog)
1371
        << "all_remove_tiles(): Websocket not responding to request.";
1372
    return QVector<std::shared_ptr<Tile>>();
1373 1374
  }

1375
  return *future_response.get();
1376 1377
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1378
QString Nemointerface::Impl::_callGetVersion(Dispatcher &d, Rosbridge &rb) {
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391

  // create response handler.
  typedef QString ResponseType;
  auto promise_response = std::make_shared<std::promise<ResponseType>>();
  auto future_response = promise_response->get_future();

  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
    const char *const versionKey = "version";
    // check if transaction was successfull
    if (o.contains(versionKey) && o[versionKey].isString()) {
      const auto version = o[versionKey].toString();
      promise_response->set_value(version);
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1392
      qCWarning(NemointerfaceLog)
1393
          << getVersionService << " no version key or wrong type.";
1394 1395 1396 1397 1398
      promise_response->set_value("error!");
    }
  };

  // call service.
1399
  rb.callService(getVersionService, responseHandler, QJsonObject());
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410

  // 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 ||
1411
           d.isInterruptionRequested());
1412 1413

  if (abort) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1414
    qCWarning(NemointerfaceLog)
1415
        << "all_remove_tiles(): Websocket not responding to request.";
1416
    return "unknown_version";
1417 1418 1419 1420 1421
  }

  // transaction error?
  auto version = future_response.get();
  if (version == "error!") {
1422
    return "unknown_version";
1423 1424 1425
  }

  // return success
1426
  return version;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1427 1428
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1429
bool Nemointerface::Impl::_addTilesRemote(
1430
    const QVector<std::shared_ptr<const Tile>> tileArray) {
1431

1432
  // qDebug() << "_addTilesRemote called";
1433

1434 1435 1436
  QVector<std::shared_ptr<Tile>> copy;
  for (auto &&pTile : tileArray) {
    copy.push_back(std::make_shared<Tile>(*pTile));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1437
  }
1438
  return _addTilesRemote(copy);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1439 1440
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1441
bool Nemointerface::Impl::_addTilesRemote(
1442
    const QVector<std::shared_ptr<Tile>> &tileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1443

1444
  bool error = false;
1445
  bool anyChange = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1446

1447 1448
  Lock lk(this->_m);
  for (auto &&pTile : tileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1449 1450 1451 1452
    auto id = pTile->id();
    auto it = _remoteTiles.find(id);
    if (Q_LIKELY(it == _remoteTiles.end())) {
      auto ret = _remoteTiles.insert(std::make_pair(id, pTile));
1453
      anyChange = true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1454 1455 1456
      Q_ASSERT(ret.second == true);
      Q_UNUSED(ret);
    } else {
1457
      if (pTile->tile() != it->second->tile()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1458
        qCWarning(NemointerfaceLog)
1459
            << "_addTilesRemote: tiles differ but have the same id.";
1460 1461
        error = true;
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1462 1463 1464
    }
  }

1465 1466 1467
  lk.unlock();
  if (anyChange > 0) {
    emit this->_parent->tilesChanged();
1468 1469
  }

1470
  return !error;
1471 1472
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1473
void Nemointerface::Impl::_removeTilesRemote(const IDArray &idArray) {
1474
  // qDebug() << "_removeTilesRemote called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1475 1476
  bool anyChange = false;

1477 1478
  Lock lk(this->_m);
  for (auto &&id : idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1479 1480 1481 1482 1483
    auto it = _remoteTiles.find(id);
    if (Q_LIKELY(it != _remoteTiles.end())) {
      _remoteTiles.erase(it);
      anyChange = true;
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1484
      qCWarning(NemointerfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1485 1486 1487 1488 1489
          << "_removeTilesRemote: tile with unknown id " << id << ".";
    }
  }

  if (anyChange) {
1490
    emit this->_parent->tilesChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1491
  }
1492
}
1493

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1494
void Nemointerface::Impl::_clearTilesRemote() {
1495 1496
  Lock lk(this->_m);
  _clearTilesRemoteNotSafe();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1497 1498
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1499
void Nemointerface::Impl::_clearTilesRemoteNotSafe() {
1500
  // qDebug() << "_clearTilesRemote called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1501 1502 1503 1504 1505
  if (_remoteTiles.size() > 0) {
    _remoteTiles.clear();
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1506
bool Nemointerface::Impl::_setStateNotSafe(STATE newState) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1507
  if (newState != this->_state) {
1508
    auto oldState = this->_state;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1509 1510
    this->_state = newState;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1511
    qCDebug(NemointerfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1512 1513 1514 1515
        << "state: " << _toString(oldState) << " -> " << _toString(newState);
    auto oldStatus = _status(oldState);
    auto newStatus = _status(newState);
    if (oldStatus != newStatus) {
1516 1517 1518
      // emit signal later
      QTimer::singleShot(5, this->_parent,
                         [this] { emit this->_parent->statusChanged(); });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1519 1520
    }

1521 1522 1523 1524
    if (_runningNotSafe(oldState) != _runningNotSafe(newState)) {
      // emit signal later
      QTimer::singleShot(5, this->_parent,
                         [this] { emit this->_parent->runningChanged(); });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1525 1526
    }

1527 1528 1529 1530 1531 1532
    return true;
  } else {
    return false;
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1533
bool Nemointerface::Impl::_readyNotSafe(Nemointerface::Impl::STATE s) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1534 1535 1536
  return s == STATE::READY;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1537
bool Nemointerface::Impl::_userSyncNotSafe(Nemointerface::Impl::STATE s) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1538
  return s == STATE::USER_SYNC;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1539 1540
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1541
bool Nemointerface::Impl::_sysSyncNotSafe(Nemointerface::Impl::STATE s) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1542
  return s == STATE::SYS_SYNC;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1543 1544
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1545
bool Nemointerface::Impl::_runningNotSafe(Nemointerface::Impl::STATE s) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1546 1547 1548
  return s != STATE::STOPPED;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1549 1550 1551
Nemointerface::STATUS
Nemointerface::Impl::_status(Nemointerface::Impl::STATE state) {
  Nemointerface::STATUS status;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1552 1553
  switch (state) {
  case STATE::STOPPED:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1554
    status = Nemointerface::STATUS::NOT_CONNECTED;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1555 1556
    break;
  case STATE::START_BRIDGE:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1557
    status = Nemointerface::STATUS::NOT_CONNECTED;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1558 1559
    break;
  case STATE::WEBSOCKET_DETECTED:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1560
    status = Nemointerface::STATUS::WEBSOCKET_DETECTED;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1561
    break;
1562
  case STATE::TRY_SETUP:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1563
    status = Nemointerface::STATUS::WEBSOCKET_DETECTED;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1564 1565
    break;
  case STATE::READY:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1566
    status = Nemointerface::STATUS::READY;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1567
    break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1568 1569
  case STATE::USER_SYNC:
  case STATE::SYS_SYNC:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1570
    status = Nemointerface::STATUS::SYNC;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1571
    break;
1572
  case STATE::SYNC_ERROR:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1573
    status = Nemointerface::STATUS::ERROR;
1574
    break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1575 1576
  case STATE::WEBSOCKET_TIMEOUT:
  case STATE::HEARTBEAT_TIMEOUT:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1577
    status = Nemointerface::STATUS::TIMEOUT;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1578 1579 1580 1581 1582 1583
    break;
  }

  return status;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1584
QString Nemointerface::Impl::_toString(Nemointerface::Impl::STATE s) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1585 1586 1587 1588 1589 1590 1591
  switch (s) {
  case STATE::STOPPED:
    return QString("STOPPED");
  case STATE::START_BRIDGE:
    return QString("START_BRIDGE");
  case STATE::WEBSOCKET_DETECTED:
    return QString("WEBSOCKET_DETECTED");
1592
  case STATE::TRY_SETUP:
1593
    return QString("TRY_SETUP");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1594 1595
  case STATE::READY:
    return QString("READY");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1596
  case STATE::USER_SYNC:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1597
    return QString("SYNC_USER");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1598
  case STATE::SYS_SYNC:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1599
    return QString("SYNC_SYS");
1600 1601
  case STATE::SYNC_ERROR:
    return QString("SYNC_ERROR");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1602 1603 1604 1605 1606 1607 1608 1609
  case STATE::WEBSOCKET_TIMEOUT:
    return QString("WEBSOCKET_TIMEOUT");
  case STATE::HEARTBEAT_TIMEOUT:
    return QString("HEARTBEAT_TIMEOUT");
  }
  return "unknown state!";
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1610
QString Nemointerface::Impl::_toString(Nemointerface::STATUS s) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1611
  switch (s) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1612
  case Nemointerface::STATUS::NOT_CONNECTED:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1613
    return QString("NOT_CONNECTED");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1614
  case Nemointerface::STATUS::ERROR:
1615
    return QString("ERROR");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1616
  case Nemointerface::STATUS::READY:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1617
    return QString("READY");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1618
  case Nemointerface::STATUS::TIMEOUT:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1619
    return QString("TIMEOUT");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1620
  case Nemointerface::STATUS::WEBSOCKET_DETECTED:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1621
    return QString("WEBSOCKET_DETECTED");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1622
  case Nemointerface::STATUS::SYNC:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1623 1624 1625 1626 1627
    return QString("SYNC");
  }
  return "unknown state!";
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1628
bool Nemointerface::Impl::_addTilesImpl(
1629 1630
    std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray,
    std::shared_ptr<const IDArray> pIdArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1631
  auto &rb = this->_rosbridge;
1632 1633 1634
  auto &disp = this->_dispatcher;

  // add tiles
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1635
  bool success = this->_callAddTiles(*pTileArray, disp, rb);
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
  if (!success) {
    this->_setWarningString(
        "Adding tiles failed. This might indicate a poor connection.");
    return false;
  }

  auto ret = this->_addTilesRemote(*pTileArray);
  if (!ret) {
    Lock lk(this->_m);
    this->_setStateNotSafe(STATE::SYNC_ERROR);
    this->_doActionNotSafe();
    lk.unlock();
    this->_setWarningString("Adding tiles failed.");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1649
    qCDebug(NemointerfaceLog) << "_addTilesImpl(): _addTilesRemote return "
1650 1651 1652 1653 1654
                                 "false: different tiles with same id.";
    return false;
  }

  // fetch progress
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1655
  auto array = this->_callGetProgress(*pIdArray, disp, rb);
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
  if (array.size() != pIdArray->size()) {
    Lock lk(this->_m);
    this->_setStateNotSafe(STATE::SYNC_ERROR);
    this->_doActionNotSafe();
    lk.unlock();
    this->_setWarningString("Getting progress failed. This might "
                            "indicate a poor connection.");
    return false;
  }
  ret = this->_updateProgress(array);

  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
1673
    qCDebug(NemointerfaceLog)
1674 1675 1676 1677 1678 1679 1680
        << "_addTilesImpl(): _updateProgress failed: unknown id.";
    return false;
  }

  return true;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1681
bool Nemointerface::Impl::_removeTilesImpl(
1682
    std::shared_ptr<const IDArray> pIdArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1683
  auto &rb = this->_rosbridge;
1684 1685
  auto &disp = this->_dispatcher;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1686
  auto success = this->_callRemoveTiles(*pIdArray, disp, rb);
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
  if (!success) {
    Lock lk(this->_m);
    this->_setStateNotSafe(STATE::SYNC_ERROR);
    this->_doActionNotSafe();
    lk.unlock();
    this->_setWarningString("Removing tiles failed. This might "
                            "indicate a poor connection.");
    return false;
  }
  this->_removeTilesRemote(*pIdArray);

  return true;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1701 1702
bool Nemointerface::Impl::_clearTilesImpl() {
  auto &rb = this->_rosbridge;
1703 1704
  auto &disp = this->_dispatcher;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1705
  auto success = this->_callClearTiles(disp, rb);
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
  if (!success) {
    Lock lk(this->_m);
    this->_setStateNotSafe(STATE::SYNC_ERROR);
    this->_doActionNotSafe();
    lk.unlock();
    this->_setWarningString("Clear tiles failed. This might "
                            "indicate a poor connection.");
    return false;
  }
  this->_clearTilesRemote();

  return true;
}

1720 1721
// ===============================================================
// NemoInterface
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1722 1723 1724
Nemointerface::Nemointerface(const QString &connectionString)
    : QObject(),
      pImpl(std::make_unique<Nemointerface::Impl>(connectionString, this)) {}
1725

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1726
Nemointerface::~Nemointerface() {}
1727

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1728
void Nemointerface::start() { this->pImpl->start(); }
1729

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1730
void Nemointerface::stop() { this->pImpl->stop(); }
1731

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1732
std::shared_future<QVariant>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1733
Nemointerface::addTiles(const TileArray &tileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1734 1735 1736 1737 1738
  TilePtrArray ptrArray;
  for (const auto &tile : tileArray) {
    ptrArray.push_back(const_cast<MeasurementTile *>(&tile));
  }
  return this->pImpl->addTiles(ptrArray);
1739 1740
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1741
std::shared_future<QVariant>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1742
Nemointerface::addTiles(const TilePtrArray &tileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1743
  return this->pImpl->addTiles(tileArray);
1744 1745
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1746
std::shared_future<QVariant>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1747
Nemointerface::removeTiles(const IDArray &idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1748 1749 1750
  return this->pImpl->removeTiles(idArray);
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1751
std::shared_future<QVariant> Nemointerface::clearTiles() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1752 1753
  return this->pImpl->clearTiles();
}
1754

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1755
TileArray Nemointerface::getTiles(const IDArray &idArray) const {
1756 1757 1758
  return this->pImpl->getTiles(idArray);
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1759
TileArray Nemointerface::getAllTiles() const {
1760 1761
  return this->pImpl->getAllTiles();
}
1762

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1763
LogicalArray Nemointerface::containsTiles(const IDArray &idArray) const {
1764 1765 1766
  return this->pImpl->containsTiles(idArray);
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1767
std::size_t Nemointerface::size() const { return this->pImpl->size(); }
1768

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1769
bool Nemointerface::empty() const { return this->pImpl->empty(); }
1770

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1771
ProgressArray Nemointerface::getProgress() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1772 1773 1774
  return this->pImpl->getProgress();
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1775
ProgressArray Nemointerface::getProgress(const IDArray &idArray) const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1776 1777 1778
  return this->pImpl->getProgress(idArray);
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1779
Nemointerface::STATUS Nemointerface::status() const {
1780 1781 1782
  return this->pImpl->status();
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1783
QString Nemointerface::statusString() const {
1784 1785 1786
  return statusMap.at(this->pImpl->status());
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1787
QString Nemointerface::infoString() const { return this->pImpl->infoString(); }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1788

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1789
QString Nemointerface::warningString() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1790 1791
  return this->pImpl->warningString();
}
1792

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1793
QString Nemointerface::editorQml() {
1794 1795 1796
  return QStringLiteral("NemoInterface.qml");
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
bool Nemointerface::running() const { return this->pImpl->running(); }

QString Nemointerface::connectionString() {
  return this->pImpl->connectionString();
}

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

NemointerfaceFactory *NemointerfaceFactory::instance() {
  return GenericSingelton<NemointerfaceFactory>::instance(
      NemointerfaceFactory::createInstance);
}

std::shared_ptr<Nemointerface>
NemointerfaceFactory::create(const QString &connectionString) {
  auto it = _map.find(connectionString);

  // If the interface was cereated, is it still in use?
  if (it != _map.end()) {
    auto weak = it->second;
    if (!weak.expired()) {
      // Still in use, can't create an other instance.
      return nullptr;
    } else {
      // Not in use, erase map entry.
      it = _map.erase(it);
    }
  }

  Q_ASSERT(it == _map.end());
  if (it == _map.end()) {
    auto p = std::make_shared<Nemointerface>(connectionString);

    if (p) {
      QQmlEngine::setObjectOwnership(p.get(), QQmlEngine::CppOwnership);
      auto ret = _map.insert(
          std::make_pair(connectionString, std::weak_ptr<Nemointerface>(p)));

      // insert error?
      Q_ASSERT(ret.second == true);
      if (ret.second != true) {
        qCCritical(NemointerfaceLog)
            << "NemointerfaceFactory::create() not able to insert pair.";
        return nullptr;
      }
    }

    return p;
  } else {
    qCCritical(NemointerfaceLog)
        << "NemointerfaceFactory::create() logical error.";
    return nullptr;
  }
}

bool NemointerfaceFactory::isCreatable(const QString &connectionString) {
  auto it = _map.find(connectionString);

  // if it was creaded, is it still in use?
  if (it != _map.end()) {
    if (it->second.expired()) {
      it = _map.erase(it);
      return true;
    } else {
      return false;
    }
  } else {
    return true;
  }
}