RosBridgeClient.cpp 36 KB
Newer Older
1 2
#include "RosBridgeClient.h"

3

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
10 11

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

19 20 21
void RosbridgeWsClient::start(const std::__cxx11::string &client_name, std::shared_ptr<WsClient> client, const std::__cxx11::string &message)
{
#ifndef DEBUG
22
    (void)client_name;
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
#endif
    if (!client->on_open)
    {
#ifdef DEBUG
        client->on_open = [client_name, message](std::shared_ptr<WsClient::Connection> connection) {
#else
        client->on_open = [message](std::shared_ptr<WsClient::Connection> connection) {
#endif

#ifdef DEBUG
            std::cout << client_name << ": Opened connection" << std::endl;
            std::cout << client_name << ": Sending message: " << message << std::endl;
#endif
            connection->send(message);
        };
    }

#ifdef DEBUG
    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;
        };
    }

    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;
        };
    }

    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;
        };
    }

#endif
#ifdef DEBUG
    std::thread client_thread([client_name, client]() {
#else
67
    std::thread client_thread([client]() {
68 69 70 71 72 73 74 75 76 77
#endif
        client->start();

#ifdef DEBUG
        std::cout << client_name << ": Terminated" << std::endl;
#endif
        client->on_open = NULL;
        client->on_message = NULL;
        client->on_close = NULL;
        client->on_error = NULL;
78
#ifdef DEBUG
79
        std::cout << client_name << " thread end" << std::endl;
80
#endif
81 82 83 84 85
    });

    client_thread.detach();
}

86
RosbridgeWsClient::RosbridgeWsClient(const std::string &server_port_path, bool run) :
87
    server_port_path(server_port_path)
88
  , isConnected(std::make_shared<std::atomic_bool>(false))
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  , stopped(std::make_shared<std::atomic_bool>(true))
{
    if ( run )
        this->run();
}

RosbridgeWsClient::RosbridgeWsClient(const std::__cxx11::string &server_port_path) :
    RosbridgeWsClient::RosbridgeWsClient(server_port_path, true)
{
}

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

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

void RosbridgeWsClient::run()
110
{
111 112 113
    if ( !stopped->load() )
        return;
    stopped->store(false);
114 115 116 117 118
    // 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();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
119
        while ( !this->stopped->load() ) {
120 121 122 123 124
            // ====================================================================================
            // Add tasks.
            // ====================================================================================
            if ( std::chrono::high_resolution_clock::now() > poll_time_point) {
                poll_time_point = std::chrono::high_resolution_clock::now() + poll_interval;
125
#ifdef DEBUG
126 127
                std::cout << "Starting new poll." << std::endl;
                std::cout << "connected: " << this->isConnected->load() << std::endl;
128
#endif
129 130 131 132 133
                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;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
134
                });
135
                if ( it == task_list.end() ){
136
#ifdef DEBUG
137
                    std::cout << "Adding status_task" << std::endl;
138
#endif
139 140 141 142
                    // 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>) {
143
#ifdef DEBUG
144
                            std::cout << "status_client opened" << std::endl;
145
#endif
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 182
                            this->isConnected->store(true);
                            status_set->store(true);
                    };

                    std::thread status_thread([status_client]{
                        status_client->start();
                        status_client->on_open = NULL;
                        status_client->on_message = NULL;
                        status_client->on_close = NULL;
                        status_client->on_error = NULL;
                    });
                    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);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
183
                }
184 185 186 187 188 189 190 191 192

                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.
193
#ifdef DEBUG
194
                        std::cout << "Adding reset_topics_task" << std::endl;
195
#endif
196 197 198 199
                        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){
200 201 202
#ifdef DEBUG
                            std::cout << "/rosapi/topics: " << in_message->string() << std::endl;
#endif
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
                            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.
244
#ifdef DEBUG
245
                        std::cout << "Adding reset_services_task" << std::endl;
246
#endif
247 248 249 250
                        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){
251 252 253
#ifdef DEBUG
                            std::cout << "/rosapi/services: " << in_message->string() << std::endl;
#endif
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
                            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();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
291 292 293
                }
            }

294 295 296 297
            // ====================================================================================
            // Process tasks.
            // ====================================================================================
            for ( auto task_it = task_list.begin(); task_it != task_list.end(); ){
298 299 300
#ifdef DEBUG
                std::cout << "processing task: " << task_it->name << std::endl;
#endif
301 302
                if ( !task_it->expired() ){
                    if ( task_it->ready() ){
303 304 305
#ifdef DEBUG
                        std::cout << "executing task: " << task_it->name << std::endl;
#endif
306 307 308
                        task_it->execute();
                        task_it = task_list.erase(task_it);
                    } else {
309 310 311
#ifdef DEBUG
                        std::cout << "noting to do for task: " << task_it->name << std::endl;
#endif
312 313 314
                        ++task_it;
                    }
                } else {
315 316 317
#ifdef DEBUG
                    std::cout << "task expired: " << task_it->name << std::endl;
#endif
318 319 320
                    task_it->clear_up();
                    task_it = task_list.erase(task_it);
                }
321
            }
322 323 324 325 326 327 328

            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();
329
        }
330
        task_list.clear();
331
#ifdef DEBUG
332
        std::cout << "periodic thread end" << std::endl;
333
#endif
334
    });
335

336 337
}

338
void RosbridgeWsClient::stop()
339
{
340 341
    if ( stopped->load() )
        return;
342
    stopped->store(true);
343 344 345 346 347 348
    periodic_thread->join();
}

void RosbridgeWsClient::reset()
{
    stop();
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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    unsubscribeAll();
    unadvertiseAll();
    unadvertiseAllServices();
    for (auto& client : client_map)
    {
        removeClient(client.first);
    }
}

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);
    }
#ifdef DEBUG
    else
    {
        std::cerr << client_name << " has already been created" << std::endl;
    }
#endif
}

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;
}

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 DEBUG
        std::thread t([client, client_name](){
#else
397
        std::thread t([client](){
398 399 400
#endif
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            client->stop();
401 402 403 404 405
            // The next lines of code seem to cause a double free or corruption error, why?
//            client->on_open = NULL;
//            client->on_message = NULL;
//            client->on_close = NULL;
//            client->on_error = NULL;
406
#ifdef DEBUG
407
            std::cout << "removeClient thread: " << client_name << " reference count: " << client.use_count() << std::endl;
408 409 410 411 412 413 414 415 416 417 418 419 420
            std::cout << client_name << " has been removed" << std::endl;
#endif
        });
        t.detach();
    }
#ifdef DEBUG
    else
    {
        std::cerr << client_name << " has not been created" << std::endl;
    }
#endif
}

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
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);
        }
#ifdef DEBUG
        else
        {
            std::cerr << client_name << " has not been created" << std::endl;
        }
#endif
    }
}

440
std::string RosbridgeWsClient::getAdvertisedTopics(){
Valentin Platzgummer's avatar
Valentin Platzgummer committed
441 442
    std::lock_guard<std::mutex> lk(mutex);
    return available_topics;
443 444 445
}

std::string RosbridgeWsClient::getAdvertisedServices(){
Valentin Platzgummer's avatar
Valentin Platzgummer committed
446 447
    std::lock_guard<std::mutex> lk(mutex);
    return available_services;
448 449 450 451 452 453
}

bool RosbridgeWsClient::topicAvailable(const std::string &topic){
#ifdef DEBUG
    std::cout << "checking if topic " << topic << " is available" << std::endl;
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
454 455 456 457 458
    size_t pos;
    {
        std::lock_guard<std::mutex> lk(mutex);
        pos = available_topics.find(topic);
    }
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 513 514 515 516
    return pos != std::string::npos ? true : false;
}

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);
        });
        if ( it_ser_top != service_topic_list.end()){
#ifdef DEBUG
            std::cerr << "topic: " << topic << " already advertised" << std::endl;
#endif
            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 + "}";

#ifdef DEBUG
        client->on_open = [this, topic, message, client_name](std::shared_ptr<WsClient::Connection> connection) {
#else
        client->on_open = [this, topic, message](std::shared_ptr<WsClient::Connection> connection) {
#endif

#ifdef DEBUG
            std::cout << client_name << ": Opened connection" << std::endl;
            std::cout << client_name << ": Sending message: " << message << std::endl;
#endif
            connection->send(message);
        };

        start(client_name, client, message);
    }
#ifdef DEBUG
    else
    {
        std::cerr << client_name << "has not been created" << std::endl;
    }
#endif
}

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(),
517
                                   [&topic](const EntryData &td){
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
        return topic == std::get<integral(EntryEnum::ServiceTopicName)>(td);
    });
    if ( it_ser_top == service_topic_list.end()){
#ifdef DEBUG
        std::cerr << "topic: " << topic << " not advertised" << std::endl;
#endif
        return;
    }

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

    std::string client_name = "topic_unadvertiser" + topic;
    auto client = std::make_shared<WsClient>(server_port_path);
#ifdef DEBUG
    client->on_open = [client_name, message](std::shared_ptr<WsClient::Connection> connection) {
#else
    client->on_open = [message](std::shared_ptr<WsClient::Connection> connection) {
#endif

#ifdef DEBUG
        std::cout << client_name << ": Opened connection" << std::endl;
        std::cout << client_name << ": Sending message: " << message << std::endl;
#endif
        connection->send(message); // unadvertise
        connection->send_close(1000);
    };

    start(client_name, client, message);
    service_topic_list.erase(it_ser_top);
}

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));
        }
    }
}

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){
        return topic == std::get<integral(EntryEnum::ServiceTopicName)>(td);
    });
    if ( it_ser_top == service_topic_list.end() ){
#ifdef DEBUG
        std::cerr << "topic: " << topic << " not yet advertised" << std::endl;
#endif
        return;
    }
    rapidjson::StringBuffer strbuf;
    rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
    msg.Accept(writer);

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

    if (id.compare("") != 0)
    {
        message += ", \"id\":\"" + id + "\"";
    }
    message = "{" + message + "}";

    std::shared_ptr<WsClient> publish_client = std::make_shared<WsClient>(server_port_path);
#ifdef DEBUG
    publish_client->on_open = [message, client_name](std::shared_ptr<WsClient::Connection> connection) {
#else
    publish_client->on_open = [message, client_name](std::shared_ptr<WsClient::Connection> connection) {
#endif
#ifdef DEBUG
        std::cout << client_name << ": Opened connection" << std::endl;
        std::cout << client_name << ": Sending message." << std::endl;
599
        std::cout << client_name << ": Sending message: " << message << std::endl;
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 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 735 736 737 738 739 740 741 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
#endif
        connection->send(message);

        // TODO: This could be improved by creating a thread to keep publishing the message instead of closing it right away
        connection->send_close(1000);
    };

    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);
        });
        if ( it_ser_top != service_topic_list.end()){
#ifdef DEBUG
            std::cerr << "topic: " << topic << " already advertised" << std::endl;
#endif
            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));

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

        if (id.compare("") != 0)
        {
            message += ", \"id\":\"" + id + "\"";
        }
        if (type.compare("") != 0)
        {
            message += ", \"type\":\"" + type + "\"";
        }
        if (throttle_rate > -1)
        {
            message += ", \"throttle_rate\":" + std::to_string(throttle_rate);
        }
        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 DEBUG
    else
    {
        std::cerr << client_name << "has not been created" << std::endl;
    }
#endif
}

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){
        return topic == std::get<integral(EntryEnum::ServiceTopicName)>(td);
    });
    if ( it_ser_top == service_topic_list.end()){
#ifdef DEBUG
        std::cerr << "topic: " << topic << " not advertised" << std::endl;
#endif
        return;
    }

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

    std::string client_name = "topic_unsubscriber" + topic;
    auto client = std::make_shared<WsClient>(server_port_path);
#ifdef DEBUG
    client->on_open = [client_name, message](std::shared_ptr<WsClient::Connection> connection) {
#else
    client->on_open = [message](std::shared_ptr<WsClient::Connection> connection) {
#endif

#ifdef DEBUG
        std::cout << client_name << ": Opened connection" << std::endl;
        std::cout << client_name << ": Sending message: " << message << std::endl;
#endif
        connection->send(message); // unadvertise
        connection->send_close(1000);
    };

    start(client_name, client, message);
    service_topic_list.erase(it_ser_top);
}

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));
        }
    }
}

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);
        });
        if ( it_ser_top != service_topic_list.end()){
#ifdef DEBUG
            std::cerr << "service: " << service << " already advertised" << std::endl;
#endif
            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));

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

        it_client->second->on_message = callback;
        start(client_name, it_client->second, message);
    }
#ifdef DEBUG
    else
    {
        std::cerr << client_name << "has not been created" << std::endl;
    }
#endif
}

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){
        return service == std::get<integral(EntryEnum::ServiceTopicName)>(td);
    });
    if ( it_ser_top == service_topic_list.end()){
#ifdef DEBUG
        std::cerr << "service: " << service << " not advertised" << std::endl;
#endif
        return;
    }

    std::string message = "\"op\":\"unadvertise_service\"";
    message += ", \"service\":\"" + service + "\"";
    message = "{" + message + "}";

772
    std::string client_name = "service_unadvertiser" + service;
773 774 775 776 777 778 779 780 781 782 783 784 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 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 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 882 883 884 885 886 887 888 889
    auto client = std::make_shared<WsClient>(server_port_path);
#ifdef DEBUG
    client->on_open = [client_name, message](std::shared_ptr<WsClient::Connection> connection) {
#else
    client->on_open = [message](std::shared_ptr<WsClient::Connection> connection) {
#endif

#ifdef DEBUG
        std::cout << client_name << ": Opened connection" << std::endl;
        std::cout << client_name << ": Sending message: " << message << std::endl;
#endif
        connection->send(message); // unadvertise
        connection->send_close(1000);
    };

    start(client_name, client, message);
    service_topic_list.erase(it_ser_top);
}

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));
        }
    }
}

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");

    // 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 + "\"";

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

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

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

#ifdef DEBUG
    service_response_client->on_open = [message, client_name](std::shared_ptr<WsClient::Connection> connection) {
#else
    service_response_client->on_open = [message](std::shared_ptr<WsClient::Connection> connection) {
#endif
#ifdef DEBUG
        std::cout << client_name << ": Opened connection" << std::endl;
        std::cout << client_name << ": Sending message: " << message << std::endl;
#endif
        connection->send(message);

        connection->send_close(1000);
    };

    start(client_name, service_response_client, message);
}

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 + "\"";

    if (!args.IsNull())
    {
        rapidjson::StringBuffer strbuf;
        rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
        args.Accept(writer);

        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 DEBUG
            std::cout << client_name << ": Message received: " << in_message->string() << std::endl;
            std::cout << client_name << ": Sending close connection" << std::endl;
#else
            (void)in_message;
#endif
            connection->send_close(1000);
        };
    }

    start(client_name, call_service_client, message);
}

bool RosbridgeWsClient::serviceAvailable(const std::string &service)
{
#ifdef DEBUG
    std::cout << "checking if service " << service << " is available" << std::endl;
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
890 891 892 893 894
    size_t pos;
    {
        std::lock_guard<std::mutex> lk(mutex);
        pos = available_services.find(service);
    }
895 896 897 898 899
    return pos != std::string::npos ? true : false;
}

void RosbridgeWsClient::waitForService(const std::string &service)
{
900 901 902
    waitForService(service, []{
        return false; // never stop
    });
903 904
}

905
void RosbridgeWsClient::waitForService(const std::string &service, const std::function<bool(void)> stop)
906 907 908 909 910
{
#ifdef DEBUG
    auto s = std::chrono::high_resolution_clock::now();
    long counter = 0;
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
911
    const auto poll_interval = std::chrono::milliseconds(1000);
912 913
    auto poll_time_point = std::chrono::high_resolution_clock::now() + poll_interval;
    while( !stop() )
914
    {
915
        if ( std::chrono::high_resolution_clock::now() > poll_time_point ){
916
#ifdef DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
917
            ++counter;
918
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
919 920 921
            if ( serviceAvailable(service) ){
                break;
            } else {
922
                poll_time_point = std::chrono::high_resolution_clock::now() + poll_interval;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
923 924
            }
        } else {
925
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
926 927 928 929 930 931 932 933 934 935 936 937 938 939
        }
    };
#ifdef DEBUG
    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;
#endif
}

void RosbridgeWsClient::waitForTopic(const std::string &topic)
{
940 941 942
    waitForTopic(topic, []{
        return false; // never stop
    });
943 944
}

945
void RosbridgeWsClient::waitForTopic(const std::string &topic, const std::function<bool(void)> stop)
946 947 948 949 950
{
#ifdef DEBUG
    auto s = std::chrono::high_resolution_clock::now();
    long counter = 0;
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
951
    const auto poll_interval = std::chrono::milliseconds(1000);
952 953
    auto poll_time_point = std::chrono::high_resolution_clock::now() + poll_interval;
    while( !stop() )
954
    {
955
        if ( std::chrono::high_resolution_clock::now() > poll_time_point ){
956
#ifdef DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
957
            ++counter;
958
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
959 960 961
            if ( topicAvailable(topic) ){
                break;
            } else {
962
                poll_time_point = std::chrono::high_resolution_clock::now() + poll_interval;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
963 964
            }
        } else {
965
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
966 967 968 969 970 971 972 973 974 975 976
        }
    };
#ifdef DEBUG
    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;
#endif
}
977 978 979 980 981 982 983 984

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);
}