Skip to content

Commit 57a134a

Browse files
committed
check for exact primitive type before publishing
1 parent 8a7fcce commit 57a134a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/MqttClient.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ SOFTWARE.
2525
*/
2626

2727

28+
#include <algorithm>
2829
#include <cstdint>
2930
#include <cstring>
3031
#include <vector>
@@ -534,6 +535,57 @@ void MqttClient::mqtt2ros(mqtt::const_message_ptr mqtt_msg,
534535
}
535536

536537

538+
void MqttClient::mqtt2primitive(mqtt::const_message_ptr mqtt_msg) {
539+
540+
bool found_primitive = false;
541+
const std::string str_msg = mqtt_msg->to_string();
542+
543+
// check for bool
544+
if (!found_primitive) {
545+
std::string bool_str = str_msg;
546+
std::transform(str_msg.cbegin(), str_msg.cend(), bool_str.begin(),
547+
::tolower);
548+
if (bool_str == "true" || bool_str == "false") {
549+
found_primitive = true;
550+
bool bool_msg = (bool_str == "true");
551+
NODELET_INFO("Got bool: %d", bool_msg);
552+
}
553+
}
554+
555+
// check for int
556+
if (!found_primitive) {
557+
std::size_t pos;
558+
try {
559+
const int int_msg = std::stoi(str_msg, &pos);
560+
if (pos == str_msg.size()) {
561+
found_primitive = true;
562+
NODELET_INFO("Got int: %d", int_msg);
563+
}
564+
} catch (const std::invalid_argument& ex) {
565+
} catch (const std::out_of_range& ex) {
566+
}
567+
}
568+
569+
// check for float
570+
if (!found_primitive) {
571+
std::size_t pos;
572+
try {
573+
const float float_msg = std::stof(str_msg, &pos);
574+
if (pos == str_msg.size()) {
575+
found_primitive = true;
576+
NODELET_INFO("Got float: %f", float_msg);
577+
}
578+
} catch (const std::invalid_argument& ex) {
579+
} catch (const std::out_of_range& ex) {
580+
}
581+
}
582+
583+
if (!found_primitive) {
584+
NODELET_INFO("Got string: %s", str_msg.c_str());
585+
}
586+
}
587+
588+
537589
void MqttClient::connected(const std::string& cause) {
538590

539591
is_connected_ = true;

0 commit comments

Comments
 (0)