RosBridgeClient.cpp 34.2 KB
Newer Older
1 2 3 4 5
#include "RosBridgeClient.h"

#include <chrono>
#include <functional>
#include <future>
6
#include <regex>
7
#include <thread>
8

9 10 11 12 13 14 15
struct Task {
  std::function<bool(void)>
      ready; // Condition under which command should be executed.
  std::function<void(void)> execute;  // Command to execute.
  std::function<bool(void)> expired;  // Returns true if the command is expired.
  std::function<void(void)> clear_up; // operation to perform if task expired.
  std::string name;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
16 17
};

18 19 20
void RosbridgeWsClient::start(const std::__cxx11::string &client_name,
                              std::shared_ptr<WsClient> client,
                              const std::__cxx11::string &message) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
21
#ifndef ROS_BRIDGE_DEBUG
22
  (void)client_name;
23
#endif
24
  if (!client->on_open) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
25
#ifdef ROS_BRIDGE_DEBUG
26 27
    client->on_open = [client_name, message](
                          std::shared_ptr<WsClient::Connection> connection) {
28
#else
29 30
    client->on_open =
        [message](std::shared_ptr<WsClient::Connection> connection) {
31 32
#endif

Valentin Platzgummer's avatar
Valentin Platzgummer committed
33
#ifdef ROS_BRIDGE_DEBUG
34 35
      std::cout << client_name << ": Opened connection" << std::endl;
      std::cout << client_name << ": Sending message: " << message << std::endl;
36
#endif
37 38 39
      connection->send(message);
    };
  }
40

Valentin Platzgummer's avatar
Valentin Platzgummer committed
41
#ifdef ROS_BRIDGE_DEBUG
42 43 44 45 46 47 48
  if (!client->on_message) {
    client->on_message =
        [client_name](std::shared_ptr<WsClient::Connection> /*connection*/,
                      std::shared_ptr<WsClient::InMessage> in_message) {
          std::cout << client_name
                    << ": Message received: " << in_message->string()
                    << std::endl;
49
        };
50 51 52 53 54 55 56 57
  }

  if (!client->on_close) {
    client->on_close =
        [client_name](std::shared_ptr<WsClient::Connection> /*connection*/,
                      int status, const std::string & /*reason*/) {
          std::cout << client_name << ": Closed connection with status code "
                    << status << std::endl;
58
        };
59 60 61 62 63 64 65 66 67 68 69
  }

  if (!client->on_error) {
    // See
    // http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html,
    // Error Codes for error code meanings
    client->on_error =
        [client_name](std::shared_ptr<WsClient::Connection> /*connection*/,
                      const SimpleWeb::error_code &ec) {
          std::cout << client_name << ": Error: " << ec
                    << ", error message: " << ec.message() << std::endl;
70
        };
71
  }
72 73

#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
74
#ifdef ROS_BRIDGE_DEBUG
75
  std::thread client_thread([client_name, client]() {
76
#else
Valentin Platzgummer's avatar
Valentin Platzgummer committed
77 78
  std::thread client_thread([client_name, client]() {
  // std::thread client_thread([client]() {
79
#endif
80
    client->start();
81

Valentin Platzgummer's avatar
Valentin Platzgummer committed
82
#ifdef ROS_BRIDGE_DEBUG
83
    std::cout << client_name << ": Terminated" << std::endl;
84
#endif
85 86 87 88
    client->on_open = NULL;
    client->on_message = NULL;
    client->on_close = NULL;
    client->on_error = NULL;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
89
#ifdef ROS_BRIDGE_DEBUG
90
    std::cout << client_name << " thread end" << std::endl;
91
#endif
92
  });
93

94
  client_thread.detach();
95 96
}

97 98 99 100 101 102 103
RosbridgeWsClient::RosbridgeWsClient(const std::string &server_port_path,
                                     bool run)
    : server_port_path(server_port_path),
      isConnected(std::make_shared<std::atomic_bool>(false)),
      stopped(std::make_shared<std::atomic_bool>(true)) {
  if (run)
    this->run();
104 105
}

106 107 108
RosbridgeWsClient::RosbridgeWsClient(
    const std::__cxx11::string &server_port_path)
    : RosbridgeWsClient::RosbridgeWsClient(server_port_path, true) {}
109

110
RosbridgeWsClient::~RosbridgeWsClient() { reset(); }
111

112
bool RosbridgeWsClient::connected() { return isConnected->load(); }
113

114 115 116 117 118 119 120 121 122 123 124 125 126 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
void RosbridgeWsClient::run() {
  if (!stopped->load())
    return;
  stopped->store(false);
  // Start periodic thread to monitor connection status, advertised topics etc.
  periodic_thread = std::make_shared<std::thread>([this] {
    std::list<Task> task_list;
    constexpr auto poll_interval = std::chrono::seconds(1);
    auto poll_time_point = std::chrono::high_resolution_clock::now();
    while (!this->stopped->load()) {
      // ====================================================================================
      // Add tasks.
      // ====================================================================================
      if (std::chrono::high_resolution_clock::now() > poll_time_point) {
        poll_time_point =
            std::chrono::high_resolution_clock::now() + poll_interval;
        std::string reset_status_task_name = "reset_status_task";
        // Add status task if necessary.
        auto const it = std::find_if(task_list.begin(), task_list.end(),
                                     [&reset_status_task_name](const Task &t) {
                                       return t.name == reset_status_task_name;
                                     });
        if (it == task_list.end()) {
          // Check connection status.
          auto status_set = std::make_shared<std::atomic_bool>(false);
          auto status_client =
              std::make_shared<WsClient>(this->server_port_path);
          status_client->on_open =
              [status_set, this](std::shared_ptr<WsClient::Connection>) {
                this->isConnected->store(true);
                status_set->store(true);
              };

          std::thread status_thread(
              [status_client] { status_client->start(); });
          status_thread.detach();

          // Create task to reset isConnected after one second.
          Task reset_task;
          reset_task.name = reset_status_task_name;
          // condition
          auto now = std::chrono::high_resolution_clock::now();
          const auto t_trigger = now + std::chrono::seconds(1);
          reset_task.ready = [t_trigger] {
            return std::chrono::high_resolution_clock::now() > t_trigger;
          };
          // command
          reset_task.execute = [status_client, status_set, this] {
            status_client->stop();
            this->isConnected->store(false);
            status_set->store(true);
          };
          // expired
          reset_task.expired = [status_set] { return status_set->load(); };
          // clear up
          reset_task.clear_up = [status_client, this] {
            status_client->stop();
          };
          task_list.push_back(reset_task);
173 174
        }

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 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
        if (this->isConnected->load()) {
          // Add available topics task if neccessary.
          std::string reset_topics_task_name = "reset_topics_task";
          auto const topics_it =
              std::find_if(task_list.begin(), task_list.end(),
                           [&reset_topics_task_name](const Task &t) {
                             return t.name == reset_topics_task_name;
                           });
          if (topics_it == task_list.end()) {
            // Call /rosapi/topics service.
            auto topics_set = std::make_shared<std::atomic_bool>(false);
            this->callService(
                "/rosapi/topics",
                [topics_set,
                 this](std::shared_ptr<WsClient::Connection> connection,
                       std::shared_ptr<WsClient::InMessage> in_message) {
                  std::unique_lock<std::mutex> lk(this->mutex);
                  this->available_topics = in_message->string();
                  lk.unlock();
                  topics_set->store(true);
                  connection->send_close(1000);
                });

            // Create task to reset topics after one second.
            Task reset_task;
            reset_task.name = reset_topics_task_name;
            // condition
            auto now = std::chrono::high_resolution_clock::now();
            auto t_trigger = now + std::chrono::seconds(1);
            reset_task.ready = [t_trigger] {
              return std::chrono::high_resolution_clock::now() > t_trigger;
            };
            // command
            reset_task.execute = [topics_set, this] {
              std::unique_lock<std::mutex> lk(this->mutex);
              this->available_topics.clear();
              lk.unlock();
              topics_set->store(true);
            };
            // expired
            reset_task.expired = [topics_set] { return topics_set->load(); };
            // clear up
            reset_task.clear_up = [this] { return; };
            task_list.push_back(reset_task);
          }

          // Add available services task if neccessary.
          std::string reset_services_name = "reset_services_task";
          auto const services_it =
              std::find_if(task_list.begin(), task_list.end(),
                           [&reset_services_name](const Task &t) {
                             return t.name == reset_services_name;
                           });
          if (services_it == task_list.end()) {
            // Call /rosapi/services service.
            auto services_set = std::make_shared<std::atomic_bool>(false);
            this->callService(
                "/rosapi/services",
                [this, services_set](
                    std::shared_ptr<WsClient::Connection> connection,
                    std::shared_ptr<WsClient::InMessage> in_message) {
                  std::unique_lock<std::mutex> lk(this->mutex);
                  this->available_services = in_message->string();
                  lk.unlock();
                  services_set->store(true);
                  connection->send_close(1000);
                });

            // Create task to reset services after one second.
            Task reset_task;
            reset_task.name = reset_services_name;
            // condition
            auto now = std::chrono::high_resolution_clock::now();
            auto t_trigger = now + std::chrono::seconds(1);
            reset_task.ready = [t_trigger] {
              return std::chrono::high_resolution_clock::now() > t_trigger;
            };
            // command
            reset_task.execute = [services_set, this] {
              std::unique_lock<std::mutex> lk(this->mutex);
              this->available_services.clear();
              lk.unlock();
              services_set->store(true);
            };
            // expired
            reset_task.expired = [services_set] {
              return services_set->load();
            };
            // clear up
            reset_task.clear_up = [this] { return; };
            task_list.push_back(reset_task);
          }
        } else {
          std::lock_guard<std::mutex> lk(mutex);
          available_topics.clear();
          available_services.clear();
        }
      }

      // ====================================================================================
      // Process tasks.
      // ====================================================================================
      for (auto task_it = task_list.begin(); task_it != task_list.end();) {
        if (!task_it->expired()) {
          if (task_it->ready()) {
            task_it->execute();
            task_it = task_list.erase(task_it);
          } else {
            ++task_it;
          }
        } else {
          task_it->clear_up();
          task_it = task_list.erase(task_it);
288
        }
289 290 291 292 293 294 295 296 297 298 299
      }

      std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    // Clear up remaining tasks.
    for (auto task_it = task_list.begin(); task_it != task_list.end();
         ++task_it) {
      task_it->clear_up();
    }
    task_list.clear();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
300
#ifdef ROS_BRIDGE_DEBUG
301
    std::cout << "periodic thread end" << std::endl;
302
#endif
303
  });
304 305
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
306 307
bool RosbridgeWsClient::running() { return !this->stopped->load(); }

308 309 310 311 312
void RosbridgeWsClient::stop() {
  if (stopped->load())
    return;
  stopped->store(true);
  periodic_thread->join();
313 314
}

315 316 317 318 319 320 321 322 323 324 325 326 327 328
void RosbridgeWsClient::reset() {
  stop();
  unsubscribeAll();
  unadvertiseAll();
  unadvertiseAllServices();

  std::unique_lock<std::mutex> lk(mutex);
  for (auto it = client_map.begin(); it != client_map.end();) {
    std::string client_name = it->first;
    lk.unlock();
    removeClient(client_name);
    lk.lock();
    it = client_map.begin();
  }
329 330
}

331 332 333 334 335 336 337
void RosbridgeWsClient::addClient(const std::string &client_name) {
  std::lock_guard<std::mutex> lk(mutex);
  std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator it =
      client_map.find(client_name);
  if (it == client_map.end()) {
    client_map[client_name] = std::make_shared<WsClient>(server_port_path);
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
338
#ifdef ROS_BRIDGE_DEBUG
339 340 341
  else {
    std::cerr << client_name << " has already been created" << std::endl;
  }
342 343 344
#endif
}

345 346 347 348 349 350 351 352 353
std::shared_ptr<WsClient>
RosbridgeWsClient::getClient(const std::string &client_name) {
  std::lock_guard<std::mutex> lk(mutex);
  std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator it =
      client_map.find(client_name);
  if (it != client_map.end()) {
    return it->second;
  }
  return NULL;
354 355
}

356 357 358 359 360 361 362 363 364 365 366
void RosbridgeWsClient::stopClient(const std::string &client_name) {
  std::lock_guard<std::mutex> lk(mutex);
  std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator it =
      client_map.find(client_name);
  if (it != client_map.end()) {
    // Stop the client asynchronously in 100 ms.
    // This is to ensure, that all threads involving the client have been
    // launched.
    std::shared_ptr<WsClient> client = it->second;
#ifdef ROS_BRIDGE_DEBUG
    std::thread t([client, client_name]() {
367
#else
368
    std::thread t([client]() {
369
#endif
370 371 372 373
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      client->stop();
      // The next lines of code seem to cause a double free or corruption error,
      // why?
374 375 376 377
//            client->on_open = NULL;
//            client->on_message = NULL;
//            client->on_close = NULL;
//            client->on_error = NULL;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
378
#ifdef ROS_BRIDGE_DEBUG
379
      std::cout << client_name << " has been removed" << std::endl;
380
#endif
381 382 383
    });
    t.detach();
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
384
#ifdef ROS_BRIDGE_DEBUG
385 386 387
  else {
    std::cerr << client_name << " has not been created" << std::endl;
  }
388 389 390
#endif
}

391 392 393 394 395 396 397 398 399
void RosbridgeWsClient::removeClient(const std::string &client_name) {
  stopClient(client_name);
  {
    std::lock_guard<std::mutex> lk(mutex);
    std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator it =
        client_map.find(client_name);
    if (it != client_map.end()) {
      client_map.erase(it);
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
400
#ifdef ROS_BRIDGE_DEBUG
401 402
    else {
      std::cerr << client_name << " has not been created" << std::endl;
403
    }
404 405
#endif
  }
406 407
}

408 409 410
std::string RosbridgeWsClient::getAdvertisedTopics() {
  std::lock_guard<std::mutex> lk(mutex);
  return available_topics;
411 412
}

413 414 415
std::string RosbridgeWsClient::getAdvertisedServices() {
  std::lock_guard<std::mutex> lk(mutex);
  return available_services;
416 417
}

418 419
bool RosbridgeWsClient::topicAvailable(const std::string &topic) {
  std::lock_guard<std::mutex> lk(mutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
420
#ifdef ROS_BRIDGE_DEBUG
421 422
  std::cout << "checking if topic " << topic << " is available" << std::endl;
  std::cout << "available topics: " << available_topics << std::endl;
423
#endif
424 425 426
  size_t pos;
  { pos = available_topics.find(topic); }
  bool ret = pos != std::string::npos ? true : false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
427
#ifdef ROS_BRIDGE_DEBUG
428 429 430 431 432
  if (ret) {
    std::cout << "topic " << topic << " is available" << std::endl;
  } else {
    std::cout << "topic " << topic << " is not available" << std::endl;
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
433
#endif
434
  return ret;
435 436
}

437 438 439 440 441 442 443 444 445 446 447 448
void RosbridgeWsClient::advertise(const std::string &client_name,
                                  const std::string &topic,
                                  const std::string &type,
                                  const std::string &id) {
  std::lock_guard<std::mutex> lk(mutex);
  std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator
      it_client = client_map.find(client_name);
  if (it_client != client_map.end()) {
    auto it_ser_top = std::find_if(
        service_topic_list.begin(), service_topic_list.end(),
        [topic](const EntryData &td) {
          return topic == std::get<integral(EntryEnum::ServiceTopicName)>(td);
449
        });
450
    if (it_ser_top != service_topic_list.end()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
451
#ifdef ROS_BRIDGE_DEBUG
452
      std::cerr << "topic: " << topic << " already advertised" << std::endl;
453
#endif
454 455 456 457 458 459 460 461 462 463 464 465 466
      return;
    }
    auto client = it_client->second;
    std::weak_ptr<WsClient> wpClient = client;
    service_topic_list.push_back(std::make_tuple(EntryType::AdvertisedTopic,
                                                 topic, client_name, wpClient));

    std::string message = "\"op\":\"advertise\", \"topic\":\"" + topic +
                          "\", \"type\":\"" + type + "\"";
    if (id.compare("") != 0) {
      message += ", \"id\":\"" + id + "\"";
    }
    message = "{" + message + "}";
467

Valentin Platzgummer's avatar
Valentin Platzgummer committed
468
#ifdef ROS_BRIDGE_DEBUG
469 470
    client->on_open = [this, topic, message, client_name](
                          std::shared_ptr<WsClient::Connection> connection) {
471
#else
472 473
    client->on_open = [this, topic, message](
                          std::shared_ptr<WsClient::Connection> connection) {
474 475
#endif

Valentin Platzgummer's avatar
Valentin Platzgummer committed
476
#ifdef ROS_BRIDGE_DEBUG
477 478
      std::cout << client_name << ": Opened connection" << std::endl;
      std::cout << client_name << ": Sending message: " << message << std::endl;
479
#endif
480 481
      connection->send(message);
    };
482

483 484
    start(client_name, client, message);
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
485
#ifdef ROS_BRIDGE_DEBUG
486 487 488
  else {
    std::cerr << client_name << "has not been created" << std::endl;
  }
489 490 491
#endif
}

492 493 494 495 496 497
void RosbridgeWsClient::unadvertise(const std::string &topic,
                                    const std::string &id) {
  std::lock_guard<std::mutex> lk(mutex);
  auto it_ser_top = std::find_if(
      service_topic_list.begin(), service_topic_list.end(),
      [&topic](const EntryData &td) {
498
        return topic == std::get<integral(EntryEnum::ServiceTopicName)>(td);
499 500
      });
  if (it_ser_top == service_topic_list.end()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
501
#ifdef ROS_BRIDGE_DEBUG
502
    std::cerr << "topic: " << topic << " not advertised" << std::endl;
503
#endif
504 505
    return;
  }
506

507 508 509 510 511 512
  std::string message = "\"op\":\"unadvertise\"";
  if (id.compare("") != 0) {
    message += ", \"id\":\"" + id + "\"";
  }
  message += ", \"topic\":\"" + topic + "\"";
  message = "{" + message + "}";
513

514 515
  std::string client_name = "topic_unadvertiser" + topic;
  auto client = std::make_shared<WsClient>(server_port_path);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
516
#ifdef ROS_BRIDGE_DEBUG
517 518
  client->on_open = [client_name, message](
                        std::shared_ptr<WsClient::Connection> connection) {
519
#else
520 521
  client->on_open =
      [message](std::shared_ptr<WsClient::Connection> connection) {
522 523
#endif

Valentin Platzgummer's avatar
Valentin Platzgummer committed
524
#ifdef ROS_BRIDGE_DEBUG
525 526
    std::cout << client_name << ": Opened connection" << std::endl;
    std::cout << client_name << ": Sending message: " << message << std::endl;
527
#endif
528 529 530
    connection->send(message); // unadvertise
    connection->send_close(1000);
  };
531

532 533
  start(client_name, client, message);
  service_topic_list.erase(it_ser_top);
534 535
}

536 537 538 539 540
void RosbridgeWsClient::unadvertiseAll() {
  for (auto entry : service_topic_list) {
    if (std::get<integral(EntryEnum::EntryType)>(entry) ==
        EntryType::AdvertisedTopic) {
      unadvertise(std::get<integral(EntryEnum::ServiceTopicName)>(entry));
541
    }
542
  }
543 544
}

545 546 547 548 549 550 551
void RosbridgeWsClient::publish(const std::string &topic,
                                const rapidjson::Document &msg,
                                const std::string &id) {
  std::lock_guard<std::mutex> lk(mutex);
  auto it_ser_top = std::find_if(
      service_topic_list.begin(), service_topic_list.end(),
      [&topic](const EntryData &td) {
552
        return topic == std::get<integral(EntryEnum::ServiceTopicName)>(td);
553 554
      });
  if (it_ser_top == service_topic_list.end()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
555
#ifdef ROS_BRIDGE_DEBUG
556
    std::cerr << "topic: " << topic << " not yet advertised" << std::endl;
557
#endif
558 559 560 561 562
    return;
  }
  rapidjson::StringBuffer strbuf;
  rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
  msg.Accept(writer);
563

564 565 566
  std::string client_name = "publish_client" + topic;
  std::string message = "\"op\":\"publish\", \"topic\":\"" + topic +
                        "\", \"msg\":" + strbuf.GetString();
567

568 569 570 571
  if (id.compare("") != 0) {
    message += ", \"id\":\"" + id + "\"";
  }
  message = "{" + message + "}";
572

573 574
  std::shared_ptr<WsClient> publish_client =
      std::make_shared<WsClient>(server_port_path);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
575
#ifdef ROS_BRIDGE_DEBUG
576 577
  publish_client->on_open =
      [message, client_name](std::shared_ptr<WsClient::Connection> connection) {
578
#else
579 580
  publish_client->on_open =
      [message, client_name](std::shared_ptr<WsClient::Connection> connection) {
581
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
582
#ifdef ROS_BRIDGE_DEBUG
583 584
        std::cout << client_name << ": Opened connection" << std::endl;
        std::cout << client_name << ": Sending message." << std::endl;
585 586
        std::cout << client_name << ": Sending message: " << message
                  << std::endl;
587 588 589
#endif
        connection->send(message);

590 591
        // TODO: This could be improved by creating a thread to keep publishing
        // the message instead of closing it right away
592
        connection->send_close(1000);
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
      };

  start(client_name, publish_client, message);
}

void RosbridgeWsClient::subscribe(const std::string &client_name,
                                  const std::string &topic,
                                  const InMessage &callback,
                                  const std::string &id,
                                  const std::string &type, int throttle_rate,
                                  int queue_length, int fragment_size,
                                  const std::string &compression) {
  std::lock_guard<std::mutex> lk(mutex);
  std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator
      it_client = client_map.find(client_name);
  if (it_client != client_map.end()) {
    auto it_ser_top = std::find_if(
        service_topic_list.begin(), service_topic_list.end(),
        [topic](const EntryData &td) {
          return topic == std::get<integral(EntryEnum::ServiceTopicName)>(td);
613
        });
614
    if (it_ser_top != service_topic_list.end()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
615
#ifdef ROS_BRIDGE_DEBUG
616
      std::cerr << "topic: " << topic << " already advertised" << std::endl;
617
#endif
618 619 620 621 622 623
      return;
    }
    auto client = it_client->second;
    std::weak_ptr<WsClient> wpClient = client;
    service_topic_list.push_back(std::make_tuple(EntryType::SubscribedTopic,
                                                 topic, client_name, wpClient));
624

625
    std::string message = "\"op\":\"subscribe\", \"topic\":\"" + topic + "\"";
626

627 628
    if (id.compare("") != 0) {
      message += ", \"id\":\"" + id + "\"";
629
    }
630 631 632 633 634
    if (type.compare("") != 0) {
      message += ", \"type\":\"" + type + "\"";
    }
    if (throttle_rate > -1) {
      message += ", \"throttle_rate\":" + std::to_string(throttle_rate);
635
    }
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    if (queue_length > -1) {
      message += ", \"queue_length\":" + std::to_string(queue_length);
    }
    if (fragment_size > -1) {
      message += ", \"fragment_size\":" + std::to_string(fragment_size);
    }
    if (compression.compare("none") == 0 || compression.compare("png") == 0) {
      message += ", \"compression\":\"" + compression + "\"";
    }
    message = "{" + message + "}";

    client->on_message = callback;
    this->start(client_name, client, message); // subscribe to topic
  }
#ifdef ROS_BRIDGE_DEBUG
  else {
    std::cerr << client_name << "has not been created" << std::endl;
  }
654 655 656
#endif
}

657 658 659 660 661 662
void RosbridgeWsClient::unsubscribe(const std::string &topic,
                                    const std::string &id) {
  std::lock_guard<std::mutex> lk(mutex);
  auto it_ser_top = std::find_if(
      service_topic_list.begin(), service_topic_list.end(),
      [topic](const EntryData &td) {
663
        return topic == std::get<integral(EntryEnum::ServiceTopicName)>(td);
664 665
      });
  if (it_ser_top == service_topic_list.end()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
666
#ifdef ROS_BRIDGE_DEBUG
667
    std::cerr << "topic: " << topic << " not advertised" << std::endl;
668
#endif
669 670
    return;
  }
671

672 673 674 675 676 677
  std::string message = "\"op\":\"unsubscribe\"";
  if (id.compare("") != 0) {
    message += ", \"id\":\"" + id + "\"";
  }
  message += ", \"topic\":\"" + topic + "\"";
  message = "{" + message + "}";
678

679 680
  std::string client_name = "topic_unsubscriber" + topic;
  auto client = std::make_shared<WsClient>(server_port_path);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
681
#ifdef ROS_BRIDGE_DEBUG
682 683
  client->on_open = [client_name, message](
                        std::shared_ptr<WsClient::Connection> connection) {
684
#else
685 686
  client->on_open =
      [message](std::shared_ptr<WsClient::Connection> connection) {
687 688
#endif

Valentin Platzgummer's avatar
Valentin Platzgummer committed
689
#ifdef ROS_BRIDGE_DEBUG
690 691
    std::cout << client_name << ": Opened connection" << std::endl;
    std::cout << client_name << ": Sending message: " << message << std::endl;
692
#endif
693 694 695
    connection->send(message); // unadvertise
    connection->send_close(1000);
  };
696

697 698
  start(client_name, client, message);
  service_topic_list.erase(it_ser_top);
699 700
}

701 702 703 704 705
void RosbridgeWsClient::unsubscribeAll() {
  for (auto entry : service_topic_list) {
    if (std::get<integral(EntryEnum::EntryType)>(entry) ==
        EntryType::SubscribedTopic) {
      unsubscribe(std::get<integral(EntryEnum::ServiceTopicName)>(entry));
706
    }
707
  }
708 709
}

710 711 712 713 714 715 716 717 718 719 720 721
void RosbridgeWsClient::advertiseService(const std::string &client_name,
                                         const std::string &service,
                                         const std::string &type,
                                         const InMessage &callback) {
  std::lock_guard<std::mutex> lk(mutex);
  std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator
      it_client = client_map.find(client_name);
  if (it_client != client_map.end()) {
    auto it_ser_top = std::find_if(
        service_topic_list.begin(), service_topic_list.end(),
        [service](const EntryData &td) {
          return service == std::get<integral(EntryEnum::ServiceTopicName)>(td);
722
        });
723
    if (it_ser_top != service_topic_list.end()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
724
#ifdef ROS_BRIDGE_DEBUG
725
      std::cerr << "service: " << service << " already advertised" << std::endl;
726
#endif
727 728 729 730 731 732
      return;
    }
    auto client = it_client->second;
    std::weak_ptr<WsClient> wpClient = client;
    service_topic_list.push_back(std::make_tuple(
        EntryType::AdvertisedService, service, client_name, wpClient));
733

734 735
    std::string message = "{\"op\":\"advertise_service\", \"service\":\"" +
                          service + "\", \"type\":\"" + type + "\"}";
736

737 738 739
    it_client->second->on_message = callback;
    start(client_name, it_client->second, message);
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
740
#ifdef ROS_BRIDGE_DEBUG
741 742 743
  else {
    std::cerr << client_name << "has not been created" << std::endl;
  }
744 745 746
#endif
}

747 748 749 750 751
void RosbridgeWsClient::unadvertiseService(const std::string &service) {
  std::lock_guard<std::mutex> lk(mutex);
  auto it_ser_top = std::find_if(
      service_topic_list.begin(), service_topic_list.end(),
      [service](const EntryData &td) {
752
        return service == std::get<integral(EntryEnum::ServiceTopicName)>(td);
753 754
      });
  if (it_ser_top == service_topic_list.end()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
755
#ifdef ROS_BRIDGE_DEBUG
756
    std::cerr << "service: " << service << " not advertised" << std::endl;
757
#endif
758 759
    return;
  }
760

761 762 763
  std::string message = "\"op\":\"unadvertise_service\"";
  message += ", \"service\":\"" + service + "\"";
  message = "{" + message + "}";
764

765 766
  std::string client_name = "service_unadvertiser" + service;
  auto client = std::make_shared<WsClient>(server_port_path);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
767
#ifdef ROS_BRIDGE_DEBUG
768 769
  client->on_open = [client_name, message](
                        std::shared_ptr<WsClient::Connection> connection) {
770
#else
771 772
  client->on_open =
      [message](std::shared_ptr<WsClient::Connection> connection) {
773 774
#endif

Valentin Platzgummer's avatar
Valentin Platzgummer committed
775
#ifdef ROS_BRIDGE_DEBUG
776 777
    std::cout << client_name << ": Opened connection" << std::endl;
    std::cout << client_name << ": Sending message: " << message << std::endl;
778
#endif
779 780 781
    connection->send(message); // unadvertise
    connection->send_close(1000);
  };
782

783 784
  start(client_name, client, message);
  service_topic_list.erase(it_ser_top);
785 786
}

787 788 789 790 791 792
void RosbridgeWsClient::unadvertiseAllServices() {
  for (auto entry : service_topic_list) {
    if (std::get<integral(EntryEnum::EntryType)>(entry) ==
        EntryType::AdvertisedService) {
      unadvertiseService(
          std::get<integral(EntryEnum::ServiceTopicName)>(entry));
793
    }
794
  }
795 796
}

797 798 799 800 801 802
void RosbridgeWsClient::serviceResponse(const std::string &service,
                                        const std::string &id, bool result,
                                        const rapidjson::Document &values) {
  std::string message = "\"op\":\"service_response\", \"service\":\"" +
                        service +
                        "\", \"result\":" + ((result) ? "true" : "false");
803

804 805 806 807
  // Rosbridge somehow does not allow service_response to be sent without id and
  // values , so we cannot omit them even though the documentation says they are
  // optional.
  message += ", \"id\":\"" + id + "\"";
808

809 810 811 812
  // Convert JSON document to string
  rapidjson::StringBuffer strbuf;
  rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
  values.Accept(writer);
813

814 815
  message += ", \"values\":" + std::string(strbuf.GetString());
  message = "{" + message + "}";
816

817 818 819
  std::string client_name = "service_response_client" + service;
  std::shared_ptr<WsClient> service_response_client =
      std::make_shared<WsClient>(server_port_path);
820

Valentin Platzgummer's avatar
Valentin Platzgummer committed
821
#ifdef ROS_BRIDGE_DEBUG
822 823
  service_response_client->on_open =
      [message, client_name](std::shared_ptr<WsClient::Connection> connection) {
824
#else
825 826
  service_response_client->on_open =
      [message](std::shared_ptr<WsClient::Connection> connection) {
827
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
828
#ifdef ROS_BRIDGE_DEBUG
829
        std::cout << client_name << ": Opened connection" << std::endl;
830 831
        std::cout << client_name << ": Sending message: " << message
                  << std::endl;
832 833 834 835
#endif
        connection->send(message);

        connection->send_close(1000);
836
      };
837

838
  start(client_name, service_response_client, message);
839 840
}

841 842 843 844 845 846 847
void RosbridgeWsClient::callService(const std::string &service,
                                    const InMessage &callback,
                                    const rapidjson::Document &args,
                                    const std::string &id, int fragment_size,
                                    const std::string &compression) {
  std::string message =
      "\"op\":\"call_service\", \"service\":\"" + service + "\"";
848

849 850 851 852
  if (!args.IsNull()) {
    rapidjson::StringBuffer strbuf;
    rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
    args.Accept(writer);
853

854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    message += ", \"args\":" + std::string(strbuf.GetString());
  }
  if (id.compare("") != 0) {
    message += ", \"id\":\"" + id + "\"";
  }
  if (fragment_size > -1) {
    message += ", \"fragment_size\":" + std::to_string(fragment_size);
  }
  if (compression.compare("none") == 0 || compression.compare("png") == 0) {
    message += ", \"compression\":\"" + compression + "\"";
  }
  message = "{" + message + "}";

  std::string client_name = "call_service_client" + service;
  std::shared_ptr<WsClient> call_service_client =
      std::make_shared<WsClient>(server_port_path);

  if (callback) {
    call_service_client->on_message = callback;
  } else {
    call_service_client->on_message =
        [client_name](std::shared_ptr<WsClient::Connection> connection,
                      std::shared_ptr<WsClient::InMessage> in_message) {
#ifdef ROS_BRIDGE_DEBUG
          std::cout << client_name
                    << ": Message received: " << in_message->string()
                    << std::endl;
          std::cout << client_name << ": Sending close connection" << std::endl;
882
#else
883
          (void)in_message;
884
#endif
885
          connection->send_close(1000);
886
        };
887
  }
888

889
  start(client_name, call_service_client, message);
890 891
}

892
bool RosbridgeWsClient::serviceAvailable(const std::string &service) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
893
#ifdef ROS_BRIDGE_DEBUG
894 895
  std::cout << "checking if service " << service << " is available"
            << std::endl;
896
#endif
897 898 899 900 901 902
  size_t pos;
  {
    std::lock_guard<std::mutex> lk(mutex);
    pos = available_services.find(service);
  }
  bool ret = pos != std::string::npos ? true : false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
903
#ifdef ROS_BRIDGE_DEBUG
904 905 906 907 908
  if (ret) {
    std::cout << "service " << service << " is available" << std::endl;
  } else {
    std::cout << "service " << service << " is not available" << std::endl;
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
909
#endif
910
  return ret;
911 912
}

913 914 915 916
void RosbridgeWsClient::waitForService(const std::string &service) {
  waitForService(service, [] {
    return false; // never stop
  });
917 918
}

919 920
void RosbridgeWsClient::waitForService(const std::string &service,
                                       const std::function<bool(void)> stop) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
921
#ifdef ROS_BRIDGE_DEBUG
922 923
  auto s = std::chrono::high_resolution_clock::now();
  long counter = 0;
924
#endif
925 926 927 928
  const auto poll_interval = std::chrono::milliseconds(1000);
  auto poll_time_point = std::chrono::high_resolution_clock::now();
  while (!stop()) {
    if (std::chrono::high_resolution_clock::now() > poll_time_point) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
929
#ifdef ROS_BRIDGE_DEBUG
930
      ++counter;
931
#endif
932 933 934 935 936 937 938 939 940
      if (serviceAvailable(service)) {
        break;
      }
      poll_time_point =
          std::chrono::high_resolution_clock::now() + poll_interval;
    } else {
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
941
#ifdef ROS_BRIDGE_DEBUG
942 943 944 945 946 947 948
  auto e = std::chrono::high_resolution_clock::now();
  std::cout
      << "waitForService() " << service << " time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(e - s).count()
      << " ms." << std::endl;
  std::cout << "waitForTopic() " << service
            << ": number of calls to topicAvailable: " << counter << std::endl;
949 950 951
#endif
}

952 953 954 955
void RosbridgeWsClient::waitForTopic(const std::string &topic) {
  waitForTopic(topic, [] {
    return false; // never stop
  });
956 957
}

958 959
void RosbridgeWsClient::waitForTopic(const std::string &topic,
                                     const std::function<bool(void)> stop) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
960
#ifdef ROS_BRIDGE_DEBUG
961 962
  auto s = std::chrono::high_resolution_clock::now();
  long counter = 0;
963
#endif
964 965 966 967
  const auto poll_interval = std::chrono::milliseconds(1000);
  auto poll_time_point = std::chrono::high_resolution_clock::now();
  while (!stop()) {
    if (std::chrono::high_resolution_clock::now() > poll_time_point) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
968
#ifdef ROS_BRIDGE_DEBUG
969
      ++counter;
970
#endif
971 972 973 974 975 976 977 978 979
      if (topicAvailable(topic)) {
        break;
      }
      poll_time_point =
          std::chrono::high_resolution_clock::now() + poll_interval;
    } else {
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
  };
Valentin Platzgummer's avatar
Valentin Platzgummer committed
980
#ifdef ROS_BRIDGE_DEBUG
981 982 983 984 985 986 987
  auto e = std::chrono::high_resolution_clock::now();
  std::cout
      << "waitForTopic() " << topic << " time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(e - s).count()
      << " ms." << std::endl;
  std::cout << "waitForTopic() " << topic
            << ": number of calls to topicAvailable: " << counter << std::endl;
988 989
#endif
}
990

991 992 993 994 995 996 997
bool is_valid_port_path(std::string server_port_path) {
  std::regex url_regex(
      "^(((([a-z]|[A-z])+([0-9]|_)*\\.*([a-z]|[A-z])+([0-9]|_)*))"
      "|(((1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\\.){3}(1?[0-9]{1,2}|2[0-4][0-9]|"
      "25[0-5]){1}))"
      ":[0-9]+$");
  return std::regex_match(server_port_path, url_regex);
998
}