Goby3 3.7.0
2026.11.12
Loading...
Searching...
No Matches
publish_subscribe_tool.h
Go to the documentation of this file.
1// Copyright 2026:
2// GobySoft, LLC (2013-)
3// Community contributors (see AUTHORS file)
4// File authors:
5// Toby Schneider <toby@gobysoft.org>
6//
7//
8// This file is part of the Goby Underwater Autonomy Project Libraries
9// ("The Goby Libraries").
10//
11// The Goby Libraries are free software: you can redistribute them and/or modify
12// them under the terms of the GNU Lesser General Public License as published by
13// the Free Software Foundation, either version 2.1 of the License, or
14// (at your option) any later version.
15//
16// The Goby Libraries are distributed in the hope that they will be useful,
17// but WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19// GNU Lesser General Public License for more details.
20//
21// You should have received a copy of the GNU Lesser General Public License
22// along with Goby. If not, see <http://www.gnu.org/licenses/>.
23
24#ifndef GOBY_MIDDLEWARE_TOOL_PUBLISH_SUBSCRIBE_TOOL_H
25#define GOBY_MIDDLEWARE_TOOL_PUBLISH_SUBSCRIBE_TOOL_H
26
27#include <chrono>
28#include <map>
29#include <memory>
30#include <regex>
31#include <set>
32#include <string>
33#include <vector>
34
35#include <google/protobuf/text_format.h>
36
37#include "dccl/dynamic_protobuf_manager.h"
38
47#include "goby/time/convert.h"
50
51// after the marshalling headers: the transporters they pull in resolve scheme<Data>() at
52// template definition, so each scheme must already be declared
55
56namespace goby
57{
58namespace middleware
59{
60namespace tool
61{
62
70inline void parse_publish_type(const std::string& spec, int& scheme, std::string& type)
71{
72 scheme = 0;
73 type.clear();
74 std::string::size_type slash_pos = spec.find('/');
75 if (slash_pos == std::string::npos)
76 {
77 if (spec == "JSON")
78 {
80 }
81 else if (spec.find("protobuf.") != std::string::npos)
82 {
84 type = spec;
85 }
86 }
87 else
88 {
90 type = spec.substr(slash_pos + 1);
91 }
92}
93
102template <typename InterprocessType, typename PublishConfig>
103void publish_tool_impl(InterprocessType& interprocess, const PublishConfig& cfg,
104 const std::string& tool_name)
105{
106 using goby::glog;
107 std::string type;
108 int scheme{0};
109 parse_publish_type(cfg.type(), scheme, type);
110
112 switch (scheme)
113 {
116 {
117 // use TextFormat
118 auto pb_msg = dccl::DynamicProtobufManager::new_protobuf_message<
119 std::shared_ptr<google::protobuf::Message>>(type);
120 google::protobuf::TextFormat::Parser parser;
121 goby::util::FlexOStreamErrorCollector error_collector(cfg.value());
122 parser.RecordErrorsTo(&error_collector);
123 parser.AllowPartialMessage(false);
124 parser.ParseFromString(cfg.value(), pb_msg.get());
125
127 interprocess.template publish_dynamic<google::protobuf::Message,
129 pb_msg, group);
131 interprocess.template publish_dynamic<
133 pb_msg, group);
134 break;
135 }
136
138 {
139 auto j = nlohmann::json::parse(cfg.value());
140 if (type.empty() || type == "nlohmann::json")
141 {
142 interprocess.template publish_dynamic<nlohmann::json>(j, group);
143 }
144 else
145 {
146 // allow for specialized types, e.g. goby_json_type = "NavigationReport";
147 std::vector<char> bytes = goby::middleware::SerializerParserHelper<
148 nlohmann::json, goby::middleware::MarshallingScheme::JSON>::serialize(j);
149
150 interprocess.publish_serialized(type, goby::middleware::MarshallingScheme::JSON,
151 bytes, group);
152 }
153
154 break;
155 }
156
157 default:
158 glog.is_die() && glog << "Scheme " << scheme << " is not implemented for '" << tool_name
159 << "'" << std::endl;
160 }
161}
162
173template <typename InterprocessType, typename SubscribeConfig>
174void subscribe_tool_impl(InterprocessType& interprocess, const SubscribeConfig& cfg,
175 std::map<int, std::unique_ptr<goby::middleware::log::LogPlugin>>& plugins,
176 const std::string& internal_group_regex = "")
177{
179
180 if (cfg.has_scheme())
181 {
183 schemes = {scheme};
184 }
185
187 std::make_unique<goby::middleware::log::ProtobufPlugin>();
189 std::make_unique<goby::middleware::log::DCCLPlugin>();
191 std::make_unique<goby::middleware::log::JSONPlugin>();
192
193 interprocess.subscribe_regex(
194 [&cfg, &plugins, internal_group_regex](const std::vector<unsigned char>& bytes, int scheme,
195 const std::string& type,
197 {
198 if (!internal_group_regex.empty())
199 {
200 std::regex exclude_pattern(internal_group_regex);
201 if (std::regex_match(std::string(group), exclude_pattern) &&
202 !cfg.include_internal_groups())
203 return;
204 }
205
206 goby::middleware::log::LogEntry log_entry(bytes, scheme, type, group);
207 std::string debug_text;
208
209 auto plugin = plugins.find(log_entry.scheme());
210 if (plugin == plugins.end())
211 {
212 debug_text = std::string("Message of " + std::to_string(bytes.size()) + " bytes");
213 }
214 else
215 {
216 try
217 {
218 debug_text = plugin->second->debug_text_message(log_entry);
219 }
221 {
222 debug_text = "Unable to parse message of " +
223 std::to_string(log_entry.data().size()) +
224 " bytes. Reason: " + e.what();
225 }
226 }
227
228 // use similar format to goby_log_tool DEBUG_TEXT
229 std::cout << scheme << " | " << group << " | " << type << " | "
230 << goby::time::convert<boost::posix_time::ptime>(log_entry.timestamp())
231 << " | " << debug_text << std::endl;
232 },
233 schemes, cfg.type_regex(), cfg.group_regex());
234}
235
241template <typename ImplementationTag, typename PublishConfig>
243 : public middleware::SingleThreadApplicationFor<PublishConfig, ImplementationTag>,
245{
248
249 public:
251 : Base(10.0 * boost::units::si::hertz),
252 middleware::ToolSharedLibraryLoader(this->app_cfg().load_shared_library()),
253 publish_time_(std::chrono::steady_clock::now() +
254 std::chrono::duration_cast<std::chrono::steady_clock::duration>(
255 std::chrono::duration<double>(this->cfg().settle_seconds())))
256 {
257 _publish_once_settled();
258 }
259 ~PublishToolApplication() override = default;
260
261 private:
262 void loop() override
263 {
264 if (!published_)
265 _publish_once_settled();
266 else if (std::chrono::steady_clock::now() >= quit_time_)
267 this->quit(0);
268 }
269
270 // a transport that routes only to the subscribers it has already discovered needs the settle
271 // time before the publish, and every transport needs a moment after it for the publish to go
272 // through
273 void _publish_once_settled()
274 {
275 if (std::chrono::steady_clock::now() < publish_time_)
276 return;
277
278 publish_tool_impl(this->interprocess(), this->cfg(),
279 std::string("goby ") + Traits::name + " publish");
280 published_ = true;
281 quit_time_ = std::chrono::steady_clock::now() + std::chrono::seconds(1);
282 }
283
284 const std::chrono::steady_clock::time_point publish_time_;
285 std::chrono::steady_clock::time_point quit_time_;
286 bool published_{false};
287};
288
294template <typename ImplementationTag, typename SubscribeConfig>
296 : public middleware::SingleThreadApplicationFor<SubscribeConfig, ImplementationTag>,
298{
300
301 public:
303 : middleware::ToolSharedLibraryLoader(this->app_cfg().load_shared_library())
304 {
305 subscribe_tool_impl(this->interprocess(), this->cfg(), plugins_,
306 std::string("goby::") + Traits::name + "::_internal.*");
307 }
308 ~SubscribeToolApplication() override = default;
309
310 private:
311 std::map<int, std::unique_ptr<goby::middleware::log::LogPlugin>> plugins_;
312};
313
314} // namespace tool
315} // namespace middleware
316} // namespace goby
317
318#endif
void quit(int return_value=0)
Requests a clean exit.
Definition interface.h:120
const Config & app_cfg()
Accesses configuration object passed at launch.
Definition interface.h:127
Implementation of Group for dynamic (run-time) instantiations. Use Group directly for static (compile...
Definition group.h:120
Class for grouping publications in the Goby middleware. Analogous to "topics" in ROS,...
Definition group.h:60
Implements an Application for a two layer middleware setup ([ intervehicle [ interprocess ] ]) based ...
Application implementing "goby <impl> publish" for a given interprocess implementation.
Application implementing "goby <impl> subscribe" for a given interprocess implementation.
goby::util::logger::GroupSetter group(std::string n)
void subscribe_tool_impl(InterprocessType &interprocess, const SubscribeConfig &cfg, std::map< int, std::unique_ptr< goby::middleware::log::LogPlugin > > &plugins, const std::string &internal_group_regex="")
Set up subscriptions for the interprocess subscribe tool.
void parse_publish_type(const std::string &spec, int &scheme, std::string &type)
Split a publish type specification into marshalling scheme and type name.
void publish_tool_impl(InterprocessType &interprocess, const PublishConfig &cfg, const std::string &tool_name)
Publish a single message on the interprocess layer using the provided publish config.
constexpr int scheme()
Placeholder to provide an interface for the scheme() function family.
Definition cstr.h:65
The global namespace for the Goby project.
util::FlexOstream glog
Access the Goby logger through this object.
STL namespace.
static int from_string(const std::string &s)
Convert from a string to a marshalling scheme id.
Definition interface.h:77
Class for parsing and serializing a given marshalling scheme. Must be specialized for a particular sc...
Definition interface.h:98
Maps an ImplementationTag to the portal that implements it, so that generic code can be written again...