Goby3 3.7.0
2026.11.12
Loading...
Searching...
No Matches
intervehicle.h
Go to the documentation of this file.
1// Copyright 2016-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_TRANSPORT_INTERVEHICLE_H
25#define GOBY_MIDDLEWARE_TRANSPORT_INTERVEHICLE_H
26
27#include <atomic>
28#include <functional>
29#include <map>
30#include <set>
31#include <sys/types.h>
32#include <thread>
33#include <type_traits>
34#include <unistd.h>
35
36#include <google/protobuf/io/zero_copy_stream_impl.h>
37
39
41#include "goby/middleware/transport/interthread.h" // used for InterVehiclePortal implementation
45#include "goby/time/convert.h"
47
48namespace goby
49{
50namespace middleware
51{
53{
54 public:
55 InvalidSubscription(const std::string& e) : Exception(e) {}
56};
57
59{
60 public:
61 InvalidPublication(const std::string& e) : Exception(e) {}
62};
63
65{
66 public:
67 InvalidUnsubscription(const std::string& e) : Exception(e) {}
68};
69
74template <typename Derived, typename InnerTransporter>
76 : public StaticTransporterInterface<InterVehicleTransporterBase<Derived, InnerTransporter>,
77 InnerTransporter>,
78 public Poller<InterVehicleTransporterBase<Derived, InnerTransporter>>
79{
80 using InterfaceType =
82 InnerTransporter>;
83
85
86 public:
88 {
91 };
92
95 {
96 // handle request from Portal to omit or include metadata on future publications for a given data type
97 this->inner()
100 [this](const protobuf::SerializerMetadataRequest& request)
101 {
102 glog.is_debug3() && glog << "Received DCCL metadata request: "
103 << request.ShortDebugString() << std::endl;
104
105 switch (request.request())
106 {
108 // resend right away if we had stopped (e.g. the portal restarted)
109 if (omit_publish_metadata_.erase(request.key().type()))
110 last_publish_metadata_time_.erase(request.key().type());
111 break;
113 omit_publish_metadata_.insert(request.key().type());
114 break;
115 }
116 });
117 }
119
120 virtual ~InterVehicleTransporterBase() = default;
121
123 template <typename Data> static constexpr int scheme()
124 {
125 static_assert(goby::middleware::scheme<typename detail::primitive_type<Data>::type>() ==
127 "Can only use DCCL messages with InterVehicleTransporters");
129 }
130
134 template <const Group& group> void check_validity()
135 {
136 static_assert(group.numeric() != Group::invalid_numeric_group,
137 "goby::middleware::Group must have non-zero numeric "
138 "value to publish on the InterVehicle layer");
139 }
140
148 template <typename Data, int scheme = goby::middleware::scheme<Data>()>
149 void publish_dynamic(const Data& data, const Group& group = Group(),
150 const Publisher<Data>& publisher = Publisher<Data>())
151 {
152 static_assert(scheme == MarshallingScheme::DCCL,
153 "Can only use DCCL messages with InterVehicleTransporters");
154
155 Data data_with_group = data;
156 publisher.set_group(data_with_group, group);
157
158 static_cast<Derived*>(this)->template _publish<Data>(data_with_group, group, publisher);
159 // publish to interprocess as both DCCL and Protobuf
160 this->inner().template publish_dynamic<Data, MarshallingScheme::DCCL>(data_with_group,
161 group, publisher);
162 this->inner().template publish_dynamic<Data, MarshallingScheme::PROTOBUF>(data_with_group,
163 group, publisher);
164 }
165
173 template <typename Data, int scheme = goby::middleware::scheme<Data>()>
174 void publish_dynamic(std::shared_ptr<const Data> data, const Group& group = Group(),
175 const Publisher<Data>& publisher = Publisher<Data>())
176 {
177 static_assert(scheme == MarshallingScheme::DCCL,
178 "Can only use DCCL messages with InterVehicleTransporters");
179 if (data)
180 {
181 // copy this way as it allows us to copy Data == google::protobuf::Message abstract base class
182 std::shared_ptr<Data> data_with_group(data->New());
183 data_with_group->CopyFrom(*data);
184
185 publisher.set_group(*data_with_group, group);
186
187 static_cast<Derived*>(this)->template _publish<Data>(*data_with_group, group,
188 publisher);
189
190 // publish to interprocess as both DCCL and Protobuf
191 this->inner().template publish_dynamic<Data, MarshallingScheme::DCCL>(data_with_group,
192 group, publisher);
193 this->inner().template publish_dynamic<Data, MarshallingScheme::PROTOBUF>(
194 data_with_group, group, publisher);
195 }
196 }
197
205 template <typename Data, int scheme = goby::middleware::scheme<Data>()>
206 void publish_dynamic(std::shared_ptr<Data> data, const Group& group = Group(),
207 const Publisher<Data>& publisher = Publisher<Data>())
208 {
209 publish_dynamic<Data, scheme>(std::shared_ptr<const Data>(data), group, publisher);
210 }
211
220 template <typename Data, int scheme = goby::middleware::scheme<Data>(),
221 Necessity necessity = Necessity::OPTIONAL>
222 void subscribe_dynamic(std::function<void(const Data&)> f, const Group& group = Group(),
223 const Subscriber<Data>& subscriber = Subscriber<Data>())
224 {
225 static_assert(scheme == MarshallingScheme::DCCL,
226 "Can only use DCCL messages with InterVehicleTransporters");
227 auto pointer_ref_lambda = [=](std::shared_ptr<const Data> d) { f(*d); };
228 static_cast<Derived*>(this)->template _subscribe<Data>(
229 pointer_ref_lambda, group, subscriber, SubscriptionAction::SUBSCRIBE);
230 }
231
240 template <typename Data, int scheme = goby::middleware::scheme<Data>(),
241 Necessity necessity = Necessity::OPTIONAL>
242 void subscribe_dynamic(std::function<void(std::shared_ptr<const Data>)> f,
243 const Group& group = Group(),
244 const Subscriber<Data>& subscriber = Subscriber<Data>())
245 {
246 static_assert(scheme == MarshallingScheme::DCCL,
247 "Can only use DCCL messages with InterVehicleTransporters");
248 static_cast<Derived*>(this)->template _subscribe<Data>(f, group, subscriber,
250 }
251
258 template <typename Data, int scheme = goby::middleware::scheme<Data>()>
260 const Subscriber<Data>& subscriber = Subscriber<Data>())
261 {
262 static_assert(scheme == MarshallingScheme::DCCL,
263 "Can only use DCCL messages with InterVehicleTransporters");
264 static_cast<Derived*>(this)->template _subscribe<Data>(
265 std::function<void(std::shared_ptr<const Data>)>(), group, subscriber,
267 }
268
275 void subscribe_dynamic(std::function<void(std::shared_ptr<const google::protobuf::Message>)> f,
276 const google::protobuf::Descriptor* desc, const Group& group,
277 const Subscriber<google::protobuf::Message>& subscriber =
279 {
280 static_cast<Derived*>(this)->template _subscribe<google::protobuf::Message>(
281 f, group, subscriber, SubscriptionAction::SUBSCRIBE, desc);
282 }
283
289 void unsubscribe_dynamic(const google::protobuf::Descriptor* desc, const Group& group,
290 const Subscriber<google::protobuf::Message>& subscriber =
292 {
293 static_cast<Derived*>(this)->template _subscribe<google::protobuf::Message>(
294 std::function<void(std::shared_ptr<const google::protobuf::Message>)>(), group,
295 subscriber, SubscriptionAction::UNSUBSCRIBE, desc);
296 }
297
298 protected:
299 template <typename Data>
300 std::shared_ptr<goby::middleware::protobuf::SerializerTransporterMessage>
301 _set_up_publish(const Data& d, const Group& group, const Publisher<Data>& publisher)
302 {
303 if (group.numeric() != Group::broadcast_group && !publisher.has_set_group_func() &&
304 publisher.group_in_message())
305 {
306 std::stringstream ss;
307 ss << "Error: Publisher must have set_group_func in order to publish to a "
308 "non-broadcast Group ("
309 << group
310 << "). The set_group_func modifies the contents of the outgoing message to store "
311 "the group information. If the message doesn't store the group, set "
312 "group_in_message to false in the Publisher's Options instead.";
313 throw(InvalidPublication(ss.str()));
314 }
315
316 auto data = intervehicle::serialize_publication(d, group, publisher);
317
318 if (publisher.cfg().intervehicle().buffer().ack_required())
319 {
320 auto ack_handler = std::make_shared<
322 publisher.acked_func(), d);
323
324 auto expire_handler =
325 std::make_shared<PublisherCallback<Data, MarshallingScheme::DCCL,
327 publisher.expired_func(), d);
328
330 data, ack_handler, expire_handler);
331 }
332
333 const auto& type = data->key().type();
334 if (!omit_publish_metadata_.count(type))
335 {
336 auto now = goby::time::SteadyClock::now();
337 auto interval = goby::time::convert_duration<goby::time::SteadyClock::duration>(
339 auto last_it = last_publish_metadata_time_.find(type);
340 if (last_it == last_publish_metadata_time_.end() || now >= last_it->second + interval)
341 {
342 _set_protobuf_metadata<Data>(data->mutable_key()->mutable_metadata(), d);
343 last_publish_metadata_time_[type] = now;
344 }
345 }
346
348 goby::glog << "Set up publishing for: " << data->ShortDebugString() << std::endl;
349
350 return data;
351 }
352
353 template <typename Data>
354 std::shared_ptr<intervehicle::protobuf::Subscription>
355 _set_up_subscribe(std::function<void(std::shared_ptr<const Data> d)> func, const Group& group,
356 const Subscriber<Data>& subscriber, SubscriptionAction action,
357 const google::protobuf::Descriptor* desc = nullptr)
358 {
359 auto dccl_id = _dccl_id<Data>(desc);
360
361 switch (action)
362 {
364 {
365 if (group.numeric() != Group::broadcast_group && !subscriber.has_group_func() &&
366 subscriber.group_in_message())
367 {
368 std::stringstream ss;
369 ss << "Error: Subscriber must have group_func in order to subscribe to "
370 "non-broadcast Group ("
371 << group
372 << "). The group_func returns the appropriate Group based on the contents "
373 "of the incoming message. If the message doesn't store the group, set "
374 "group_in_message to false in the Subscriber's Options instead.";
375 throw(InvalidSubscription(ss.str()));
376 }
377
378 if (subscriber.cfg().intervehicle().broadcast() &&
379 subscriber.cfg().intervehicle().buffer().ack_required())
380 {
381 std::stringstream ss;
382 ss << "Error: Broadcast subscriptions cannot have ack_required: true";
383 throw(InvalidSubscription(ss.str()));
384 }
385
386 if (subscriber.cfg().intervehicle().republish_on_receive())
387 func = _republishing(func, group);
388
389 using SubscriptionType =
391 std::shared_ptr<SubscriptionType> subscription;
392 if constexpr (std::is_same_v<Data, google::protobuf::Message>)
393 subscription = std::make_shared<SubscriptionType>(func, desc->full_name(),
394 group, subscriber);
395 else
396 subscription = std::make_shared<SubscriptionType>(func, group, subscriber);
397
398 this->subscriptions_[dccl_id][group] = subscription;
399 }
400 break;
402 {
403 auto sub_it = this->subscriptions_[dccl_id].find(group);
404 if (sub_it != this->subscriptions_[dccl_id].end())
405 {
406 this->subscriptions_[dccl_id].erase(sub_it);
407 }
408 else
409 {
410 std::stringstream ss;
411 ss << "Cannot unsubscribe to DCCL id: " << dccl_id
412 << " and group: " << std::string(group) << " as no subscription was found.";
413 throw(InvalidUnsubscription(ss.str()));
414 }
415 }
416 break;
417 }
418
419 auto dccl_subscription =
420 this->template _serialize_subscription<Data>(group, subscriber, action, desc);
422 // insert pending subscription
423 auto subscription_publication = intervehicle::serialize_publication(
426
427 // overwrite timestamps to ensure mapping with driver threads
428 auto subscribe_time = dccl_subscription->time_with_units();
429 subscription_publication->mutable_key()->set_serialize_time_with_units(subscribe_time);
430
431 auto ack_handler = std::make_shared<PublisherCallback<Subscription, MarshallingScheme::DCCL,
433 subscriber.subscribed_func());
434
435 auto expire_handler =
436 std::make_shared<PublisherCallback<Subscription, MarshallingScheme::DCCL,
438 subscriber.subscribe_expired_func());
439
440 goby::glog.is_debug1() && goby::glog << "Inserting subscription ack handler for "
441 << subscription_publication->ShortDebugString()
442 << std::endl;
443
444 this->pending_ack_.insert(std::make_pair(*subscription_publication,
445 std::make_tuple(ack_handler, expire_handler)));
446
447 return dccl_subscription;
448 }
449
450 template <int tuple_index, typename AckorExpirePair>
451 void _handle_ack_or_expire(const AckorExpirePair& ack_or_expire_pair)
452 {
453 auto original = ack_or_expire_pair.serializer();
454 const auto& ack_or_expire_msg = ack_or_expire_pair.data();
455 bool is_subscription = original.key().marshalling_scheme() == MarshallingScheme::DCCL &&
456 original.key().type() ==
458
459 if (is_subscription)
460 {
461 // rewrite data to remove src()
462 auto bytes_begin = original.data().begin(), bytes_end = original.data().end();
463 decltype(bytes_begin) actual_end;
464
467 auto subscription = Helper::parse(bytes_begin, bytes_end, actual_end);
468 subscription->mutable_header()->set_src(0);
469
470 std::vector<char> bytes(Helper::serialize(*subscription));
471 std::string* sbytes = new std::string(bytes.begin(), bytes.end());
472 original.set_allocated_data(sbytes);
473 }
474
475 auto it = pending_ack_.find(original);
476 if (it != pending_ack_.end())
477 {
478 goby::glog.is_debug3() && goby::glog << ack_or_expire_msg.GetDescriptor()->name()
479 << " for: " << original.ShortDebugString() << ", "
480 << ack_or_expire_msg.ShortDebugString()
481 << std::endl;
482
483 std::get<tuple_index>(it->second)
484 ->post(original.data().begin(), original.data().end(), ack_or_expire_msg);
485 }
486 else
487 {
488 goby::glog.is_debug3() && goby::glog << "No pending Ack/Expire for "
489 << (is_subscription ? "subscription: " : "data: ")
490 << original.ShortDebugString() << std::endl;
491 }
492 }
493
495 {
496 goby::glog.is_debug3() && goby::glog << "Received DCCLForwarded data: "
497 << packets.ShortDebugString() << std::endl;
498
499 for (const auto& packet : packets.frame())
500 {
501 for (auto p : this->subscriptions_[packet.dccl_id()])
502 p.second->post(packet.data().begin(), packet.data().end(), packets.header());
503 }
504 }
505
506 template <typename Data>
507 std::shared_ptr<intervehicle::protobuf::Subscription>
509 SubscriptionAction action,
510 const google::protobuf::Descriptor* desc = nullptr)
511 {
512 auto dccl_id = _dccl_id<Data>(desc);
513 auto dccl_subscription = std::make_shared<intervehicle::protobuf::Subscription>();
514 dccl_subscription->mutable_header()->set_src(0);
515
516 for (auto id : subscriber.cfg().intervehicle().publisher_id())
517 dccl_subscription->mutable_header()->add_dest(id);
518
519 dccl_subscription->set_api_version(GOBY_INTERVEHICLE_API_VERSION);
520 dccl_subscription->set_dccl_id(dccl_id);
521 dccl_subscription->set_group(group.numeric());
522 dccl_subscription->set_time_with_units(
523 goby::time::SystemClock::now<goby::time::MicroTime>());
524 dccl_subscription->set_action((action == SubscriptionAction::SUBSCRIBE)
527
528 _set_protobuf_metadata<Data>(dccl_subscription->mutable_metadata(), desc);
529 *dccl_subscription->mutable_intervehicle() = subscriber.cfg().intervehicle();
530 return dccl_subscription;
531 }
532
534 int dccl_id, std::shared_ptr<goby::middleware::protobuf::SerializerTransporterMessage> data,
537 expire_handler)
538 {
539 goby::glog.is_debug3() && goby::glog << "Inserting ack handler for "
540 << data->ShortDebugString() << std::endl;
541
542 this->pending_ack_.insert(
543 std::make_pair(*data, std::make_tuple(ack_handler, expire_handler)));
544 }
545
546 protected:
547 // maps DCCL ID to map of Group->subscription
548 // only one subscription allowed per IntervehicleForwarder/Portal (new subscription overwrites old one)
549 std::unordered_map<
550 int, std::unordered_map<std::string, std::shared_ptr<const SerializationHandlerBase<
553
554 private:
555 friend PollerType;
556 int _poll(std::unique_ptr<std::unique_lock<std::mutex>>& lock)
557 {
558 _expire_pending_ack();
559
560 return static_cast<Derived*>(this)->_poll(lock);
561 }
562
563 // received messages go to func and then to the inner layer, as an outgoing publication in the
564 // same group would be (DCCL and PROTOBUF). The group's string form ("name;7", or "7" for a
565 // numeric-only group) is the identifier that publication uses, and outlives a DynamicGroup.
566 template <typename Data>
567 std::function<void(std::shared_ptr<const Data>)>
568 _republishing(std::function<void(std::shared_ptr<const Data>)> func, const Group& group)
569 {
570 return [this, func, inner_group = std::string(group)](std::shared_ptr<const Data> d)
571 {
572 if (func)
573 func(d);
574 DynamicGroup g(inner_group);
575 this->inner().template publish_dynamic<Data, MarshallingScheme::DCCL>(d, g);
576 this->inner().template publish_dynamic<Data, MarshallingScheme::PROTOBUF>(d, g);
577 };
578 }
579
580 // desc is only used (and required) when Data is google::protobuf::Message
581 template <typename Data> static int _dccl_id(const google::protobuf::Descriptor* desc)
582 {
583 if constexpr (std::is_same_v<Data, google::protobuf::Message>)
584 return SerializerParserHelper<google::protobuf::Message, MarshallingScheme::DCCL>::id(
585 desc);
586 else
587 return SerializerParserHelper<Data, MarshallingScheme::DCCL>::id();
588 }
589
590 template <typename Data>
591 void _set_protobuf_metadata(protobuf::SerializerProtobufMetadata* meta,
592 const google::protobuf::Descriptor* desc)
593 {
594 if constexpr (std::is_same_v<Data, google::protobuf::Message>)
595 {
596 meta->set_protobuf_name(std::string(desc->full_name()));
597 _insert_file_desc_with_dependencies(desc->file(), meta);
598 }
599 else
600 {
601 meta->set_protobuf_name(
603 _insert_file_desc_with_dependencies(Data::descriptor()->file(), meta);
604 }
605 }
606
607 template <typename Data>
608 void _set_protobuf_metadata(protobuf::SerializerProtobufMetadata* meta, const Data& d)
609 {
610 meta->set_protobuf_name(
612 _insert_file_desc_with_dependencies(d.GetDescriptor()->file(), meta);
613 }
614
615 // used to populated InterVehicleSubscription file_descriptor fields
616 void _insert_file_desc_with_dependencies(const google::protobuf::FileDescriptor* file_desc,
617 protobuf::SerializerProtobufMetadata* meta)
618 {
619 std::set<std::string> inserted;
620 _insert_file_desc_with_dependencies(file_desc, meta, inserted);
621 }
622
623 void _insert_file_desc_with_dependencies(const google::protobuf::FileDescriptor* file_desc,
624 protobuf::SerializerProtobufMetadata* meta,
625 std::set<std::string>& inserted)
626 {
627 if (!inserted.insert(std::string(file_desc->name())).second)
628 return;
629
630 for (int i = 0, n = file_desc->dependency_count(); i < n; ++i)
631 _insert_file_desc_with_dependencies(file_desc->dependency(i), meta, inserted);
632
633 google::protobuf::FileDescriptorProto* file_desc_proto = meta->add_file_descriptor();
634 file_desc->CopyTo(file_desc_proto);
635 }
636
637 // expire any pending_ack entries that are no longer relevant
638 void _expire_pending_ack()
639 {
640 auto now = goby::time::SystemClock::now<goby::time::MicroTime>();
641 for (auto it = pending_ack_.begin(), end = pending_ack_.end(); it != end;)
642 {
644 ->FindFieldByName("ttl")
645 ->options()
646 .GetExtension(dccl::field)
647 .max() *
649
650 decltype(now) serialize_time(it->first.key().serialize_time_with_units());
651 decltype(now) expire_time(serialize_time + max_ttl);
652
653 // time to let any expire messages from the drivers propagate through the interprocess layer before we remove this
654 const decltype(now) interprocess_wait(1.0 * boost::units::si::seconds);
655
656 // loop through pending ack, and clear any at the front that can be removed
657
658 if (now > expire_time + interprocess_wait)
659 {
660 goby::glog.is_debug3() && goby::glog << "Erasing pending ack for "
661 << it->first.ShortDebugString() << std::endl;
662 it = pending_ack_.erase(it);
663 }
664 else
665 {
666 // pending_ack_ is ordered by serialize time, so we can bail now
667 break;
668 }
669 }
670 }
671
672 private:
673 // maps data with ack_requested onto callbacks for when the data are acknowledged or expire
674 // ordered by serialize time
675 std::map<
676 protobuf::SerializerTransporterMessage,
677 std::tuple<std::shared_ptr<SerializationHandlerBase<intervehicle::protobuf::AckData>>,
678 std::shared_ptr<SerializationHandlerBase<intervehicle::protobuf::ExpireData>>>>
679 pending_ack_;
680
681 // map of Protobuf names where we can omit metadata on publication
682 std::set<std::string> omit_publish_metadata_;
683 std::map<std::string, goby::time::SteadyClock::time_point> last_publish_metadata_time_;
684};
685
690template <typename InnerTransporter>
692 : public InterVehicleTransporterBase<InterVehicleForwarder<InnerTransporter>, InnerTransporter>
693{
694 public:
695 using implementation_tag = typename InnerTransporter::implementation_tag;
696
697 using Base =
699
703 InterVehicleForwarder(InnerTransporter& inner) : Base(inner)
704 {
705 this->inner()
709 { this->_receive(msg); });
710
711 using ack_pair_type = intervehicle::protobuf::AckMessagePair;
712 this->inner().template subscribe<intervehicle::groups::modem_ack_in, ack_pair_type>(
713 [this](const ack_pair_type& ack_pair)
714 { this->template _handle_ack_or_expire<0>(ack_pair); });
715
716 using expire_pair_type = intervehicle::protobuf::ExpireMessagePair;
717 this->inner().template subscribe<intervehicle::groups::modem_expire_in, expire_pair_type>(
718 [this](const expire_pair_type& expire_pair)
719 { this->template _handle_ack_or_expire<1>(expire_pair); });
720 }
721
722 virtual ~InterVehicleForwarder() = default;
723
724 friend Base;
725
726 private:
727 template <typename Data>
728 void _publish(const Data& d, const Group& group, const Publisher<Data>& publisher)
729 {
730 this->inner().template publish<intervehicle::groups::modem_data_out>(
731 this->_set_up_publish(d, group, publisher));
732 }
733
734 template <typename Data>
735 void _subscribe(std::function<void(std::shared_ptr<const Data> d)> func, const Group& group,
736 const Subscriber<Data>& subscriber, typename Base::SubscriptionAction action,
737 const google::protobuf::Descriptor* desc = nullptr)
738 {
739 try
740 {
741 this->inner()
745 this->_set_up_subscribe(func, group, subscriber, action, desc));
746 }
747 catch (const InvalidUnsubscription& e)
748 {
749 goby::glog.is_warn() && goby::glog << e.what() << std::endl;
750 }
751 }
752
753 int _poll(std::unique_ptr<std::unique_lock<std::mutex>>& lock) { return 0; }
754};
755
759template <typename InnerTransporter>
761 : public InterVehicleTransporterBase<InterVehiclePortal<InnerTransporter>, InnerTransporter>
762{
763 // Derive the ImplementationTag from InnerTransporter so that the modem driver thread
764 // uses the same InterProcessForwarder prefix as the portal's inner transporter.
765 using implementation_tag = typename InnerTransporter::implementation_tag;
766 using modem_id_type = typename goby::middleware::intervehicle::ModemDriverThread<
767 implementation_tag>::modem_id_type;
768
769 public:
770 using Base =
772
776 InterVehiclePortal(const intervehicle::protobuf::PortalConfig& cfg) : cfg_(cfg) { _init(); }
777
783 : Base(inner), cfg_(cfg)
784 {
785 _init();
786 }
787
789 {
790 // stop every link before joining any, so their drivers shut down in parallel
791 for (auto& modem_driver_data : modem_drivers_)
792 modem_driver_data->driver_thread_alive = false;
793 for (auto& modem_driver_data : modem_drivers_)
794 {
795 if (modem_driver_data->underlying_thread)
796 modem_driver_data->underlying_thread->join();
797 }
798 }
799
800 friend Base;
801
802 private:
803 template <typename Data>
804 void _publish(const Data& d, const Group& group, const Publisher<Data>& publisher)
805 {
806 this->innermost().template publish<intervehicle::groups::modem_data_out>(
807 this->_set_up_publish(d, group, publisher));
808 }
809
810 template <typename Data>
811 void _subscribe(std::function<void(std::shared_ptr<const Data> d)> func, const Group& group,
812 const Subscriber<Data>& subscriber, typename Base::SubscriptionAction action,
813 const google::protobuf::Descriptor* desc = nullptr)
814 {
815 try
816 {
817 auto dccl_subscription = this->_set_up_subscribe(func, group, subscriber, action, desc);
818
819 this->innermost().template publish<intervehicle::groups::modem_subscription_forward_tx>(
820 dccl_subscription);
821 }
822 catch (const InvalidUnsubscription& e)
823 {
824 goby::glog.is_warn() && goby::glog << e.what() << std::endl;
825 }
826 }
827
828 int _poll(std::unique_ptr<std::unique_lock<std::mutex>>& lock)
829 {
830 int items = 0;
832 while (!received_.empty())
833 {
834 this->_receive(received_.front());
835 received_.pop_front();
836 ++items;
837 if (lock)
838 lock.reset();
839 }
840 return items;
841 }
842
843 void _init()
844 {
845 // set up reception of forwarded (via acoustic) subscriptions,
846 // then re-publish to driver threads
847 {
848 using intervehicle::protobuf::Subscription;
849 auto subscribe_lambda = [this](std::shared_ptr<const Subscription> d)
850 {
851 this->innermost()
853 intervehicle::protobuf::Subscription,
855 };
856 auto subscription = std::make_shared<
857 IntervehicleSerializationSubscription<Subscription, MarshallingScheme::DCCL>>(
858 subscribe_lambda);
859
860 auto dccl_id = SerializerParserHelper<Subscription, MarshallingScheme::DCCL>::id();
861 this->subscriptions_[dccl_id].insert(
862 std::make_pair(subscription->subscribed_group(), subscription));
863 }
864
865 this->innermost().template subscribe<intervehicle::groups::modem_data_in>(
866 [this](const intervehicle::protobuf::DCCLForwardedData& msg)
867 { received_.push_back(msg); });
868
869 // a message requiring ack can be disposed by either [1] ack, [2] expire (TTL exceeded), [3] having no subscribers, [4] queue size exceeded.
870 // post the correct callback (ack for [1] and expire for [2-4])
871 // and remove the pending ack message
872 using ack_pair_type = intervehicle::protobuf::AckMessagePair;
873 this->innermost().template subscribe<intervehicle::groups::modem_ack_in, ack_pair_type>(
874 [this](const ack_pair_type& ack_pair)
875 { this->template _handle_ack_or_expire<0>(ack_pair); });
876
877 using expire_pair_type = intervehicle::protobuf::ExpireMessagePair;
878 this->innermost()
879 .template subscribe<intervehicle::groups::modem_expire_in, expire_pair_type>(
880 [this](const expire_pair_type& expire_pair)
881 { this->template _handle_ack_or_expire<1>(expire_pair); });
882
883 this->innermost().template subscribe<intervehicle::groups::modem_driver_ready, bool>(
884 [this](const bool& ready)
885 {
886 goby::glog.is_debug1() && goby::glog << "Received driver ready" << std::endl;
887 ++drivers_ready_;
888 });
889
890 // set up before drivers ready to ensure we don't miss subscriptions
891 if (cfg_.has_persist_subscriptions())
892 _set_up_persistent_subscriptions();
893
894 for (int i = 0, n = cfg_.link_size(); i < n; ++i)
895 {
896 auto* link = cfg_.mutable_link(i);
897
898 link->mutable_driver()->set_modem_id(link->modem_id());
899 link->mutable_mac()->set_modem_id(link->modem_id());
900
901 modem_drivers_.emplace_back(new ModemDriverData);
902 ModemDriverData& data = *modem_drivers_.back();
903
904 data.underlying_thread.reset(new std::thread(
905 [&data, link]()
906 {
907 try
908 {
909 data.modem_driver_thread.reset(
910 new intervehicle::ModemDriverThread<implementation_tag>(*link));
911 data.modem_driver_thread->run(data.driver_thread_alive);
912 }
913 catch (std::exception& e)
914 {
916 goby::glog << "Modem driver thread had uncaught exception: " << e.what()
917 << std::endl;
918 throw;
919 }
920 }));
921
922 if (goby::glog.buf().is_gui())
923 // allows for visual grouping of each link in the NCurses gui
924 std::this_thread::sleep_for(std::chrono::milliseconds(250));
925 }
926
927 while (drivers_ready_ < modem_drivers_.size())
928 {
929 goby::glog.is_debug1() && goby::glog << "Waiting for drivers to be ready." << std::endl;
930 this->poll();
931 std::this_thread::sleep_for(std::chrono::seconds(1));
932 }
933
934 // write subscriptions after drivers ready to ensure they aren't missed
935 if (former_sub_collection_.subscription_size() > 0)
936 {
938 goby::glog << "Begin loading subscriptions from persistent storage..." << std::endl;
939 for (const auto& sub : former_sub_collection_.subscription())
940 this->innermost()
941 .template publish<intervehicle::groups::modem_subscription_forward_rx,
942 intervehicle::protobuf::Subscription,
943 MarshallingScheme::PROTOBUF>(sub);
944 }
945 }
946
947 void _set_up_persistent_subscriptions()
948 {
949 const auto& dir = cfg_.persist_subscriptions().dir();
950 if (dir.empty())
951 goby::glog.is_die() && goby::glog << "persist_subscriptions.dir cannot be empty"
952 << std::endl;
953
954 std::stringstream file_name;
955 file_name << dir;
956 if (dir.back() != '/')
957 file_name << "/";
958 file_name << "goby_intervehicle_subscriptions_" << cfg_.persist_subscriptions().name()
959 << ".pb.txt";
960 persist_sub_file_name_ = file_name.str();
961 {
962 std::ifstream persist_sub_ifs(persist_sub_file_name_.c_str());
963 try
964 {
965 if (persist_sub_ifs.is_open())
966 {
967 google::protobuf::TextFormat::Parser parser;
968 google::protobuf::io::IstreamInputStream iis(&persist_sub_ifs);
969 parser.Parse(&iis, &former_sub_collection_);
970 }
971 else
972 {
974 goby::glog << "Could not open persistent subscriptions file: "
975 << persist_sub_file_name_
976 << ". Assuming no persistent subscriptions exist" << std::endl;
977 }
978 }
979 catch (const std::exception& e)
980 {
982 goby::glog << "Error reading persistent subscriptions file: " << e.what()
983 << std::endl;
984 }
985 }
986
987 std::ofstream persist_sub_ofs(persist_sub_file_name_.c_str());
988 if (!persist_sub_ofs.is_open())
989 {
990 goby::glog.is_die() &&
991 goby::glog << "Could not open persistent subscriptions file for writing: "
992 << persist_sub_file_name_ << std::endl;
993 }
994 remove(persist_sub_file_name_.c_str());
995
996 this->innermost().template subscribe<intervehicle::groups::subscription_report>(
997 [this](const intervehicle::protobuf::SubscriptionReport& report)
998 {
999 goby::glog.is_debug1() && goby::glog << "Received subscription report: "
1000 << report.ShortDebugString() << std::endl;
1001 sub_reports_[report.link_modem_id()] = report;
1002 std::ofstream persist_sub_ofs(persist_sub_file_name_.c_str());
1003 intervehicle::protobuf::SubscriptionPersistCollection collection;
1004 collection.set_time_with_units(
1005 goby::time::SystemClock::now<goby::time::MicroTime>());
1006 for (auto report_p : sub_reports_)
1007 {
1008 for (const auto& sub : report_p.second.subscription())
1009 *collection.add_subscription() = sub;
1010 }
1011 google::protobuf::TextFormat::Printer printer;
1012 google::protobuf::io::OstreamOutputStream oos(&persist_sub_ofs);
1014 goby::glog << "Collection: " << collection.ShortDebugString() << std::endl;
1015 printer.Print(collection, &oos);
1016 });
1017 }
1018
1019 private:
1020 intervehicle::protobuf::PortalConfig cfg_;
1021
1022 struct ModemDriverData
1023 {
1024 std::unique_ptr<std::thread> underlying_thread;
1025 std::unique_ptr<intervehicle::ModemDriverThread<implementation_tag>> modem_driver_thread;
1026 std::atomic<bool> driver_thread_alive{true};
1027 };
1028 std::vector<std::unique_ptr<ModemDriverData>> modem_drivers_;
1029 unsigned drivers_ready_{0};
1030
1031 std::deque<intervehicle::protobuf::DCCLForwardedData> received_;
1032
1033 intervehicle::protobuf::SubscriptionPersistCollection former_sub_collection_;
1034 std::string persist_sub_file_name_;
1035 std::map<modem_id_type, intervehicle::protobuf::SubscriptionReport> sub_reports_;
1036};
1037} // namespace middleware
1038} // namespace goby
1039
1040#endif
simple exception class for goby applications
Definition exception.h:35
static const ::PROTOBUF_NAMESPACE_ID::Descriptor * descriptor()
Definition buffer.pb.h:110
boost::units::unit< ttl_dimension, boost::units::si::system > ttl_unit
Definition buffer.pb.h:302
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
static constexpr std::uint32_t broadcast_group
Special group number representing the broadcast group (used when no grouping is required for a given ...
Definition group.h:63
static constexpr std::uint32_t invalid_numeric_group
Special group number representing an invalid numeric group (unsuitable for intervehicle and outer lay...
Definition group.h:65
Implements the forwarder concept for the intervehicle layer.
InterVehicleForwarder(InnerTransporter &inner)
Construct a forwarder for the intervehicle layer.
typename InnerTransporter::implementation_tag implementation_tag
Implements a portal for the intervehicle layer based on Goby Acomms.
InterVehiclePortal(InnerTransporter &inner, const intervehicle::protobuf::PortalConfig &cfg)
Instantiate a portal with the given configuration and a reference to an external inner transporter.
InterVehiclePortal(const intervehicle::protobuf::PortalConfig &cfg)
Instantiate a portal with the given configuration (with the portal owning the inner transporter)
Base class for implementing transporters (both portal and forwarder) for the intervehicle layer.
void subscribe_dynamic(std::function< void(std::shared_ptr< const google::protobuf::Message >)> f, const google::protobuf::Descriptor *desc, const Group &group, const Subscriber< google::protobuf::Message > &subscriber=Subscriber< google::protobuf::Message >())
Subscribe to a DCCL type known only at run time, given by its descriptor.
void subscribe_dynamic(std::function< void(std::shared_ptr< const Data >)> f, const Group &group=Group(), const Subscriber< Data > &subscriber=Subscriber< Data >())
Subscribe to a specific run-time defined group and data type (shared pointer variant)....
static constexpr int scheme()
returns the marshalling scheme id for a given data type on this layer. Only MarshallingScheme::DCCL i...
void publish_dynamic(std::shared_ptr< Data > data, const Group &group=Group(), const Publisher< Data > &publisher=Publisher< Data >())
Publish a message using a run-time defined DynamicGroup (shared pointer to mutable data variant)....
void _handle_ack_or_expire(const AckorExpirePair &ack_or_expire_pair)
void publish_dynamic(std::shared_ptr< const Data > data, const Group &group=Group(), const Publisher< Data > &publisher=Publisher< Data >())
Publish a message using a run-time defined DynamicGroup (shared pointer to const data variant)....
InterVehicleTransporterBase(InnerTransporter &inner)
std::shared_ptr< intervehicle::protobuf::Subscription > _set_up_subscribe(std::function< void(std::shared_ptr< const Data > d)> func, const Group &group, const Subscriber< Data > &subscriber, SubscriptionAction action, const google::protobuf::Descriptor *desc=nullptr)
void _receive(const intervehicle::protobuf::DCCLForwardedData &packets)
std::shared_ptr< intervehicle::protobuf::Subscription > _serialize_subscription(const Group &group, const Subscriber< Data > &subscriber, SubscriptionAction action, const google::protobuf::Descriptor *desc=nullptr)
void _insert_pending_ack(int dccl_id, std::shared_ptr< goby::middleware::protobuf::SerializerTransporterMessage > data, std::shared_ptr< SerializationHandlerBase< intervehicle::protobuf::AckData > > ack_handler, std::shared_ptr< SerializationHandlerBase< intervehicle::protobuf::ExpireData > > expire_handler)
void publish_dynamic(const Data &data, const Group &group=Group(), const Publisher< Data > &publisher=Publisher< Data >())
Publish a message using a run-time defined DynamicGroup (const reference variant)....
void unsubscribe_dynamic(const Group &group=Group(), const Subscriber< Data > &subscriber=Subscriber< Data >())
Unsubscribe from a specific run-time defined group and data type. Where possible, prefer the static v...
void check_validity()
Check validity of the Group for interthread use (at compile time)
void subscribe_dynamic(std::function< void(const Data &)> f, const Group &group=Group(), const Subscriber< Data > &subscriber=Subscriber< Data >())
Subscribe to a specific run-time defined group and data type (const reference variant)....
std::unordered_map< int, std::unordered_map< std::string, std::shared_ptr< const SerializationHandlerBase< intervehicle::protobuf::Header > > > > subscriptions_
std::shared_ptr< goby::middleware::protobuf::SerializerTransporterMessage > _set_up_publish(const Data &d, const Group &group, const Publisher< Data > &publisher)
void unsubscribe_dynamic(const google::protobuf::Descriptor *desc, const Group &group, const Subscriber< google::protobuf::Message > &subscriber=Subscriber< google::protobuf::Message >())
Unsubscribe from a DCCL type known only at run time, given by its descriptor.
Represents a subscription to a serialized data type (intervehicle layer).
InvalidPublication(const std::string &e)
InvalidSubscription(const std::string &e)
InvalidUnsubscription(const std::string &e)
int poll(const std::chrono::time_point< Clock, Duration > &timeout=std::chrono::time_point< Clock, Duration >::max())
poll for data. Blocks until a data event occurs or a timeout when a particular time has been reached
Definition interface.h:375
Utility class for allowing the various Goby middleware transporters to poll the underlying transport ...
Definition poller.h:38
Represents a callback for a published data type (e.g. acked_func or expired_func)
Class that holds additional metadata and callback functions related to a publication (and is optional...
Definition publisher.h:40
const goby::middleware::protobuf::TransporterConfig & cfg() const
Returns the metadata configuration.
Definition publisher.h:108
acked_func_type acked_func() const
Returns the acked data callback (or an empty function if none is set)
Definition publisher.h:118
bool has_set_group_func() const
Definition publisher.h:122
bool group_in_message() const
False if the group isn't stored in the message (see Options::group_in_message)
Definition publisher.h:125
expired_func_type expired_func() const
Returns the expired data callback (or an empty function if none is set)
Definition publisher.h:120
Base class for handling posting callbacks for serialized data types (interprocess and outer)
Defines the common interface for publishing and subscribing data using static (constexpr) groups on G...
Definition interface.h:234
void subscribe(std::function< void(const Data &)> f, const Subscriber< Data > &subscriber=Subscriber< Data >())
Subscribe to a specific group and data type (const reference variant)
Definition interface.h:300
void publish(const Data &data, const Publisher< Data > &publisher=Publisher< Data >())
Publish a message (const reference variant)
Definition interface.h:245
Class that holds additional metadata and callback functions related to a subscription (and is optiona...
Definition subscriber.h:37
bool group_in_message() const
False if the group isn't stored in the message (see Options::group_in_message)
Definition subscriber.h:130
subscribed_func_type subscribed_func() const
Definition subscriber.h:123
const goby::middleware::protobuf::TransporterConfig & cfg() const
Definition subscriber.h:111
subscribe_expired_func_type subscribe_expired_func() const
Definition subscriber.h:125
Provides the modem driver thread used by InterVehiclePortal, templated on ImplementationTag so it use...
const ::goby::middleware::intervehicle::protobuf::Header & header() const
const ::goby::middleware::intervehicle::protobuf::DCCLPacket & frame(int index) const
const ::goby::middleware::intervehicle::protobuf::PortalConfig_PersistSubscriptions & persist_subscriptions() const
::goby::middleware::intervehicle::protobuf::PortalConfig_LinkConfig * mutable_link(int index)
static const ::PROTOBUF_NAMESPACE_ID::Descriptor * descriptor()
const ::goby::acomms::protobuf::DynamicBufferConfig & buffer() const
const ::goby::middleware::intervehicle::protobuf::TransporterConfig & intervehicle() const
#define GOBY_INTERVEHICLE_API_VERSION
goby::util::logger::GroupSetter group(std::string n)
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::goby::acomms::protobuf::ModemReport, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::acomms::iridium::protobuf::Report >, 11, false > report
constexpr Group modem_subscription_forward_tx
Definition groups.h:48
constexpr Group modem_subscription_forward_rx
Definition groups.h:50
std::shared_ptr< goby::middleware::protobuf::SerializerTransporterMessage > serialize_publication(const Data &d, const Group &group, const Publisher< Data > &publisher)
Necessity
Used to tag subscriptions based on their necessity (e.g. required for correct functioning,...
Definition interface.h:222
constexpr T e
Definition constants.h:35
The global namespace for the Goby project.
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::PROTOBUF_NAMESPACE_ID::MessageOptions, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::GobyMessageOptions >, 11, false > msg
util::FlexOstream glog
Access the Goby logger through this object.
Class for parsing and serializing a given marshalling scheme. Must be specialized for a particular sc...
Definition interface.h:98
static std::string type_name()
The marshalling scheme specific string name for this type.
Definition interface.h:107
static time_point now() noexcept
Returns the current steady time unless SimulatorSettings::using_sim_time == true in which case a simu...