zmq_monitor.h
Go to the documentation of this file.
1 /*+-------------------------------------------------------------------------+
2  | MultiVehicle simulator (libmvsim) |
3  | |
4  | Copyright (C) 2014-2023 Jose Luis Blanco Claraco |
5  | Copyright (C) 2017 Borys Tymchenko (Odessa Polytechnic University) |
6  | Distributed under 3-clause BSD License |
7  | See COPYING |
8  +-------------------------------------------------------------------------+ */
9 
10 #pragma once
11 
12 #include <mrpt/core/format.h>
13 
14 #include <atomic>
15 #include <iostream>
16 #include <mutex>
17 #include <thread>
18 
19 #if defined(MVSIM_HAS_ZMQ) && defined(MVSIM_HAS_PROTOBUF)
20 #include <zmq.hpp>
21 
22 namespace mvsim
23 {
27 class SocketMonitor : public zmq::monitor_t
28 {
29  public:
30  SocketMonitor() = default;
31  ~SocketMonitor()
32  {
33  zmq::monitor_t::abort();
34  if (runningMonitor_.joinable()) runningMonitor_.join();
35  }
36 
37  void monitor(zmq::socket_t& s)
38  {
39  static std::atomic_int nonce = 1000;
40  const int v = nonce++;
41 
42  const std::string endpoint =
43  mrpt::format("inproc://monitor%i_%p.req", v, s.operator void*());
44 
45  runningMonitor_ = std::thread([&, endpoint]() {
46  try
47  {
48  zmq::monitor_t::monitor(s, endpoint, ZMQ_EVENT_ALL);
49  }
50  catch (const std::exception& e)
51  {
52  if (zmq_errno() == ETERM)
53  {
54  // Not a real error, just we are shutting down.
55  }
56  else
57  {
58  std::cerr << "[MySocketMonitor] Error: " << e.what()
59  << " (zmq_errno=" << zmq_errno() << ")\n";
60  }
61  }
62  });
63  }
64 
65  void setConnected(bool v)
66  {
67  std::lock_guard<std::mutex> lck(connectedMtx_);
68  connected_ = v;
69  }
70 
71  void on_event_disconnected(
72  [[maybe_unused]] const zmq_event_t& event_,
73  [[maybe_unused]] const char* addr_) override
74  {
75  setConnected(false);
76  }
77 
78  void on_event_connected(
79  [[maybe_unused]] const zmq_event_t& event_,
80  [[maybe_unused]] const char* addr_) override
81  {
82  setConnected(true);
83  }
84 
85  bool connected() const
86  {
87  std::lock_guard<std::mutex> lck(connectedMtx_);
88  return connected_;
89  }
90 
91  private:
92  bool connected_ = false;
93  mutable std::mutex connectedMtx_;
94 
95  std::thread runningMonitor_;
96 };
97 
100 } // namespace mvsim
101 
102 #endif


mvsim
Author(s):
autogenerated on Tue Jul 4 2023 03:08:22