WPILibC++  unspecified
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Pages
RpcServer.h
1 /*----------------------------------------------------------------------------*/
2 /* Copyright (c) FIRST 2015. All Rights Reserved. */
3 /* Open Source Software - may be modified and shared by FRC teams. The code */
4 /* must be accompanied by the FIRST BSD license file in the root directory of */
5 /* the project. */
6 /*----------------------------------------------------------------------------*/
7 
8 #ifndef NT_RPCSERVER_H_
9 #define NT_RPCSERVER_H_
10 
11 #include <atomic>
12 #include <condition_variable>
13 #include <mutex>
14 #include <queue>
15 #include <utility>
16 
17 #include "llvm/DenseMap.h"
18 #include "support/atomic_static.h"
19 #include "support/SafeThread.h"
20 #include "Message.h"
21 #include "ntcore_cpp.h"
22 
23 namespace nt {
24 
25 class RpcServer {
26  friend class RpcServerTest;
27 
28  public:
29  static RpcServer& GetInstance() {
30  ATOMIC_STATIC(RpcServer, instance);
31  return instance;
32  }
33  ~RpcServer();
34 
35  typedef std::function<void(std::shared_ptr<Message>)> SendMsgFunc;
36 
37  void Start();
38  void Stop();
39 
40  void SetOnStart(std::function<void()> on_start) { m_on_start = on_start; }
41  void SetOnExit(std::function<void()> on_exit) { m_on_exit = on_exit; }
42 
43  void ProcessRpc(StringRef name, std::shared_ptr<Message> msg,
44  RpcCallback func, unsigned int conn_id,
45  SendMsgFunc send_response, const ConnectionInfo& conn_info);
46 
47  bool PollRpc(bool blocking, RpcCallInfo* call_info);
48  bool PollRpc(bool blocking, double time_out, RpcCallInfo* call_info);
49  void PostRpcResponse(unsigned int rpc_id, unsigned int call_uid,
50  llvm::StringRef result);
51 
52  private:
53  RpcServer();
54 
55  class Thread;
56  wpi::SafeThreadOwner<Thread> m_owner;
57 
58  struct RpcCall {
59  RpcCall(StringRef name_, std::shared_ptr<Message> msg_, RpcCallback func_,
60  unsigned int conn_id_, SendMsgFunc send_response_,
61  const ConnectionInfo conn_info_)
62  : name(name_),
63  msg(msg_),
64  func(func_),
65  conn_id(conn_id_),
66  send_response(send_response_),
67  conn_info(conn_info_) {}
68 
69  std::string name;
70  std::shared_ptr<Message> msg;
71  RpcCallback func;
72  unsigned int conn_id;
73  SendMsgFunc send_response;
74  ConnectionInfo conn_info;
75  };
76 
77  std::mutex m_mutex;
78 
79  std::queue<RpcCall> m_poll_queue;
80  llvm::DenseMap<std::pair<unsigned int, unsigned int>, SendMsgFunc>
81  m_response_map;
82 
83  std::condition_variable m_poll_cond;
84 
85  std::atomic_bool m_terminating;
86 
87  std::function<void()> m_on_start;
88  std::function<void()> m_on_exit;
89 
90  ATOMIC_STATIC_DECL(RpcServer)
91 };
92 
93 } // namespace nt
94 
95 #endif // NT_RPCSERVER_H_
NetworkTables Connection Information.
Definition: ntcore_cpp.h:43
NetworkTables RPC Call Data.
Definition: ntcore_cpp.h:79
Definition: RpcServer.cpp:18
Definition: RpcServer.h:25