rosbridgeimpl.cpp 15.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
#include "rosbridgeimpl.h"

#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>

static const char *advertiseOpKey = "advertise";
static const char *subscribeOpKey = "subscribe";
static const char *unsubscribeOpKey = "unsubscribe";
static const char *unadvertiseOpKey = "unadvertise";
static const char *publishOpKey = "publish";
static const char *serviceResponseOpKey = "service_response";
static const char *unadvertiseServiceOpKey = "unadvertise_service";
static const char *advertiseServiceOpKey = "advertise_service";
static const char *callServiceOpKey = "call_service";
static const char *topicKey = "topic";
static const char *serviceKey = "service";
static const char *msgKey = "msg";
static const char *opKey = "op";
static const char *idKey = "id";
static const char *argsKey = "args";
static const char *resultKey = "result";
static const char *valuesKey = "values";
static const char *typeKey = "type";

struct ServiceCall {
  ServiceCall() {}
  ServiceCall(const Rosbridge::CallBack &c, QString i, QString s)
      : callback(c), id(i), service(s) {}

  Rosbridge::CallBack callback;
  QString id;
  QString service;
};

RosbridgeImpl::RosbridgeImpl(const QUrl &url, QObject *parent)
    : QObject(parent),
      _webSocket(QString(), QWebSocketProtocol::VersionLatest, this), _url(url),
      _state(STATE::STOPPED) {
  connect(this, &RosbridgeImpl::stateChanged, this, &RosbridgeImpl::_doAction);
  connect(&_webSocket, &QWebSocket::connected, this,
          &RosbridgeImpl::_onConnected);
  connect(&_webSocket, &QWebSocket::disconnected, this,
          &RosbridgeImpl::_onDisconnected);
  connect(&_webSocket, &QWebSocket::textMessageReceived, this,
          &RosbridgeImpl::_onTextMessageReceived);
  qRegisterMetaType<QAbstractSocket::SocketState>();
  qRegisterMetaType<QAbstractSocket::SocketError>();
}

RosbridgeImpl::~RosbridgeImpl() {
  if (_state == STATE::CONNECTED) {
    stop();
  }
}

RosbridgeImpl::STATE RosbridgeImpl::state() { return _state.load(); }

void RosbridgeImpl::start() {
  if (_state == STATE::STOPPED) {
    _setState(STATE::STARTING);
  }
}

void RosbridgeImpl::stop() {
  if (_state != STATE::STOPPED) {
    _setState(STATE::STOPPING);
  }
}

void RosbridgeImpl::advertiseTopic(const QString &topic, const QString &type) {
  if (_state == STATE::CONNECTED) {
    auto it = _advertisedTopics.find(topic);
    if (Q_LIKELY(it == _advertisedTopics.end())) {
      _advertisedTopics.insert(topic);

      QJsonObject o;
      o[opKey] = advertiseOpKey;
      o[topicKey] = topic;
      o[typeKey] = type;

      QString payload =
          QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
      _webSocket.sendTextMessage(payload);
    } else {
      qDebug() << "Topic " << topic << " already advertised.";
    }
  } else {
    qDebug() << "advertiseTopic: Rosbridge not connected!";
  }
}

void RosbridgeImpl::publish(const QString &topic, const QJsonObject &msg) {
  if (_state == STATE::CONNECTED) {
    auto it = _advertisedTopics.find(topic);
    if (Q_LIKELY(it != _advertisedTopics.end())) {
      QJsonObject o;
      o[opKey] = publishOpKey;
      o[topicKey] = topic;
      o[msgKey] = msg;

      QString payload =
          QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
      _webSocket.sendTextMessage(payload);
    } else {
      qDebug() << "Topic " << topic << " not advertised.";
    }
  } else {
    qDebug() << "publish: Rosbridge not connected!";
  }
}

void RosbridgeImpl::unadvertiseTopic(const QString &topic) {
  if (_state == STATE::CONNECTED || _state == STATE::STOPPING) {
    auto it = _advertisedTopics.find(topic);
    if (Q_LIKELY(it != _advertisedTopics.end())) {

      QJsonObject o;
      o[opKey] = unadvertiseOpKey;
      o[topicKey] = topic;

      QString payload =
          QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
      _webSocket.sendTextMessage(payload);
125 126

      _advertisedTopics.erase(it);
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    } else {
      qDebug() << "Topic " << topic << " not advertised.";
    }
  } else {
    qDebug() << "unadvertiseTopic: Rosbridge not connected!";
  }
}

void RosbridgeImpl::unadvertiseAllTopics() {
  if (_state == STATE::CONNECTED || _state == STATE::STOPPING) {
    while (!_advertisedTopics.empty()) {
      const auto topic = _advertisedTopics.begin();
      unadvertiseTopic(*topic);
    }
  } else {
    qDebug() << "unadvertiseAllTopic: Rosbridge not connected!";
  }
}

void RosbridgeImpl::subscribeTopic(const QString &topic,
                                   const Rosbridge::CallBack &callback) {
  if (_state == STATE::CONNECTED) {
    auto it = _subscribedTopics.find(topic);
    if (Q_LIKELY(it == _subscribedTopics.end())) {
      auto ret = _subscribedTopics.insert(std::make_pair(topic, callback));
      Q_ASSERT(ret.second == true);

      QJsonObject o;
      o[opKey] = subscribeOpKey;
      o[topicKey] = topic;

      QString payload =
          QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
      _webSocket.sendTextMessage(payload);

    } else {
      qDebug() << "subscribeTopic: topic " << topic << " already subscribed!";
    }
  } else {
    qDebug() << "subscribeTopic: Rosbridge not connected!";
  }
}

void RosbridgeImpl::unsubscribeTopic(const QString &topic) {
  if (_state == STATE::CONNECTED || _state == STATE::STOPPING) {
    auto it = _subscribedTopics.find(topic);
    if (Q_LIKELY(it != _subscribedTopics.end())) {

      QJsonObject o;
      o[opKey] = unsubscribeOpKey;
      o[topicKey] = topic;

      QString payload =
          QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
      _webSocket.sendTextMessage(payload);
182 183

      _subscribedTopics.erase(it);
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    } else {
      qDebug() << "unsubscribeTopic: topic " << topic << " already subscribed!";
    }
  } else {
    qDebug() << "unsubscribeTopic: Rosbridge not connected!";
  }
}

void RosbridgeImpl::unsubscribeAllTopics() {
  if (_state == STATE::CONNECTED || _state == STATE::STOPPING) {
    while (!_subscribedTopics.empty()) {
      auto it = _subscribedTopics.begin();
      unsubscribeTopic(it->first);
    }
  } else {
    qDebug() << "unsubscribeAll: Rosbridge not connected!";
  }
}

void RosbridgeImpl::advertiseService(
    const QString &service, const QString &type,
    const Rosbridge::CallBackWReturn &callback) {
  if (_state == STATE::CONNECTED) {
    auto it = _advertisedServices.find(service);
    if (it == _advertisedServices.end()) {
      auto ret = _advertisedServices.insert(std::make_pair(service, callback));
      Q_ASSERT(ret.second == true);

      QJsonObject o;
      o[opKey] = advertiseServiceOpKey;
      o[serviceKey] = service;
      o[typeKey] = type;

      QString payload =
          QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
      _webSocket.sendTextMessage(payload);
    } else {
      qDebug() << "advertiseService: Service " << service
               << " already advertised. Use unadvertiseService first to "
                  "unadvertise the service.";
    }
  } else {
    qDebug() << "advertiseService: Rosbridge not connected!";
  }
}

void RosbridgeImpl::_serviceResponse(const QString &service, const QString &id,
                                     bool result, const QJsonObject &values) {

  if (_state == STATE::CONNECTED) {
    auto it = _advertisedServices.find(service);
    if (it != _advertisedServices.end()) {

      QJsonObject o;
      o[opKey] = serviceResponseOpKey;
      o[serviceKey] = service;
      o[resultKey] = result;
      o[idKey] = id;
      o[valuesKey] = values;

      QString payload =
          QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
      _webSocket.sendTextMessage(payload);
    } else {
      qDebug() << "serviceResponse: Service " << service << " not advertised.";
    }
  } else {
    qDebug() << "serviceResponse: Rosbridge not connected!";
  }
}

void RosbridgeImpl::_clearAllPendingServiceCalls() {
  while (!_pendingServiceCalls.empty()) {
    auto it = _pendingServiceCalls.begin();
    it = _pendingServiceCalls.erase(it);
  }
}

void RosbridgeImpl::callService(const QString &service,
                                const Rosbridge::CallBack &callback,
                                const QJsonObject &req) {
  if (_state == STATE::CONNECTED) {
    auto it = _pendingServiceCalls.find(service);
    if (it == _pendingServiceCalls.end()) {
      auto ret = _pendingServiceCalls.insert(
          std::make_pair(service, std::deque<std::unique_ptr<ServiceCall>>()));
      Q_ASSERT(ret.second == true);
      it = ret.first;
    }

    QString id(QString::number(_getMessageId()));
    auto p =
        std::unique_ptr<ServiceCall>(new ServiceCall(callback, id, service));
    it->second.push_back(std::move(p));

    QJsonObject o;
    o[opKey] = callServiceOpKey;
    o[serviceKey] = service;
    o[idKey] = id;
    o[argsKey] = req;

    QString payload =
        QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
    _webSocket.sendTextMessage(payload);
  } else {
    qDebug() << "callService: Rosbridge not connected!";
  }
}

void RosbridgeImpl::unadvertiseService(const QString &service) {

  if (_state == STATE::CONNECTED || _state == STATE::STOPPING) {
    auto it = _advertisedServices.find(service);
    if (it != _advertisedServices.end()) {

      QJsonObject o;
      o[opKey] = unadvertiseServiceOpKey;
      o[serviceKey] = service;

      QString payload =
          QJsonDocument(o).toJson(QJsonDocument::JsonFormat::Compact);
      _webSocket.sendTextMessage(payload);
306 307

      it = _advertisedServices.erase(it);
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
    } else {
      qDebug() << "unadvertiseService: Service " << service
               << " not advertised.";
    }
  } else {
    qDebug() << "unadvertiseService: Rosbridge not connected!";
  }
}

void RosbridgeImpl::unadvertiseAllServices() {
  if (_state == STATE::CONNECTED || _state == STATE::STOPPING) {
    while (!_advertisedServices.empty()) {
      auto it = _advertisedServices.begin();
      unadvertiseService(it->first);
    }
  } else {
    qDebug() << "unadvertiseAllService: Rosbridge not connected!";
  }
}

void RosbridgeImpl::_onConnected() {
  if (this->_state == STATE::STARTING) {
    _setState(STATE::CONNECTED);
  }
}

void RosbridgeImpl::_onDisconnected() {
  if (this->_state == STATE::CONNECTED) {
    _setState(STATE::TIMEOUT);
  }
}

void RosbridgeImpl::_setState(RosbridgeImpl::STATE newState) {
  if (_state != newState) {
    _state = newState;
    emit stateChanged();
  }
}

int RosbridgeImpl::_getMessageId() {
  static int c = 0;
  return c++;
}

void RosbridgeImpl::_doAction() {
  switch (_state.load()) {
  case STATE::STOPPED:
    break;
  case STATE::STOPPING:
    unadvertiseAllTopics();
    unadvertiseAllServices();
    unsubscribeAllTopics();
    _clearAllPendingServiceCalls();
    _webSocket.close();
    _setState(STATE::STOPPED);
    break;
  case STATE::STARTING:
    _webSocket.open(_url);
    break;
  case STATE::TIMEOUT:
    break;
  case STATE::CONNECTED:
    break;
  }
}

void RosbridgeImpl::_onTextMessageReceived(const QString &message) {
375
  qDebug() << "_onTextMessageReceived: " << message;
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
  QJsonParseError e;
  auto d = QJsonDocument::fromJson(message.toUtf8(), &e);
  if (!d.isNull()) {
    if (d.isObject()) {
      QJsonObject o = d.object();
      if (o.contains(opKey) && o[opKey].isString()) {
        auto opCode = o[opKey].toString();
        if (opCode == publishOpKey) {
          _processTopic(o);
          return;
        } else if (opCode == serviceResponseOpKey) {
          _processServiceResponse(o);
          return;
        } else if (opCode == callServiceOpKey) {
          _processServiceCall(o);
          return;
        } else {
          qDebug() << "_onTextMessageReceived: unknown op code: "
                   << o[opKey].toString();
        }
      } else {
        qDebug()
            << "_onTextMessageReceived: json document doesn't contain op code ("
            << opKey << ") or op code has wrong type.";
      }
    } else {
      qDebug() << "_onTextMessageReceived: json document is not an object.";
    }
  } else {
    qDebug() << "_onTextMessageReceived: parse error: " << e.errorString();
  }
  qDebug() << "_onTextMessageReceived: message: " << message;
}

void RosbridgeImpl::_processTopic(const QJsonObject &o) {
  if (o.contains(topicKey) && o[topicKey].isString()) {
    if (o.contains(msgKey) && o[msgKey].isObject()) {
      auto topic = o[topicKey].toString();
      auto it = _subscribedTopics.find(topic);
      if (Q_LIKELY(it != _subscribedTopics.end())) {
        it->second(o[msgKey].toObject(QJsonObject()));
        return;
      } else {
        qDebug() << "_processTopic: unknown topic " << topic;
      }
    } else {
      qDebug() << "_processTopic: message key (" << msgKey << ") missing";
    }
  } else {
    qDebug() << "_processTopic: json document doesn't contain topic key ("
             << topicKey << ") or topic key has wrong type.";
  }
  qDebug() << "_processTopic: msg: " << o;
}

void RosbridgeImpl::_processServiceResponse(const QJsonObject &o) {
  if (o.contains(serviceKey) && o[serviceKey].isString()) {
    if (o.contains(valuesKey) && o[valuesKey].isObject()) {
      auto service = o[serviceKey].toString();
      auto it = _pendingServiceCalls.find(service);
      if (Q_LIKELY(it != _pendingServiceCalls.end())) {
        auto p = it->second.begin();

        // check if ids match
        if (o.contains(idKey) && o[idKey].isString()) {
          auto id = o[idKey].toString();
          if (id != (*p)->id) {
            qDebug() << "_processServiceResponse: ids, don't match, searching "
                        "correct callback...";
            auto match =
                std::find_if(it->second.begin(), it->second.end(),
                             [&id](const std::unique_ptr<ServiceCall> &c) {
                               return c->id == id;
                             });
            if (match != it->second.end()) {
              p = match;
            } else {
              qDebug()
                  << "_processServiceResponse: unknown id, can't determine "
                     "callback";
              return;
            }
          }
        }

        ((*p)->callback)(o[valuesKey].toObject()); // callback
        p = it->second.erase(p);
        if (it->second.size() == 0) {
          _pendingServiceCalls.erase(it);
        }
        return;
      } else {
        qDebug() << "_processServiceResponse: unknown service " << service;
      }
    } else {
      qDebug() << "_processServiceResponse: json document doesn't contain "
                  "values key ("
               << valuesKey << ") or values key has wrong type.";
    }
  } else {
    qDebug() << "_processServiceResponse: json document doesn't contain "
                "service key ("
             << serviceKey << ") or service key has wrong type.";
  }
  qDebug() << "_processServiceResponse: msg: " << o;
}

void RosbridgeImpl::_processServiceCall(const QJsonObject &o) {
  if (o.contains(serviceKey) && o[serviceKey].isString()) {
    auto service = o[serviceKey].toString();
    if (o.contains(idKey) && o[idKey].isString()) {
      if (o.contains(argsKey) && o[argsKey].isObject()) {
        auto id = o[idKey].toString();
        auto it = _advertisedServices.find(service);
        if (Q_LIKELY(it != _advertisedServices.end())) {
          auto resp = it->second(o[argsKey].toObject());
          auto result = !resp.empty();
          _serviceResponse(service, id, result, resp);
          return;
        } else {
          qDebug() << "_processServiceCall: unknown service " << service;
        }
      } else {
        qDebug() << "_processServiceCall: args key (" << idKey
                 << ") missing, response not possible.";
      }
    } else {
      qDebug() << "_processServiceCall: id key (" << idKey
               << ") missing, response not possible.";
    }
  } else {
    qDebug()
        << "_processServiceCall: json document doesn't contain service key ("
        << serviceKey << ") or service key has wrong type.";
  }
  qDebug() << "_processServiceCall: msg: " << o;
}