zmq_monitor.h
Go to the documentation of this file.
1 /*+-------------------------------------------------------------------------+
2  | MultiVehicle simulator (libmvsim) |
3  | |
4  | Copyright (C) 2014-2020 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  std::cerr << "[MySocketMonitor] Error: " << e.what() << "\n";
53  }
54  });
55  }
56 
57  void setConnected(bool v)
58  {
59  std::lock_guard<std::mutex> lck(connectedMtx_);
60  connected_ = v;
61  }
62 
63  void on_event_disconnected(
64  [[maybe_unused]] const zmq_event_t& event_,
65  [[maybe_unused]] const char* addr_) override
66  {
67  setConnected(false);
68  }
69 
70  void on_event_connected(
71  [[maybe_unused]] const zmq_event_t& event_,
72  [[maybe_unused]] const char* addr_) override
73  {
74  setConnected(true);
75  }
76 
77  bool connected() const
78  {
79  std::lock_guard<std::mutex> lck(connectedMtx_);
80  return connected_;
81  }
82 
83  private:
84  bool connected_ = false;
85  mutable std::mutex connectedMtx_;
86 
87  std::thread runningMonitor_;
88 };
89 
92 } // namespace mvsim
93 
94 #endif
const GLdouble * v
GLdouble s
std::string BASE_IMPEXP format(const char *fmt,...) MRPT_printf_format_check(1


mvsim
Author(s):
autogenerated on Fri May 7 2021 03:05:51