MRPT  1.9.9
[mrpt-comms]

Detailed Description

Communication utilities: serial ports, networking (TCP, DNS,...), pub/sub nodelets.

Back to list of all libraries | See all modules

Library mrpt-comms

[New in MRPT 2.0.0]

This C++ library is part of MRPT and can be installed in Debian-based systems with:

    sudo apt install libmrpt-comms-dev

Find below some examples of use.

Nodelets-like Pub/Sub mechanism

MRPT provides a Publisher/Subscriber (Pub/Sub) pattern implementation for intra-process (multiple threads) zero-copy super fast communication.

Thread creation and handling is the responsibility of the user.

The main concepts are:

All these concepts are illustrated in the example below. Note that different subscribers are created: with a lambda, with a regular function, a std::bind(), etc.

See: comms_nodelets_example/NodeletsTest_impl.cpp

#include <cstdio> // printf()
#include <thread>
#include <chrono>
#include <iostream>
// Test payload:
const mrpt::poses::CPose3D p_tx(1.0, 2.0, 3.0, 0.2, 0.4, 0.6);
// Create the topic directory. Only once per process, and must be shared
// by all nodelets/threads.
{
using namespace mrpt::comms;
using namespace std;
try
{
#ifdef NODELETS_TEST_VERBOSE
printf("[publisher] Started\n");
#endif
for (int i = 0; i < 5; i++)
{
std::this_thread::sleep_for(100ms);
dir->getTopic("/robot/odom")->publish(p_tx);
}
#ifdef NODELETS_TEST_VERBOSE
printf("[publisher] Finish\n");
#endif
}
catch (std::exception& e)
{
cerr << e.what() << endl;
}
catch (...)
{
printf("[thread_publisher] Runtime error!\n");
}
}
{
#ifdef NODELETS_TEST_VERBOSE
std::cout << "sub2: rx CPose3D" << p.asString() << std::endl;
#endif
}
void onNewMsg2(int idx, const mrpt::poses::CPose3D& p)
{
#ifdef NODELETS_TEST_VERBOSE
std::cout << "onNewMsg2: idx=" << idx << " rx CPose3D" << p.asString()
<< std::endl;
#endif
}
{
using namespace mrpt::comms;
using namespace std;
try
{
#ifdef NODELETS_TEST_VERBOSE
printf("[subscriber] Connecting\n");
#endif
#ifdef NODELETS_TEST_VERBOSE
printf("[subscriber] Connected. Waiting for a message...\n");
#endif
// Create a subscriber with a lambda:
dir->getTopic("/robot/odom")
->createSubscriber<mrpt::poses::CPose3D>(
[](const mrpt::poses::CPose3D& p_rx) -> void {
#ifdef NODELETS_TEST_VERBOSE
std::cout << "sub1: rx CPose3D" << p_rx.asString()
<< std::endl;
#endif
});
// Create a subscriber with a regular function via std::function:
auto sub2 = dir->getTopic("/robot/odom")
->createSubscriber<mrpt::poses::CPose3D>(
std::function<void(const mrpt::poses::CPose3D&)>(
// Create a subscriber with a regular function:
auto sub3 = dir->getTopic("/robot/odom")
->createSubscriber<mrpt::poses::CPose3D>(&onNewMsg);
// Create a subscriber with std::bind:
using namespace std::placeholders;
auto sub4 = dir->getTopic("/robot/odom")
->createSubscriber<mrpt::poses::CPose3D>(std::bind(
onNewMsg2, 123 /*fixed 1st argument*/,
_1 /* 2nd arg is the subscribed data */));
// wait for messages to arrive.
// The nodelet is up and live until "sub" gets out of scope.
std::this_thread::sleep_for(1000ms);
#ifdef NODELETS_TEST_VERBOSE
printf("[subscriber] Finish\n");
#endif
}
catch (std::exception& e)
{
cerr << e.what() << endl;
}
catch (...)
{
cerr << "[thread_subscriber] Runtime error!" << endl;
}
}
{
using namespace std::chrono_literals;
std::thread(thread_publisher).detach();
std::thread(thread_subscriber).detach();
std::this_thread::sleep_for(1000ms);
}

HTTP request methods

mrpt::comms::net::http_get() is an easy way to GET an HTTP resource from any C++ program. You can also use mrpt::comms::net::http_request() to access APIs requiring the POST method.

See: comms_http_client/test.cpp

#include <iostream>
using namespace mrpt;
using namespace mrpt::comms;
using namespace mrpt::comms::net;
using namespace std;
string url = "http://www.google.es/";
{
string content;
string errmsg;
cout << "Retrieving " << url << "..." << endl;
url, content, errmsg, 80, "", "", nullptr, nullptr, &out_headers);
if (ret != net::erOk)
{
cout << " Error: " << errmsg << endl;
return;
}
string typ = out_headers.has("Content-Type") ? out_headers["Content-Type"]
: string("???");
cout << "Ok: " << content.size() << " bytes of type: " << typ << endl;
// cout << content << endl;
}

Classes

class  mrpt::comms::CClientTCPSocket
 A TCP socket that can be connected to a TCP server, implementing MRPT's CStream interface for passing objects as well as generic read/write methods. More...
 
struct  mrpt::comms::TFTDIDevice
 A list of FTDI devices and their descriptors. More...
 
class  mrpt::comms::CInterfaceFTDI
 A definition of a CStream actually representing a USB connection to a FTDI chip. More...
 
class  mrpt::comms::CSerialPort
 A communications serial port built as an implementation of a utils::CStream. More...
 
class  mrpt::comms::CServerTCPSocket
 A TCP socket that can be wait for client connections to enter. More...
 
class  mrpt::comms::Subscriber
 Nodelet-like Pub/Sub communications (in #include <mrpt/comms/nodelets.h>) More...
 

Namespaces

 mrpt::comms::net
 A set of useful routines for networking.
 

Enumerations

enum  mrpt::comms::net::ERRORCODE_HTTP {
  mrpt::comms::net::erOk = 0, mrpt::comms::net::erBadURL, mrpt::comms::net::erCouldntConnect, mrpt::comms::net::erNotFound,
  mrpt::comms::net::erOtherHTTPError
}
 Possible returns from a HTTP request. More...
 

Functions

ERRORCODE_HTTP mrpt::comms::net::http_get (const string &url, std::vector< uint8_t > &out_content, string &out_errormsg, int port=80, const string &auth_user=string(), const string &auth_pass=string(), int *out_http_responsecode=nullptr, mrpt::system::TParameters< string > *extra_headers=nullptr, mrpt::system::TParameters< string > *out_headers=nullptr, int timeout_ms=1000)
 Perform an HTTP GET operation (version for retrieving the data as a std::vector<uint8_t>) More...
 
ERRORCODE_HTTP mrpt::comms::net::http_get (const string &url, string &out_content, string &out_errormsg, int port=80, const string &auth_user=string(), const string &auth_pass=string(), int *out_http_responsecode=nullptr, mrpt::system::TParameters< string > *extra_headers=nullptr, mrpt::system::TParameters< string > *out_headers=nullptr, int timeout_ms=1000)
 Perform an HTTP GET operation (version for retrieving the data as text) More...
 
ERRORCODE_HTTP mrpt::comms::net::http_request (const string &http_method, const string &http_send_content, const string &url, std::vector< uint8_t > &out_content, string &out_errormsg, int port=80, const string &auth_user=string(), const string &auth_pass=string(), int *out_http_responsecode=nullptr, mrpt::system::TParameters< string > *extra_headers=nullptr, mrpt::system::TParameters< string > *out_headers=nullptr, int timeout_ms=1000)
 Generic function for HTTP GET & POST methods. More...
 
bool mrpt::comms::net::DNS_resolve_async (const std::string &server_name, std::string &out_ip, const unsigned int timeout_ms=3000)
 Resolve a server address by its name, returning its IP address as a string - This method has a timeout for the maximum time to wait for the DNS server. More...
 
std::string mrpt::comms::net::getLastSocketErrorStr ()
 Returns a description of the last Sockets error. More...
 
bool mrpt::comms::net::Ping (const std::string &address, const int max_attempts, std::string *output_str=NULL)
 Ping an IP address. More...
 

Enumeration Type Documentation

◆ ERRORCODE_HTTP

Possible returns from a HTTP request.

Enumerator
erOk 
erBadURL 
erCouldntConnect 
erNotFound 
erOtherHTTPError 

Definition at line 31 of file net_utils.h.

Function Documentation

◆ DNS_resolve_async()

bool mrpt::comms::net::DNS_resolve_async ( const std::string server_name,
std::string out_ip,
const unsigned int  timeout_ms = 3000 
)

Resolve a server address by its name, returning its IP address as a string - This method has a timeout for the maximum time to wait for the DNS server.

For example: server_name="www.google.com" -> out_ip="209.85.227.99"

Returns
true on success, false on timeout or other error.

Definition at line 404 of file net_utils.cpp.

References mrpt::system::os::memcpy(), and status.

Referenced by mrpt::comms::CClientTCPSocket::connect().

◆ getLastSocketErrorStr()

◆ http_get() [1/2]

ERRORCODE_HTTP mrpt::comms::net::http_get ( const string url,
std::vector< uint8_t > &  out_content,
string out_errormsg,
int  port = 80,
const string auth_user = string(),
const string auth_pass = string(),
int *  out_http_responsecode = nullptr,
mrpt::system::TParameters< string > *  extra_headers = nullptr,
mrpt::system::TParameters< string > *  out_headers = nullptr,
int  timeout_ms = 1000 
)

Perform an HTTP GET operation (version for retrieving the data as a std::vector<uint8_t>)

Parameters
urlMust be a simple string of the form "http://<servername>/<relative-address>".
portThe server port, if different from 80.
extra_headersIf provided, the given extra HTTP headers will be sent.
out_errormsgOn exit will contain a description of the error or "Ok".
out_contentThe buffer with the retrieved data.
out_http_responsecodeIf provided, will hold the HTTP code, eg: 200, 404...
out_headersIf provided, a copy of all the headers returned by the server will be saved here.
auth_userSend a basic HTTP authorization request with the given user & password.
auth_passSend a basic HTTP authorization request with the given user & password.
Returns
The error or success code.
See also
http_request()
Examples:
comms_http_client/test.cpp.

Definition at line 386 of file net_utils.cpp.

References mrpt::comms::net::http_request(), and url.

Referenced by mrpt::hwdrivers::CRovio::captureImageAsync(), mrpt::hwdrivers::CRovio::general_command(), mrpt::comms::net::http_get(), mrpt::hwdrivers::CRovio::initialize(), mrpt::hwdrivers::CRovio::path_management(), mrpt::hwdrivers::CRovio::pathRename(), mrpt::hwdrivers::CNTRIPClient::retrieveListOfMountpoints(), and mrpt::hwdrivers::CRovio::send_cmd_action().

◆ http_get() [2/2]

ERRORCODE_HTTP mrpt::comms::net::http_get ( const string url,
string out_content,
string out_errormsg,
int  port = 80,
const string auth_user = string(),
const string auth_pass = string(),
int *  out_http_responsecode = nullptr,
mrpt::system::TParameters< string > *  extra_headers = nullptr,
mrpt::system::TParameters< string > *  out_headers = nullptr,
int  timeout_ms = 1000 
)

Perform an HTTP GET operation (version for retrieving the data as text)

Parameters
urlMust be a simple string of the form "http://<servername>/<relative-address>".
portThe server port, if different from 80.
extra_headersIf provided, the given extra HTTP headers will be sent.
out_errormsgOn exit will contain a description of the error or "Ok".
out_contentThe buffer with the retrieved data.
out_http_responsecodeIf provided, will hold the HTTP code, eg: 200, 404...
out_headersIf provided, a copy of all the headers returned by the server will be saved here.
auth_userSend a basic HTTP authorization request with the given user & password.
auth_passSend a basic HTTP authorization request with the given user & password.
Returns
The error or success code.
See also
http_request()

Definition at line 51 of file net_utils.cpp.

References mrpt::comms::net::http_get(), mrpt::system::os::memcpy(), and url.

◆ http_request()

ERRORCODE_HTTP mrpt::comms::net::http_request ( const string http_method,
const string http_send_content,
const string url,
std::vector< uint8_t > &  out_content,
string out_errormsg,
int  port = 80,
const string auth_user = string(),
const string auth_pass = string(),
int *  out_http_responsecode = nullptr,
mrpt::system::TParameters< string > *  extra_headers = nullptr,
mrpt::system::TParameters< string > *  out_headers = nullptr,
int  timeout_ms = 1000 
)

◆ Ping()

bool mrpt::comms::net::Ping ( const std::string address,
const int  max_attempts,
std::string output_str = NULL 
)

Ping an IP address.

Parameters
[in]addressAddress to ping.
[in]max_attemptsNumber of attempts to try and ping.
[out]outputString containing output information
Returns
True if responsive, false otherwise.
Note
{ I am redirecting stderr to stdout, so that the overall process is simplified. Otherwise see: https://jineshkj.wordpress.com/2006/12/22/how-to-capture-stdin-stdout-and-stderr-of-child-program/ }

Definition at line 498 of file net_utils.cpp.

References mrpt::system::executeCommand(), and mrpt::to_string().




Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: 7d5e6d718 Fri Aug 24 01:51:28 2018 +0200 at lun nov 2 08:35:50 CET 2020