Resurgence (PY2022)
Codebase for the Husky Robotics 2021-2022 rover Resurgence
Loading...
Searching...
No Matches
WebSocketProtocol.h
1#pragma once
2
3#include <chrono>
4#include <functional>
5#include <map>
6#include <optional>
7#include <string>
8
9#include <nlohmann/json.hpp>
10
11namespace net {
12namespace websocket {
13
14using nlohmann::json;
15
16typedef std::function<void(const json&)> msghandler_t;
17typedef std::function<bool(const json&)> validator_t;
18typedef std::function<void()> connhandler_t;
19typedef std::function<void()> heartbeattimeouthandler_t;
20
31public:
40 WebSocketProtocol(const std::string& protocolPath);
41
42 virtual ~WebSocketProtocol() = default;
43
53 bool addMessageHandler(const std::string& messageType, const msghandler_t& callback);
54
67 bool addMessageHandler(const std::string& messageType, const msghandler_t& callback,
68 const validator_t& validator);
69
77 bool removeMessageHandler(const std::string& messageType);
78
85 bool hasMessageHandler(const std::string& messageType) const;
86
87 void addConnectionHandler(const connhandler_t& handler);
88
89 void addDisconnectionHandler(const connhandler_t& handler);
90
101 const heartbeattimeouthandler_t& handler);
102
109
110private:
111 friend class SingleClientWSServer;
112
113 std::string protocolPath;
116 std::vector<connhandler_t> connectionHandlers;
117 std::vector<connhandler_t> disconnectionHandlers;
118 std::optional<std::pair<std::chrono::milliseconds, heartbeattimeouthandler_t>>
119 heartbeatInfo;
120
127 void processMessage(const json& obj) const;
128
132 void clientConnected();
133
137 void clientDisconnected();
138
142 void heartbeatTimedOut();
143};
144
145} // namespace websocket
146} // namespace net
_GLIBCXX_END_NAMESPACE_CXX11 typedef basic_string< char > string
duration< int64_t, milli > milliseconds
WebSocketProtocol(const std::string &protocolPath)
Construct a new WebSocket protocol.
Definition WebSocketProtocol.cpp:11
bool removeMessageHandler(const std::string &messageType)
Remove the message handler for the given message type, if it exists.
Definition WebSocketProtocol.cpp:34
std::string getProtocolPath() const
Get the protocol path of the endpoint this protocol is served on.
Definition WebSocketProtocol.cpp:97
bool addMessageHandler(const std::string &messageType, const msghandler_t &callback)
Add a message handler for the given message type, if no handler already exists.
Definition WebSocketProtocol.cpp:14
WebSocketProtocol(const std::string &protocolPath)
Construct a new WebSocket protocol.
Definition WebSocketProtocol.cpp:11
bool hasMessageHandler(const std::string &messageType) const
Check if the given message type has an associated message handler.
Definition WebSocketProtocol.cpp:30
void setHeartbeatTimedOutHandler(std::chrono::milliseconds timeout, const heartbeattimeouthandler_t &handler)
Set the handler that's called when the heartbeat times out.
Definition WebSocketProtocol.cpp:50
basic_json<> json