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

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

#include <shared_mutex>

12 13
#include <QJsonArray>
#include <QJsonObject>
14
#include <QTimer>
15
#include <QUrl>
16

17
#include "GenericSingelton.h"
18
#include "geometry/MeasurementArea.h"
19
#include "geometry/geometry.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
20
#include "nemo_interface/FutureWatcher.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

QGC_LOGGING_CATEGORY(NemoInterfaceLog, "NemoInterfaceLog")

34 35 36 37 38
#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
Valentin Platzgummer's avatar
Valentin Platzgummer committed
39
static constexpr auto maxResponseTime = std::chrono::milliseconds(10000);
40

41 42 43
static const char *progressTopic = "/nemo/progress";
static const char *heartbeatTopic = "/nemo/heartbeat";

Valentin Platzgummer's avatar
Valentin Platzgummer committed
44
using hrc = std::chrono::high_resolution_clock;
45
using ROSBridgePtr = std::shared_ptr<Rosbridge>;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
46 47 48 49

typedef ros_bridge::messages::nemo_msgs::tile::GenericTile<QGeoCoordinate,
                                                           QList>
    Tile;
50 51
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
52 53 54 55
typedef ros_bridge::messages::nemo_msgs::heartbeat::Heartbeat Heartbeat;
typedef nemo_interface::TaskDispatcher Dispatcher;
typedef nemo_interface::FutureWatcher<QVariant, std::shared_future>
    FutureWatcher;
56 57

class NemoInterface::Impl {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
58 59
  enum class STATE {
    STOPPED,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
60
    START_BRIDGE,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
61
    WEBSOCKET_DETECTED,
62
    TRY_SETUP,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
63 64
    USER_SYNC,
    SYS_SYNC,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
65
    READY,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
66 67
    WEBSOCKET_TIMEOUT,
    HEARTBEAT_TIMEOUT
Valentin Platzgummer's avatar
Valentin Platzgummer committed
68
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
69

Valentin Platzgummer's avatar
Valentin Platzgummer committed
70
public:
71
  Impl(NemoInterface *p);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
72
  ~Impl();
73 74 75 76

  void start();
  void stop();

Valentin Platzgummer's avatar
Valentin Platzgummer committed
77 78
  // Tile editing.
  // 	Functions that require communication to device.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
79 80 81
  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
82 83

  // 	Functions that don't require communication to device.
84 85 86 87 88
  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
89 90

  // Progress.
91 92
  ProgressArray getProgress() const;
  ProgressArray getProgress(const IDArray &idArray) const;
93

94 95 96
  NemoInterface::STATUS status() const;
  bool running() const; // thread safe
  bool ready() const;   // thread safe
Valentin Platzgummer's avatar
Valentin Platzgummer committed
97

98 99
  const QString &infoString() const;
  const QString &warningString() const;
100 101

private:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
102
  void _doTopicServiceSetup();
103 104 105
  void _checkVersion();
  void _subscribeProgressTopic();
  void _subscribeHearbeatTopic();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
106 107
  void _doAction();
  void _trySynchronize();
108 109
  void _synchronizeIfNeccessary();
  void _tryRestart();
110 111 112
  bool _isSynchronized() const;
  bool _userSync() const;          // thread safe
  bool _sysSync() const;           // thread safe
Valentin Platzgummer's avatar
Valentin Platzgummer committed
113
  void _onFutureWatcherFinished(); // thread safe
114
  void _onHeartbeatTimeout();      // thread safe
115
  void _onRosbridgeStateChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
116 117 118 119 120 121 122 123 124 125

  // called from dispatcher thread!
  QVariant _callAddTiles(
      std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray);
  // called from dispatcher thread!
  QVariant _callRemoveTiles(std::shared_ptr<IDArray> pIdArray);
  // called from dispatcher thread!
  QVariant _callClearTiles();
  // called from dispatcher thread!
  QVariant _callGetProgress(std::shared_ptr<IDArray> pIdArray);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
126
  QVariant _callGetAllProgress();
127 128
  QVariant _callGetAllTiles();
  QVariant _callGetVersion();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
129 130 131 132 133
  enum class CALL_NAME {
    ADD_TILES,
    REMOVE_TILES,
    CLEAR_TILES,
    GET_PROGRESS,
134 135 136
    GET_ALL_TILES,
    GET_ALL_PROGRESS,
    GET_VERSION
Valentin Platzgummer's avatar
Valentin Platzgummer committed
137
  };
138
  QString _toString(CALL_NAME name);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
139 140

  void _addTilesRemote(
141 142
      std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray,
      std::promise<bool> promise);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
143
  void
144 145
  _addTilesRemote2(std::shared_ptr<QVector<std::shared_ptr<Tile>>> pTileArray,
                   std::promise<bool> promise);
146 147 148
  void _setTiles(std::shared_ptr<QVector<std::shared_ptr<Tile>>> pTileArray,
                 std::promise<bool> promise);
  void _setVersion(QString version, std::promise<bool> promise);
149 150 151 152 153 154 155
  void _removeTilesRemote(std::shared_ptr<IDArray> idArray,
                          std::promise<bool> promise);
  void _clearTilesRemote(std::promise<bool> promise);
  void _updateProgress(std::shared_ptr<ProgressArray> pArray,
                       std::promise<bool> promise);
  void _onHeartbeatReceived(const QNemoHeartbeat &hb,
                            std::promise<bool> promise);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
156 157
  void _setInfoString(const QString &info);
  void _setWarningString(const QString &warning);
158

Valentin Platzgummer's avatar
Valentin Platzgummer committed
159
  bool _setState(STATE newState); // not thread safe
160

Valentin Platzgummer's avatar
Valentin Platzgummer committed
161
  static bool _ready(STATE s);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
162 163
  static bool _userSync(STATE s);
  static bool _sysSync(STATE s);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
164
  static bool _running(STATE s);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
165 166 167
  static NemoInterface::STATUS _status(STATE state);
  static QString _toString(STATE s);
  static QString _toString(NemoInterface::STATUS s);
168

169 170 171
  static QString _localVersion;
  QString _remoteVersion;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
172
  std::atomic<STATE> _state;
173 174 175
  std::atomic_bool _versionOK;
  std::atomic_bool _progressTopicOK;
  std::atomic_bool _heartbeatTopicOK;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
176
  std::atomic<CALL_NAME> _lastCall;
177
  ROSBridgePtr _pRosbridge;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
178 179 180
  TileMap _remoteTiles;
  TileMapConst _localTiles;
  NemoInterface *const _parent;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
181 182 183 184
  Dispatcher _dispatcher;
  QString _infoString;
  QString _warningString;
  QTimer _timeoutTimer;
185 186
  QTimer _syncTimer;
  QTimer _restartTimer;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
187
  QNemoHeartbeat _lastHeartbeat;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
188
  FutureWatcher _futureWatcher;
189 190
};

191 192
QString NemoInterface::Impl::_localVersion("V_1.0");

193 194 195 196
using StatusMap = std::map<NemoInterface::STATUS, QString>;
static StatusMap statusMap{
    std::make_pair<NemoInterface::STATUS, QString>(
        NemoInterface::STATUS::NOT_CONNECTED, "Not Connected"),
197 198
    std::make_pair<NemoInterface::STATUS, QString>(NemoInterface::STATUS::ERROR,
                                                   "ERROR"),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
199 200
    std::make_pair<NemoInterface::STATUS, QString>(NemoInterface::STATUS::SYNC,
                                                   "Synchronizing"),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
201 202
    std::make_pair<NemoInterface::STATUS, QString>(NemoInterface::STATUS::READY,
                                                   "Ready"),
203 204 205 206 207 208
    std::make_pair<NemoInterface::STATUS, QString>(
        NemoInterface::STATUS::TIMEOUT, "Timeout"),
    std::make_pair<NemoInterface::STATUS, QString>(
        NemoInterface::STATUS::WEBSOCKET_DETECTED, "Websocket Detected")};

NemoInterface::Impl::Impl(NemoInterface *p)
209 210
    : _state(STATE::STOPPED), _versionOK(false), _progressTopicOK(false),
      _heartbeatTopicOK(false), _parent(p) {
211 212 213 214 215 216 217

  // ROS Bridge.
  WimaSettings *wimaSettings =
      qgcApp()->toolbox()->settingsManager()->wimaSettings();
  auto connectionStringFact = wimaSettings->rosbridgeConnectionString();
  auto setConnectionString = [connectionStringFact, this] {
    auto connectionString = connectionStringFact->rawValue().toString();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
218

Valentin Platzgummer's avatar
Valentin Platzgummer committed
219 220
    bool wasRunning = this->running();
    this->stop();
221 222
    this->_pRosbridge = std::make_shared<Rosbridge>(
        QUrl(QString("ws://") + connectionString.toLocal8Bit().data()));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
223 224 225
    if (wasRunning) {
      this->start();
    }
226 227 228 229 230
  };
  connect(connectionStringFact, &SettingsFact::rawValueChanged,
          setConnectionString);
  setConnectionString();

Valentin Platzgummer's avatar
Valentin Platzgummer committed
231
  // Heartbeat timeout.
232 233
  connect(&this->_timeoutTimer, &QTimer::timeout,
          std::bind(&Impl::_onHeartbeatTimeout, this));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
234

235
  connect(this->_pRosbridge.get(), &Rosbridge::stateChanged, this->_parent,
236
          [this] { this->_onRosbridgeStateChanged(); });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
237

238
  connect(&this->_futureWatcher, &FutureWatcher::finished, this->_parent,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
239
          [this] { this->_onFutureWatcherFinished(); });
240 241 242 243 244 245

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

  connect(&this->_syncTimer, &QTimer::timeout, this->_parent,
          [this] { this->_synchronizeIfNeccessary(); });
246 247
}

248
NemoInterface::Impl::~Impl() { this->_pRosbridge->stop(); }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
249

250
void NemoInterface::Impl::start() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
251 252 253 254
  if (!running()) {
    this->_setState(STATE::START_BRIDGE);
    this->_doAction();
  }
255 256 257
}

void NemoInterface::Impl::stop() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
258 259 260 261
  if (running()) {
    this->_setState(STATE::STOPPED);
    this->_doAction();
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
262 263
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
264 265
std::shared_future<QVariant>
NemoInterface::Impl::addTiles(const TilePtrArray &tileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
266 267
  using namespace nemo_interface;

268
  // qDebug() << "addTiles called";
269

Valentin Platzgummer's avatar
Valentin Platzgummer committed
270 271 272 273
  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
274
    auto pIdArray = std::make_shared<IDArray>();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
275 276 277 278 279 280 281 282 283
    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
284
        pIdArray->push_back(id);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
285 286 287 288 289
      } else {
        qCDebug(NemoInterfaceLog)
            << "addTiles(): tile with id: " << pTile->id() << "already added.";
      }
    }
290
    if (pTileArray->size() > 0) {
291
      emit this->_parent->tilesChanged();
292
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
293

Valentin Platzgummer's avatar
Valentin Platzgummer committed
294 295 296
    // ready for send?
    if (pTileArray->size() > 0 && (this->ready() || this->_userSync())) {

Valentin Platzgummer's avatar
Valentin Platzgummer committed
297
      this->_setState(STATE::USER_SYNC);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
298
      this->_doAction();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
299

Valentin Platzgummer's avatar
Valentin Platzgummer committed
300 301
      // create add tiles command.
      auto pTask = std::make_unique<Task>(
Valentin Platzgummer's avatar
Valentin Platzgummer committed
302 303
          std::bind(&Impl::_callAddTiles, this, pTileArray));

Valentin Platzgummer's avatar
Valentin Platzgummer committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
      // dispatch command.
      auto ret = _dispatcher.dispatch(std::move(pTask));
      auto addFuture = ret.share();

      // create get progress cmd.
      pTask = std::make_unique<Task>([this, addFuture, pIdArray] {
        addFuture.wait();
        if (addFuture.get().toBool()) {
          return this->_callGetProgress(pIdArray);
        } else {
          return QVariant(false);
        }
      });

      // dispatch command.
      ret = _dispatcher.dispatch(std::move(pTask));
      auto progressFuture = ret.share();
      _futureWatcher.setFuture(progressFuture);
      return progressFuture;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
323 324 325 326 327 328 329 330 331 332 333 334
    }
  }

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

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

335
  // qDebug() << "removeTiles called";
336

Valentin Platzgummer's avatar
Valentin Platzgummer committed
337 338 339 340
  if (idArray.size() > 0) {

    // copy known ids
    auto pIdArray = std::make_shared<IDArray>();
341
    for (const auto &id : idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
342 343 344 345 346 347 348
      const auto it = this->_localTiles.find(id);
      Q_ASSERT(it != _localTiles.end());
      if (Q_LIKELY(it != _localTiles.end())) {
        _localTiles.erase(it);
        pIdArray->push_back(id);
      } else {
        qCDebug(NemoInterfaceLog) << "removeTiles(): unknown id: " << id << ".";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
349
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
350
    }
351
    if (pIdArray->size() > 0) {
352
      emit this->_parent->tilesChanged();
353
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
354 355 356 357

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
358
      this->_setState(STATE::USER_SYNC);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
      this->_doAction();

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

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

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
378 379
std::shared_future<QVariant> NemoInterface::Impl::clearTiles() {
  using namespace nemo_interface;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
380

381
  // qDebug() << "clearTiles called";
382

Valentin Platzgummer's avatar
Valentin Platzgummer committed
383
  // clear local tiles (_localTiles)
384 385
  if (!_localTiles.empty()) {
    this->_localTiles.clear();
386
    emit this->_parent->tilesChanged();
387
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
388

389
  if (this->ready() || this->_userSync()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
390

Valentin Platzgummer's avatar
Valentin Platzgummer committed
391
    this->_setState(STATE::USER_SYNC);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
392
    this->_doAction();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
393

Valentin Platzgummer's avatar
Valentin Platzgummer committed
394 395 396
    // create command.
    auto pTask =
        std::make_unique<Task>(std::bind(&Impl::_callClearTiles, this));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
397 398

    // dispatch command and return.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
399 400 401 402
    auto ret = _dispatcher.dispatch(std::move(pTask));
    auto sfut = ret.share();
    _futureWatcher.setFuture(sfut);
    return sfut;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
403 404 405 406 407 408
  } else {
    std::promise<QVariant> p;
    p.set_value(QVariant(false));
    return p.get_future();
  }
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
409

410
TileArray NemoInterface::Impl::getTiles(const IDArray &idArray) const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
411 412
  TileArray tileArray;

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
  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
434 435 436 437 438 439
    }
  }

  return tileArray;
}

440
TileArray NemoInterface::Impl::getAllTiles() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
441 442
  TileArray tileArray;

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
  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
462 463 464 465 466
  }

  return tileArray;
}

467
LogicalArray NemoInterface::Impl::containsTiles(const IDArray &idArray) const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
468 469 470
  LogicalArray logicalArray;

  for (const auto &id : idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
471 472
    const auto &it = _localTiles.find(id);
    logicalArray.append(it != _localTiles.end());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
473 474 475 476 477
  }

  return logicalArray;
}

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

480
bool NemoInterface::Impl::empty() const { return _localTiles.empty(); }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
481

482
ProgressArray NemoInterface::Impl::getProgress() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
483 484
  ProgressArray progressArray;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
485 486 487 488 489 490 491 492 493 494
  if (this->_isSynchronized()) {
    for (const auto &entry : _remoteTiles) {
      progressArray.append(
          LabeledProgress{entry.second->progress(), entry.second->id()});
    }
  } else {
    for (const auto &entry : _localTiles) {
      progressArray.append(
          LabeledProgress{entry.second->progress(), entry.second->id()});
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
495 496 497 498 499
  }

  return progressArray;
}

500
ProgressArray NemoInterface::Impl::getProgress(const IDArray &idArray) const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
501 502
  ProgressArray progressArray;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
  if (this->_isSynchronized()) {
    for (const auto &id : idArray) {
      const auto it = _remoteTiles.find(id);
      if (it != _remoteTiles.end()) {
        progressArray.append(
            LabeledProgress{it->second->progress(), it->second->id()});
      }
    }
  } else {
    for (const auto &id : idArray) {
      const auto it = _localTiles.find(id);
      if (it != _localTiles.end()) {
        progressArray.append(
            LabeledProgress{it->second->progress(), it->second->id()});
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
518 519 520 521
    }
  }

  return progressArray;
522 523
}

524
NemoInterface::STATUS NemoInterface::Impl::status() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
525
  return _status(this->_state);
526 527
}

528
bool NemoInterface::Impl::running() const { return _running(this->_state); }
529

530
bool NemoInterface::Impl::ready() const { return _ready(this->_state.load()); }
531

532
bool NemoInterface::Impl::_sysSync() const { return _sysSync(this->_state); }
533

Valentin Platzgummer's avatar
Valentin Platzgummer committed
534
void NemoInterface::Impl::_onFutureWatcherFinished() {
535
  if (this->ready() || this->_userSync() || this->_sysSync()) {
536
    static long tries = 0;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
537 538
    auto lastTransactionSuccessfull = _futureWatcher.result().toBool();
    if (!lastTransactionSuccessfull) {
539
      ++tries;
540 541
      qCDebug(NemoInterfaceLog)
          << "last transaction unsuccessfull: " << _toString(_lastCall);
542 543 544 545 546 547 548 549 550 551 552

      if (tries < 5) {
        QTimer::singleShot(SYNC_RETRY_INTERVAL, this->_parent,
                           [this] { this->_trySynchronize(); });
      } else {
        _setWarningString("The last 5 transactions failed! Please check the "
                          "connection and consider reseting the connection.");
        tries = 0;
      }
    } else {
      tries = 0;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
553
    }
554
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
555 556
}

557 558 559 560 561
void NemoInterface::Impl::_onHeartbeatTimeout() {
  this->_setState(STATE::HEARTBEAT_TIMEOUT);
  this->_doAction();
}

562 563 564 565 566 567 568 569 570
void NemoInterface::Impl::_onRosbridgeStateChanged() {
  auto state = this->_pRosbridge->state();
  if (state == Rosbridge::STATE::CONNECTED) {
    if (this->_state == STATE::START_BRIDGE ||
        this->_state == STATE::WEBSOCKET_TIMEOUT) {
      this->_setState(STATE::WEBSOCKET_DETECTED);
      this->_doAction();
    }
  } else if (state == Rosbridge::STATE::TIMEOUT) {
571
    if (this->_state == STATE::TRY_SETUP || this->_state == STATE::READY ||
572 573 574 575 576 577 578 579
        this->_state == STATE::WEBSOCKET_DETECTED ||
        this->_state == STATE::HEARTBEAT_TIMEOUT) {
      this->_setState(STATE::WEBSOCKET_TIMEOUT);
      this->_doAction();
    }
  }
}

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

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

584 585 586
const QString &NemoInterface::Impl::warningString() const {
  return _warningString;
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
587

588 589
void NemoInterface::Impl::_updateProgress(std::shared_ptr<ProgressArray> pArray,
                                          std::promise<bool> promise) {
590
  // qDebug() << "_updateProgress called";
591 592

  bool error = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
593
  for (auto itLP = pArray->begin(); itLP != pArray->end();) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
594

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
597 598 599
    if (Q_LIKELY(it != _remoteTiles.end())) {
      it->second->setProgress(itLP->progress());
      ++itLP;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
600 601
    } else {
      qCDebug(NemoInterfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
602 603
          << "_updateProgress(): tile with id " << itLP->id() << " not found.";
      itLP = pArray->erase(itLP);
604
      error = true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
605 606 607
    }
  }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
608 609 610
  if (pArray->size() > 0) {
    emit _parent->progressChanged(*pArray);
  }
611 612

  promise.set_value(!error);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
613 614
}

615 616
void NemoInterface::Impl::_onHeartbeatReceived(const QNemoHeartbeat &hb,
                                               std::promise<bool> promise) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
617 618
  _lastHeartbeat = hb;
  this->_timeoutTimer.start(NO_HEARTBEAT_TIMEOUT);
619
  if (this->_state == STATE::TRY_SETUP) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
620 621 622 623 624
    this->_setState(STATE::READY);
    this->_doAction();
  } else if (this->_state == STATE::HEARTBEAT_TIMEOUT) {
    this->_setState(STATE::READY);
    this->_doAction();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
625
  }
626
  promise.set_value(true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
}

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

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

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
void NemoInterface::Impl::_doTopicServiceSetup() {}

void NemoInterface::Impl::_checkVersion() {

  auto pTask = std::make_unique<nemo_interface::Task>([this] {
    // wait for service
    std::future<bool> fut;
    long tries = 0;
    long maxTries = 50;
    do {
      fut = this->_pRosbridge->serviceAvailable("/nemo/get_version");

      // wait
      while (true) {
        auto status = fut.wait_for(std::chrono::milliseconds(5));
        if (this->_dispatcher.isInterruptionRequested()) {
          return QVariant(false);
        }
        if (status == std::future_status::ready) {
          break;
        }
      }
      ++tries;
      if (tries > maxTries) {
        qCWarning(NemoInterfaceLog)
            << "_checkVersion: service /nemo/get_version not available.";
        bool value =
            QMetaObject::invokeMethod(this->_parent /* context */, [this]() {
              this->_setWarningString("Version checking failed.");
            });
        Q_ASSERT(value == true);
        return QVariant(false);
      }
    } while (!fut.get());

    // call service
    return this->_callGetVersion();
  });

  this->_dispatcher.dispatch(std::move(pTask));
}

void NemoInterface::Impl::_subscribeProgressTopic() {
  auto pTask = std::make_unique<nemo_interface::Task>([this] {
    // wait for service
    std::future<bool> fut;
    long tries = 0;
    long maxTries = 50;
    do {
      fut = this->_pRosbridge->topicAvailable(progressTopic);

      // wait
      while (true) {
        auto status = fut.wait_for(std::chrono::milliseconds(5));
        if (this->_dispatcher.isInterruptionRequested()) {
          return QVariant(false);
        }
        if (status == std::future_status::ready) {
          break;
        }
      }
      ++tries;
      if (tries > maxTries) {
        qCWarning(NemoInterfaceLog)
            << "_subscribeProgressTopic: topic /nemo/progress not available.";
        bool value =
            QMetaObject::invokeMethod(this->_parent /* context */, [this]() {
              this->_setWarningString("Progress topic not available.");
            });
        Q_ASSERT(value == true);
        return QVariant(false);
      }
    } while (!fut.get());

    // subscribe
    this->_pRosbridge->subscribeTopic(progressTopic, [this](
                                                         const QJsonObject &o) {
      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
735
          }
736

737 738 739 740 741
          if (rangeError) {
            qCWarning(NemoInterfaceLog) << "/nemo/progress progress out "
                                           "of range, value was set to: "
                                        << lp.progress();
          }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
742
        }
743

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
        auto p = std::make_shared<ProgressArray>();
        *p = std::move(progressArray.progress_array());
        std::promise<bool> promise;
        auto future = promise.get_future();
        bool value = QMetaObject::invokeMethod(
            this->_parent, [this, p, promise = std::move(promise)]() mutable {
              this->_updateProgress(p, std::move(promise));
            });
        Q_ASSERT(value == true);
        future.wait();
      } else {
        qCWarning(NemoInterfaceLog) << "/nemo/progress not able to "
                                       "create ProgressArray form json: "
                                    << o;
      }
    });
    this->_progressTopicOK = true;
    bool value = QMetaObject::invokeMethod(this->_parent /* context */,
                                           [this]() { this->_doAction(); });
    Q_ASSERT(value == true);

    return QVariant(true);
  });

  this->_dispatcher.dispatch(std::move(pTask));
}

void NemoInterface::Impl::_subscribeHearbeatTopic() {
  auto pTask = std::make_unique<nemo_interface::Task>([this] {
    // wait for service
    std::future<bool> fut;
    long tries = 0;
    long maxTries = 50;
    do {
      fut = this->_pRosbridge->topicAvailable(heartbeatTopic);

      // wait
      while (true) {
        auto status = fut.wait_for(std::chrono::milliseconds(5));
        if (this->_dispatcher.isInterruptionRequested()) {
          return QVariant(false);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
785
        }
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
        if (status == std::future_status::ready) {
          break;
        }
      }
      ++tries;
      if (tries > maxTries) {
        qCWarning(NemoInterfaceLog)
            << "_subscribeHeartbeatTopic: topic /nemo/hearbeat not available.";
        bool value =
            QMetaObject::invokeMethod(this->_parent /* context */, [this]() {
              this->_setWarningString("Heartbeat topic not available.");
            });
        Q_ASSERT(value == true);
        return QVariant(false);
      }
    } while (!fut.get());

    // subscribe
    using namespace ros_bridge::messages;
    this->_pRosbridge->subscribeTopic(
        heartbeatTopic, [this](const QJsonObject &o) {
          nemo_msgs::heartbeat::Heartbeat heartbeat;
          if (nemo_msgs::heartbeat::fromJson(o, heartbeat)) {
            std::promise<bool> promise;
            auto future = promise.get_future();
            bool value = QMetaObject::invokeMethod(
                this->_parent,
                [this, heartbeat, promise = std::move(promise)]() mutable {
                  this->_onHeartbeatReceived(heartbeat, std::move(promise));
                });
            Q_ASSERT(value == true);
            future.wait();
          } else {
            qCWarning(NemoInterfaceLog) << "/nemo/heartbeat not able to "
                                           "create Heartbeat form json: "
                                        << o;
          }
        });

    this->_heartbeatTopicOK = true;
    bool value = QMetaObject::invokeMethod(this->_parent /* context */,
                                           [this]() { this->_doAction(); });
    Q_ASSERT(value == true);

    return QVariant(true);
  });

  this->_dispatcher.dispatch(std::move(pTask));
834 835
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
836
void NemoInterface::Impl::_trySynchronize() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
837 838 839
  if ((this->_state == STATE::READY || this->_state == STATE::SYS_SYNC ||
       this->_state == STATE::USER_SYNC) &&
      !_isSynchronized()) {
840

841
    if (!_dispatcher.idle()) {
842 843 844
      QTimer::singleShot(SYNC_RETRY_INTERVAL, this->_parent,
                         [this] { this->_trySynchronize(); });
      qCWarning(NemoInterfaceLog) << "synchronization defered";
845 846 847
      return;
    }

848 849
    qCWarning(NemoInterfaceLog) << "trying to synchronize";

Valentin Platzgummer's avatar
Valentin Platzgummer committed
850
    this->_setState(STATE::SYS_SYNC);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
851 852 853 854 855 856 857 858 859
    this->_doAction();

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

    // dispatch command.
    Q_ASSERT(_dispatcher.pendingTasks() == 0);
    auto ret = _dispatcher.dispatch(std::move(pTask));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
860
    auto clearFuture = ret.share();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
861 862 863

    // create tile array.
    auto pTileArray = std::make_shared<QVector<std::shared_ptr<const Tile>>>();
864
    for (const auto &pair : _localTiles) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
865 866 867 868
      pTileArray->push_back(pair.second);
    }

    // create addTiles cmd.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
    pTask =
        std::make_unique<nemo_interface::Task>([this, pTileArray, clearFuture] {
          clearFuture.wait();
          if (clearFuture.get().toBool()) {
            return this->_callAddTiles(pTileArray);
          } else {
            return QVariant(false);
          }
        });

    // dispatch command.
    ret = _dispatcher.dispatch(std::move(pTask));
    auto addFuture = ret.share();

    // create GetAllProgress cmd.
    pTask = std::make_unique<nemo_interface::Task>([this, addFuture] {
      addFuture.wait();
      if (addFuture.get().toBool()) {
        return this->_callGetAllProgress();
      } else {
        return QVariant(false);
      }
    });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
892 893

    // dispatch command.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
894
    ret = _dispatcher.dispatch(std::move(pTask));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
895 896 897 898
    _futureWatcher.setFuture(ret.share());
  }
}

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
void NemoInterface::Impl::_synchronizeIfNeccessary() {
  if (_dispatcher.idle()) {
    // create getAllTiles cmd.
    auto pTask = std::make_unique<nemo_interface::Task>(
        [this] { return this->_callGetAllTiles(); });

    // dispatch command.
    auto ret = _dispatcher.dispatch(std::move(pTask));
    auto fut = ret.share();
    _futureWatcher.setFuture(fut);
    _syncTimer.start(SYNC_INTERVAL);
  } else {
    _syncTimer.start(SYNC_RETRY_INTERVAL);
  }
}

void NemoInterface::Impl::_tryRestart() {
  if (this->running()) {
    if (_dispatcher.idle()) {
      qDebug() << "_tryRestart: restarting";
      this->stop();
      this->start();
      _restartTimer.start(RESTART_INTERVAl);
    } else {
      _restartTimer.start(RESTART_RETRY_INTERVAl);
    }
  }
}

928
bool NemoInterface::Impl::_isSynchronized() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
929 930 931 932 933 934
  return _localTiles.size() > 0 && _remoteTiles.size() > 0 &&
         std::equal(
             _localTiles.begin(), _localTiles.end(), _remoteTiles.begin(),
             [](const auto &a, const auto &b) { return a.first == b.first; });
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
935
void NemoInterface::Impl::_doAction() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
936
  static bool resetDone = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
937 938
  switch (this->_state) {
  case STATE::STOPPED:
939 940
    _setWarningString("");
    _setInfoString("");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
941
    this->_timeoutTimer.stop();
942 943
    this->_restartTimer.stop();
    this->_syncTimer.stop();
944
    this->_clearTilesRemote(std::promise<bool>());
945 946
    if (this->_pRosbridge->state() != Rosbridge::STATE::STOPPED) {
      this->_pRosbridge->stop();
947
    }
948 949 950
    _versionOK = false;
    _progressTopicOK = false;
    _heartbeatTopicOK = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
951
    break;
952

Valentin Platzgummer's avatar
Valentin Platzgummer committed
953
  case STATE::START_BRIDGE:
954
    this->_pRosbridge->start();
955
    this->_restartTimer.start(RESTART_INTERVAl);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
956
    break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
957
  case STATE::WEBSOCKET_DETECTED:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
958
    resetDone = false;
959
    this->_setState(STATE::TRY_SETUP);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
960 961
    this->_doAction();
    break;
962 963 964 965 966 967 968 969 970 971
  case STATE::TRY_SETUP:
    if (!_versionOK) {
      this->_checkVersion();
    } else if (!_progressTopicOK) {
      this->_subscribeProgressTopic();
    } else if (!_heartbeatTopicOK) {
      this->_subscribeHearbeatTopic();
    } else {
      this->_timeoutTimer.start(NO_HEARTBEAT_TIMEOUT);
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
972 973
    break;
  case STATE::READY:
974 975
    this->_trySynchronize();
    this->_syncTimer.start(SYNC_INTERVAL);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
976
    break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
977 978
  case STATE::USER_SYNC:
  case STATE::SYS_SYNC:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
979 980
    break;
  case STATE::HEARTBEAT_TIMEOUT:
981
    this->_clearTilesRemote(std::promise<bool>());
982
    this->_syncTimer.stop();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
983 984 985 986
    break;
  case STATE::WEBSOCKET_TIMEOUT:
    if (!resetDone) {
      resetDone = true;
987 988
      this->_pRosbridge->stop();
      this->_pRosbridge->start();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
989
    }
990
    this->_timeoutTimer.stop();
991
    this->_syncTimer.stop();
992
    this->_clearTilesRemote(std::promise<bool>());
993 994 995
    _versionOK = false;
    _progressTopicOK = false;
    _heartbeatTopicOK = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
996 997
    break;
  };
998 999
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1000 1001
QVariant NemoInterface::Impl::_callAddTiles(
    std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1002

1003
  // qDebug() << "_callAddTiles called";
1004

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1005 1006
  this->_lastCall = CALL_NAME::ADD_TILES;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1007
  // create json object
1008
  QJsonArray jsonTileArray;
1009
  for (auto &&tile : *pTileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1010
    using namespace ros_bridge::messages;
1011 1012
    QJsonObject jsonTile;
    if (!nemo_msgs::tile::toJson(*tile, jsonTile)) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1013 1014 1015 1016 1017
      qCDebug(NemoInterfaceLog)
          << "addTiles(): not able to create json object: tile id: "
          << tile->id() << " progress: " << tile->progress()
          << " points: " << tile->tile();
    }
1018
    jsonTileArray.append(std::move(jsonTile));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1019
  } // for
1020

1021 1022
  QJsonObject req;
  req["in_tile_array"] = std::move(jsonTileArray);
1023

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1024 1025 1026
  // create response handler.
  auto promise_response = std::make_shared<std::promise<bool>>();
  auto future_response = promise_response->get_future();
1027 1028
  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
    // check if transaction was successfull
1029 1030
    if (o.contains("success") && o["success"].isBool()) {
      promise_response->set_value(o["success"].toBool());
1031
    } else {
1032 1033
      qCWarning(NemoInterfaceLog)
          << "/nemo/add_tiles no \"success\" key or wrong type: " << o;
1034 1035 1036
      promise_response->set_value(false);
    }
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1037 1038

  // call service.
1039
  this->_pRosbridge->callService("/nemo/add_tiles", responseHandler, req);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064

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

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

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

  // add remote tiles (_remoteTiles)
1065 1066 1067 1068 1069 1070 1071 1072
  std::promise<bool> promise;
  auto future = promise.get_future();
  bool value = QMetaObject::invokeMethod(
      this->_parent /* context */,
      [this, pTileArray, promise = std::move(promise)]() mutable {
        this->_addTilesRemote(pTileArray, std::move(promise));
      });
  Q_ASSERT(value == true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1073 1074

  // return success
1075
  return QVariant(future.get());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1076 1077 1078 1079
}

QVariant
NemoInterface::Impl::_callRemoveTiles(std::shared_ptr<IDArray> pIdArray) {
1080
  // qDebug() << "_callRemoveTiles called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1081 1082 1083

  this->_lastCall = CALL_NAME::REMOVE_TILES;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1084
  // create json object
1085
  QJsonArray jsonIdArray;
1086
  for (auto &&id : *pIdArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1087
    using namespace ros_bridge::messages;
1088
    jsonIdArray.append(id);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1089
  } // for
1090 1091
  QJsonObject req;
  req["ids"] = std::move(jsonIdArray);
1092

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1093 1094 1095
  // create response handler.
  auto promise_response = std::make_shared<std::promise<bool>>();
  auto future_response = promise_response->get_future();
1096 1097 1098
  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
    // check if transaction was successfull
    QString msg = QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
1099 1100
    if (o.contains("success") && o["success"].isBool()) {
      promise_response->set_value(o["success"].toBool());
1101
    } else {
1102 1103
      qCWarning(NemoInterfaceLog)
          << "/nemo/remove_tiles no \"success\" key or wrong type: " << msg;
1104 1105 1106
      promise_response->set_value(false);
    }
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1107 1108

  // call service.
1109
  this->_pRosbridge->callService("/nemo/remove_tiles", responseHandler, req);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

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

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

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

  // remove remote tiles (_remoteTiles)
1135 1136 1137 1138 1139 1140 1141 1142
  std::promise<bool> promise;
  auto future = promise.get_future();
  bool value = QMetaObject::invokeMethod(
      this->_parent /* context */,
      [this, pIdArray, promise = std::move(promise)]() mutable {
        this->_removeTilesRemote(pIdArray, std::move(promise));
      });
  Q_ASSERT(value == true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1143 1144

  // return success
1145
  return QVariant(future.get());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1146 1147 1148
}

QVariant NemoInterface::Impl::_callClearTiles() {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1149

1150
  // qDebug() << "_callClearTiles called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1151 1152
  this->_lastCall = CALL_NAME::CLEAR_TILES;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1153 1154 1155
  // create response handler.
  auto promise_response = std::make_shared<std::promise<bool>>();
  auto future_response = promise_response->get_future();
1156
  auto responseHandler = [promise_response](const QJsonObject &) mutable {
1157
    // check if transaction was successfull
1158
    promise_response->set_value(true);
1159
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1160 1161

  // call service.
1162 1163
  this->_pRosbridge->callService("/nemo/clear_tiles", responseHandler,
                                 QJsonObject());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187

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

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

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

  // clear remote tiles (_remoteTiles)
1188 1189 1190 1191 1192 1193 1194
  std::promise<bool> promise;
  auto future = promise.get_future();
  bool value = QMetaObject::invokeMethod(
      this->_parent, [this, promise = std::move(promise)]() mutable {
        this->_clearTilesRemote(std::move(promise));
      });
  Q_ASSERT(value == true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1195 1196

  // return success
1197
  return QVariant(future.get());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1198 1199 1200 1201
}

QVariant
NemoInterface::Impl::_callGetProgress(std::shared_ptr<IDArray> pIdArray) {
1202
  // qDebug() << "_callGetProgress called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1203 1204 1205

  this->_lastCall = CALL_NAME::GET_PROGRESS;

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1215 1216 1217 1218
  // 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();
1219 1220
  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
    // check if transaction was successfull
1221 1222 1223 1224 1225 1226 1227
    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);
1228
    } else {
1229 1230 1231
      qCWarning(NemoInterfaceLog)
          << "/nemo/get_progress error while creating ProgressArray "
             "from json.";
1232 1233 1234
      promise_response->set_value(nullptr);
    }
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1235 1236

  // call service.
1237
  this->_pRosbridge->callService("/nemo/get_progress", responseHandler, req);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

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

  if (abort) {
    qCWarning(NemoInterfaceLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
        << "all_remove_tiles(): Websocket not responding to request.";
    return QVariant(false);
  }

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

  // remove remote tiles (_remoteTiles)
1264 1265 1266 1267 1268 1269 1270
  std::promise<bool> promise;
  auto future = promise.get_future();
  bool value = QMetaObject::invokeMethod(
      this->_parent, [this, pArray, promise = std::move(promise)]() mutable {
        this->_updateProgress(pArray, std::move(promise));
      });
  Q_ASSERT(value == true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1271 1272

  // return success
1273
  return QVariant(future.get());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1274 1275 1276
}

QVariant NemoInterface::Impl::_callGetAllProgress() {
1277
  // qDebug() << "_callGetAllProgress called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1278 1279 1280 1281 1282 1283 1284

  this->_lastCall = CALL_NAME::GET_ALL_PROGRESS;

  // 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();
1285
  auto responseHandler = [promise_response](const QJsonObject &o) mutable {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1286
    // check if transaction was successfull
1287 1288 1289 1290 1291 1292 1293
    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
1294 1295
    } else {
      qCWarning(NemoInterfaceLog)
1296 1297 1298
          << "/nemo/get_all_progress error while creating ProgressArray "
             "from json. msg: "
          << o;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1299 1300 1301 1302 1303
      promise_response->set_value(nullptr);
    }
  };

  // call service.
1304 1305
  this->_pRosbridge->callService("/nemo/get_all_progress", responseHandler,
                                 QJsonObject());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321

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

  if (abort) {
    qCWarning(NemoInterfaceLog)
        << "all_remove_tiles(): Websocket not responding to request.";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    return QVariant(false);
  }

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

  // remove remote tiles (_remoteTiles)
1332 1333 1334 1335 1336 1337 1338
  std::promise<bool> promise;
  auto future = promise.get_future();
  bool value = QMetaObject::invokeMethod(
      this->_parent, [this, pArray, promise = std::move(promise)]() mutable {
        this->_updateProgress(pArray, std::move(promise));
      });
  Q_ASSERT(value == true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1339 1340

  // return success
1341 1342 1343
  return QVariant(future.get());
}

1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
QVariant NemoInterface::Impl::_callGetAllTiles() {
  // qDebug() << "_callGetAllProgress called";

  this->_lastCall = CALL_NAME::GET_ALL_TILES;

  // 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 {
            qCWarning(NemoInterfaceLog)
                << "/nemo/get_all_tiles error while creating tile.";
            promise_response->set_value(nullptr);
          }
        } else {
          qCWarning(NemoInterfaceLog)
              << "/nemo/get_all_tiles json array does not contain objects.";
          promise_response->set_value(nullptr);
        }
      }
      // success!
      promise_response->set_value(pArray);
    } else {
      qCWarning(NemoInterfaceLog)
          << "/nemo/get_all_tiles no tile_array key or wrong type.";
      promise_response->set_value(nullptr);
    }
  };

  // call service.
  this->_pRosbridge->callService("/nemo/get_all_tiles", responseHandler,
                                 QJsonObject());

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

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

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

  // remote tiles (_remoteTiles)
  std::promise<bool> promise;
  auto future = promise.get_future();
  bool value = QMetaObject::invokeMethod(
      this->_parent, [this, pArray, promise = std::move(promise)]() mutable {
        this->_setTiles(pArray, std::move(promise));
      });
  Q_ASSERT(value == true);

  // return success
  return QVariant(future.get());
}

QVariant NemoInterface::Impl::_callGetVersion() {
  this->_lastCall = CALL_NAME::GET_VERSION;

  // 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 {
      qCWarning(NemoInterfaceLog)
          << "/nemo/get_version no version key or wrong type.";
      promise_response->set_value("error!");
    }
  };

  // call service.
  this->_pRosbridge->callService("/nemo/get_version", responseHandler,
                                 QJsonObject());

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

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

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

  // remote tiles (_remoteTiles)
  std::promise<bool> promise;
  auto future = promise.get_future();
  bool value = QMetaObject::invokeMethod(
      this->_parent, [this, version, promise = std::move(promise)]() mutable {
        this->_setVersion(version, std::move(promise));
      });
  Q_ASSERT(value == true);

  // return success
  return QVariant(future.get());
}

1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
QString NemoInterface::Impl::_toString(NemoInterface::Impl::CALL_NAME name) {
  switch (name) {
  case CALL_NAME::ADD_TILES:
    return QString("ADD_TILES");
  case CALL_NAME::REMOVE_TILES:
    return QString("REMOVE_TILES");
  case CALL_NAME::CLEAR_TILES:
    return QString("CLEAR_TILES");
  case CALL_NAME::GET_PROGRESS:
    return QString("GET_PROGRESS");
  case CALL_NAME::GET_ALL_PROGRESS:
    return QString("GET_ALL_PROGRESS");
1501 1502 1503 1504
  case CALL_NAME::GET_ALL_TILES:
    return QString("GET_ALL_TILES");
  case CALL_NAME::GET_VERSION:
    return QString("GET_VERSION");
1505 1506
  }
  return QString("unknown CALL_NAME");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1507 1508 1509
}

void NemoInterface::Impl::_addTilesRemote(
1510 1511 1512
    std::shared_ptr<QVector<std::shared_ptr<const Tile>>> pTileArray,
    std::promise<bool> promise) {

1513
  // qDebug() << "_addTilesRemote called";
1514

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1515
  auto pArrayDup = std::make_shared<QVector<std::shared_ptr<Tile>>>();
1516
  for (auto &&pTile : *pTileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1517 1518
    pArrayDup->push_back(std::make_shared<Tile>(*pTile));
  }
1519
  _addTilesRemote2(pArrayDup, std::move(promise));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1520 1521
}

1522 1523 1524 1525
void NemoInterface::Impl::_addTilesRemote2(
    std::shared_ptr<QVector<std::shared_ptr<Tile>>> pTileArray,
    std::promise<bool> promise) {

1526
  // qDebug() << "_addTilesRemote2 called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1527 1528

  bool anyChange = false;
1529
  bool error = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1530

1531
  for (auto &&pTile : *pTileArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
    auto id = pTile->id();
    auto it = _remoteTiles.find(id);
    if (Q_LIKELY(it == _remoteTiles.end())) {
      auto ret = _remoteTiles.insert(std::make_pair(id, pTile));
      Q_ASSERT(ret.second == true);
      Q_UNUSED(ret);
      anyChange = true;
    } else {
      qCWarning(NemoInterfaceLog)
          << "_addTilesRemote: tile with id " << id << " already added.";
1542 1543 1544
      if (pTile->tile() != it->second->tile()) {
        error = true;
      }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1545 1546 1547 1548 1549 1550 1551 1552 1553
    }
  }

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

  promise.set_value(!error);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1556 1557
}

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
void NemoInterface::Impl::_setTiles(
    std::shared_ptr<QVector<std::shared_ptr<Tile>>> pTileArray,
    std::promise<bool> promise) {

  bool error = false;

  _remoteTiles.clear();
  for (auto &&pTile : *pTileArray) {
    auto id = pTile->id();
    auto it = _remoteTiles.find(id);
    if (Q_LIKELY(it == _remoteTiles.end())) {
      auto ret = _remoteTiles.insert(std::make_pair(id, pTile));
      Q_ASSERT(ret.second == true);
      Q_UNUSED(ret);
    } else {
      qCWarning(NemoInterfaceLog)
          << "_addTilesRemote: tile with id " << id << " already added.";
      error = true;
    }
  }

  if (error || !this->_isSynchronized()) {
    qDebug() << "_setTiles: trying to synchronize";
    _trySynchronize();
  }

  promise.set_value(true);
}

void NemoInterface::Impl::_setVersion(QString version,
                                      std::promise<bool> promise) {
  _remoteVersion = version;
  if (_remoteVersion != _localVersion) {
    _setWarningString("Local protocol version (" + _localVersion +
                      ") does not match remote version (" + _remoteVersion +
                      ").");
  } else {
    _versionOK = true;
    _doAction();
  }
  promise.set_value(true);
}

1601 1602
void NemoInterface::Impl::_removeTilesRemote(std::shared_ptr<IDArray> idArray,
                                             std::promise<bool> promise) {
1603
  // qDebug() << "_removeTilesRemote called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1604 1605
  bool anyChange = false;

1606
  for (auto &&id : *idArray) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    auto it = _remoteTiles.find(id);
    if (Q_LIKELY(it != _remoteTiles.end())) {
      _remoteTiles.erase(it);
      anyChange = true;
    } else {
      qCWarning(NemoInterfaceLog)
          << "_removeTilesRemote: tile with unknown id " << id << ".";
    }
  }

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

  promise.set_value(true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1625 1626
}

1627
void NemoInterface::Impl::_clearTilesRemote(std::promise<bool> promise) {
1628
  // qDebug() << "_clearTilesRemote called";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1629 1630 1631 1632 1633 1634 1635
  if (_remoteTiles.size() > 0) {
    _remoteTiles.clear();
    if (this->_isSynchronized()) {
      this->_setState(STATE::READY);
      this->_doAction();
    }
  }
1636
  promise.set_value(true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
}

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

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

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

1656 1657 1658 1659 1660 1661
    return true;
  } else {
    return false;
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1662 1663 1664 1665
bool NemoInterface::Impl::_ready(NemoInterface::Impl::STATE s) {
  return s == STATE::READY;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1666
bool NemoInterface::Impl::_userSync(NemoInterface::Impl::STATE s) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1667
  return s == STATE::USER_SYNC;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1668 1669 1670
}

bool NemoInterface::Impl::_sysSync(NemoInterface::Impl::STATE s) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1671
  return s == STATE::SYS_SYNC;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1672 1673
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1674 1675 1676 1677
bool NemoInterface::Impl::_running(NemoInterface::Impl::STATE s) {
  return s != STATE::STOPPED;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
NemoInterface::STATUS
NemoInterface::Impl::_status(NemoInterface::Impl::STATE state) {
  NemoInterface::STATUS status;
  switch (state) {
  case STATE::STOPPED:
    status = NemoInterface::STATUS::NOT_CONNECTED;
    break;
  case STATE::START_BRIDGE:
    status = NemoInterface::STATUS::NOT_CONNECTED;
    break;
  case STATE::WEBSOCKET_DETECTED:
    status = NemoInterface::STATUS::WEBSOCKET_DETECTED;
    break;
1691
  case STATE::TRY_SETUP:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1692 1693 1694 1695 1696
    status = NemoInterface::STATUS::WEBSOCKET_DETECTED;
    break;
  case STATE::READY:
    status = NemoInterface::STATUS::READY;
    break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1697 1698
  case STATE::USER_SYNC:
  case STATE::SYS_SYNC:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
    status = NemoInterface::STATUS::SYNC;
    break;
  case STATE::WEBSOCKET_TIMEOUT:
  case STATE::HEARTBEAT_TIMEOUT:
    status = NemoInterface::STATUS::TIMEOUT;
    break;
  }

  return status;
}

QString NemoInterface::Impl::_toString(NemoInterface::Impl::STATE s) {
  switch (s) {
  case STATE::STOPPED:
    return QString("STOPPED");
  case STATE::START_BRIDGE:
    return QString("START_BRIDGE");
  case STATE::WEBSOCKET_DETECTED:
    return QString("WEBSOCKET_DETECTED");
1718
  case STATE::TRY_SETUP:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1719 1720 1721
    return QString("TRY_TOPIC_SERVICE_SETUP");
  case STATE::READY:
    return QString("READY");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1722
  case STATE::USER_SYNC:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1723
    return QString("SYNC_USER");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1724
  case STATE::SYS_SYNC:
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
    return QString("SYNC_SYS");
  case STATE::WEBSOCKET_TIMEOUT:
    return QString("WEBSOCKET_TIMEOUT");
  case STATE::HEARTBEAT_TIMEOUT:
    return QString("HEARTBEAT_TIMEOUT");
  }
  return "unknown state!";
}

QString NemoInterface::Impl::_toString(NemoInterface::STATUS s) {
  switch (s) {
  case NemoInterface::STATUS::NOT_CONNECTED:
    return QString("NOT_CONNECTED");
1738 1739
  case NemoInterface::STATUS::ERROR:
    return QString("ERROR");
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
  case NemoInterface::STATUS::READY:
    return QString("READY");
  case NemoInterface::STATUS::TIMEOUT:
    return QString("TIMEOUT");
  case NemoInterface::STATUS::WEBSOCKET_DETECTED:
    return QString("WEBSOCKET_DETECTED");
  case NemoInterface::STATUS::SYNC:
    return QString("SYNC");
  }
  return "unknown state!";
}

1752 1753
// ===============================================================
// NemoInterface
1754 1755 1756 1757 1758 1759 1760 1761 1762
NemoInterface::NemoInterface()
    : QObject(), pImpl(std::make_unique<NemoInterface::Impl>(this)) {}

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

NemoInterface *NemoInterface::instance() {
  return GenericSingelton<NemoInterface>::instance(
      NemoInterface::createInstance);
}
1763 1764 1765 1766 1767 1768 1769

NemoInterface::~NemoInterface() {}

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

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1770 1771 1772 1773 1774 1775 1776
std::shared_future<QVariant>
NemoInterface::addTiles(const TileArray &tileArray) {
  TilePtrArray ptrArray;
  for (const auto &tile : tileArray) {
    ptrArray.push_back(const_cast<MeasurementTile *>(&tile));
  }
  return this->pImpl->addTiles(ptrArray);
1777 1778
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1779 1780 1781
std::shared_future<QVariant>
NemoInterface::addTiles(const TilePtrArray &tileArray) {
  return this->pImpl->addTiles(tileArray);
1782 1783
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1784 1785 1786 1787 1788 1789 1790 1791
std::shared_future<QVariant>
NemoInterface::removeTiles(const IDArray &idArray) {
  return this->pImpl->removeTiles(idArray);
}

std::shared_future<QVariant> NemoInterface::clearTiles() {
  return this->pImpl->clearTiles();
}
1792

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

1797 1798 1799
TileArray NemoInterface::getAllTiles() const {
  return this->pImpl->getAllTiles();
}
1800

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

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

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

1809
ProgressArray NemoInterface::getProgress() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1810 1811 1812
  return this->pImpl->getProgress();
}

1813
ProgressArray NemoInterface::getProgress(const IDArray &idArray) const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1814 1815 1816
  return this->pImpl->getProgress(idArray);
}

1817
NemoInterface::STATUS NemoInterface::status() const {
1818 1819 1820 1821 1822 1823 1824
  return this->pImpl->status();
}

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1825 1826 1827 1828 1829
QString NemoInterface::infoString() const { return this->pImpl->infoString(); }

QString NemoInterface::warningString() const {
  return this->pImpl->warningString();
}
1830 1831 1832 1833 1834

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

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