RosBridgeClient.h 13 KB
Newer Older
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#pragma once

/*
*  Created on: Apr 16, 2018
*      Author: Poom Pianpak
*/

#include "Simple-WebSocket-Server/client_ws.hpp"

#include "rapidjson/include/rapidjson/document.h"
#include "rapidjson/include/rapidjson/writer.h"
#include "rapidjson/include/rapidjson/stringbuffer.h"
#include "rapidjson/include/rapidjson/ostreamwrapper.h"

#include <chrono>
#include <functional>
#include <thread>
18 19
#include <future>
#include <functional>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
20
#include <mutex>
Valentin Platzgummer's avatar
Valentin Platzgummer committed
21 22 23 24 25 26 27 28

using WsClient = SimpleWeb::SocketClient<SimpleWeb::WS>;
using InMessage =  std::function<void(std::shared_ptr<WsClient::Connection>, std::shared_ptr<WsClient::InMessage>)>;

class RosbridgeWsClient
{
 std::string server_port_path;
 std::unordered_map<std::string, std::shared_ptr<WsClient>> client_map;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
29
 std::mutex map_mutex;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
30

31
 // Starts the client.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
32 33 34 35
 void start(const std::string& client_name, std::shared_ptr<WsClient> client, const std::string& message)
 {
   if (!client->on_open)
   {
36
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
37 38 39 40 41
     client->on_open = [client_name, message](std::shared_ptr<WsClient::Connection> connection) {
#else
     client->on_open = [message](std::shared_ptr<WsClient::Connection> connection) {
#endif

42
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
43 44 45 46 47 48 49
       std::cout << client_name << ": Opened connection" << std::endl;
       std::cout << client_name << ": Sending message: " << message << std::endl;
#endif
       connection->send(message);
     };
   }

50
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
   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

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

81
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
     std::cout << client_name << ": Terminated" << std::endl;
#endif
     client->on_open = NULL;
     client->on_message = NULL;
     client->on_close = NULL;
     client->on_error = NULL;
   });

   client_thread.detach();
 }

public:
 RosbridgeWsClient(const std::string& server_port_path)
 {
   this->server_port_path = server_port_path;
 }

 ~RosbridgeWsClient()
 {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
101 102

   std::lock_guard<std::mutex> lk(map_mutex); // neccessary?
Valentin Platzgummer's avatar
Valentin Platzgummer committed
103 104 105 106 107 108 109
   for (auto& client : client_map)
   {
     client.second->stop();
     client.second.reset();
   }
 }

110 111 112 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
 // The execution can take up to 100 ms!
 bool connected(){

    auto p = std::make_shared<std::promise<void>>();
    auto future = p->get_future();

    auto callback = [](std::shared_ptr<WsClient::Connection> connection, std::shared_ptr<std::promise<void>> p) {
        p->set_value();
        connection->send_close(1000);
    };
    std::shared_ptr<WsClient> status_client = std::make_shared<WsClient>(server_port_path);
    status_client->on_open = std::bind(callback, std::placeholders::_1, p);

    std::async([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;

    });

    auto status = future.wait_for(std::chrono::milliseconds(100));
    return status == std::future_status::ready;
 }

 // Adds a client to the client_map.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
138 139
 void addClient(const std::string& client_name)
 {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
140 141

   std::lock_guard<std::mutex> lk(map_mutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
142 143 144 145 146
   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);
   }
147
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
148 149 150 151 152 153 154 155 156
   else
   {
     std::cerr << client_name << " has already been created" << std::endl;
   }
#endif
 }

 std::shared_ptr<WsClient> getClient(const std::string& client_name)
 {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
157 158

   std::lock_guard<std::mutex> lk(map_mutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
159 160 161 162 163 164 165 166 167 168
   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 stopClient(const std::string& client_name)
 {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
169 170

   std::lock_guard<std::mutex> lk(map_mutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
171 172 173 174 175 176 177 178
   std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator it = client_map.find(client_name);
   if (it != client_map.end())
   {
     it->second->stop();
     it->second->on_open = NULL;
     it->second->on_message = NULL;
     it->second->on_close = NULL;
     it->second->on_error = NULL;
179
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
180 181 182
     std::cout << client_name << " has been stopped" << std::endl;
#endif
   }
183
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
184 185 186 187 188 189 190 191 192
   else
   {
     std::cerr << client_name << " has not been created" << std::endl;
   }
#endif
 }

 void removeClient(const std::string& client_name)
 {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
193 194

   std::lock_guard<std::mutex> lk(map_mutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
195 196 197
   std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator it = client_map.find(client_name);
   if (it != client_map.end())
   {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
198 199 200 201 202 203 204 205 206
     // Stop the client asynchronously in 100 ms.
     // This is to ensure, that all threads involving client have been launched.
     std::thread t([](std::shared_ptr<WsClient> client){
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        client->stop();
        client.reset();
     },
     it->second /*lambda param*/ );

Valentin Platzgummer's avatar
Valentin Platzgummer committed
207
     client_map.erase(it);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
208
     t.detach();
209
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
210 211 212
     std::cout << client_name << " has been removed" << std::endl;
#endif
   }
213
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
214 215 216 217 218 219 220
   else
   {
     std::cerr << client_name << " has not been created" << std::endl;
   }
#endif
 }

221
 // Gets the client from client_map and starts it. Advertising is essentially sending a message.
222
 // One client per topic!
Valentin Platzgummer's avatar
Valentin Platzgummer committed
223 224
 void advertise(const std::string& client_name, const std::string& topic, const std::string& type, const std::string& id = "")
 {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
225 226

   std::lock_guard<std::mutex> lk(map_mutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
227 228 229 230 231 232 233 234 235 236 237 238 239
   std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator it = client_map.find(client_name);
   if (it != client_map.end())
   {
     std::string message = "\"op\":\"advertise\", \"topic\":\"" + topic + "\", \"type\":\"" + type + "\"";

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

     start(client_name, it->second, message);
   }
240
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
   else
   {
     std::cerr << client_name << "has not been created" << std::endl;
   }
#endif
 }

 void publish(const std::string& topic, const rapidjson::Document& msg, const std::string& id = "")
 {
   rapidjson::StringBuffer strbuf;
   rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
   msg.Accept(writer);

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

   publish_client->on_open = [message](std::shared_ptr<WsClient::Connection> connection) {
265
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279
     std::cout << "publish_client: Opened connection" << std::endl;
     std::cout << "publish_client: Sending message: " << message << std::endl;
#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("publish_client", publish_client, message);
 }

 void subscribe(const std::string& client_name, const std::string& topic, const InMessage& callback, const std::string& id = "", const std::string& type = "", int throttle_rate = -1, int queue_length = -1, int fragment_size = -1, const std::string& compression = "")
 {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
280 281

   std::lock_guard<std::mutex> lk(map_mutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
   std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator it = client_map.find(client_name);
   if (it != client_map.end())
   {
     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 + "}";

     it->second->on_message = callback;
     start(client_name, it->second, message);
   }
316
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
317 318 319 320 321 322 323 324 325
   else
   {
     std::cerr << client_name << "has not been created" << std::endl;
   }
#endif
 }

 void advertiseService(const std::string& client_name, const std::string& service, const std::string& type, const InMessage& callback)
 {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
326 327

   std::lock_guard<std::mutex> lk(map_mutex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
328 329 330 331 332 333 334 335
   std::unordered_map<std::string, std::shared_ptr<WsClient>>::iterator it = client_map.find(client_name);
   if (it != client_map.end())
   {
     std::string message = "{\"op\":\"advertise_service\", \"service\":\"" + service + "\", \"type\":\"" + type + "\"}";

     it->second->on_message = callback;
     start(client_name, it->second, message);
   }
336
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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
   else
   {
     std::cerr << client_name << "has not been created" << std::endl;
   }
#endif
 }

 void 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::shared_ptr<WsClient> service_response_client = std::make_shared<WsClient>(server_port_path);

   service_response_client->on_open = [message](std::shared_ptr<WsClient::Connection> connection) {
363
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
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 397 398 399 400 401 402 403 404 405 406 407 408 409
     std::cout << "service_response_client: Opened connection" << std::endl;
     std::cout << "service_response_client: Sending message: " << message << std::endl;
#endif
     connection->send(message);

     connection->send_close(1000);
   };

   start("service_response_client", service_response_client, message);
 }

 void callService(const std::string& service, const InMessage& callback, const rapidjson::Document& args = {}, const std::string& id = "", int fragment_size = -1, 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::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 = [](std::shared_ptr<WsClient::Connection> connection, std::shared_ptr<WsClient::InMessage> in_message) {
410
#ifdef ROS_BRIDGE_CLIENT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
411 412 413 414 415 416 417 418 419 420 421 422
       std::cout << "call_service_client: Message received: " << in_message->string() << std::endl;
       std::cout << "call_service_client: Sending close connection" << std::endl;
#endif
       connection->send_close(1000);
     };
   }

   start("call_service_client", call_service_client, message);
 }
};