Bridges-C++  3.4.5-dev1-6-g935685a
Bridges(C++ API)
SocketConnection.h
Go to the documentation of this file.
1 #ifndef SOCKET_CONNECTION_H
2 #define SOCKET_CONNECTION_H
3 
5 //technically these are defined necessarry for socketio.
6 //but they only get included from here
7 //so this is simpler than mocking with build chains for each compiler
8 #define BOOST_DATE_TIME_NO_LIB
9 #define BOOST_REGEX_NO_LIB
10 #define ASIO_STANDALONE
11 #define _WEBSOCKETPP_CPP11_STL_
12 #define _WEBSOCKETPP_CPP11_FUNCTIONAL_
14 
15 #include "sio_client.h"
16 #include "internal/sio_packet.h"
17 #include <Bridges.h>
18 #include <GameGrid.h>
19 #include <Scene.h>
20 #include <list>
21 #include <thread>
22 #include <mutex>
23 #include <condition_variable>
24 #include <functional>
25 
26 #include <unistd.h>
27 
28 namespace bridges {
29  namespace game {
30 
35  public:
36  virtual void keyup(std::string JSONmessage) = 0;
37  virtual void keydown(std::string JSONmessage) = 0;
38  };
39 
49  bool debug = false;
50  bool debugVerbose = false;
51  sio::client client;
52  sio::socket::ptr current_socket;
53 
55 
56  std::mutex _lock;
57 
58  std::condition_variable_any _cond; //condition used to wait on connection to be established
59  bool connect_finish = false;
60 
61  std::list<KeypressListener*> key_listeners;
62 
63  private:
66  std::string getJSON( sio::message::ptr msg ) {
67  //This function is from SocketIO's issues.
68  static sio::packet_manager manager;
69  static std::mutex packetLock;
70  std::lock_guard< std::mutex > guard( packetLock );
71 
72  std::stringstream ss;
73  sio::packet packet( "/", msg );
74  manager.encode( packet, [&](bool isBinary, std::shared_ptr<const std::string> const & json) {
75  ss << *json;
76  assert( !isBinary );
77  });
78  manager.reset();
79 
80  // Need to strip off the message type flags (typically '42',
81  // but there are other possible combinations).
82  std::string result = ss.str();
83  std::size_t indexList = result.find( '[' );
84  std::size_t indexObject = result.find( '{' );
85  std::size_t indexString = result.find( '"' );
86  std::size_t index = indexList;
87  if ( indexObject != std::string::npos && indexObject < index )
88  index = indexObject;
89  if ( indexString != std::string::npos && indexString < index )
90  index = indexString;
91 
92  if ( index == std::string::npos ) {
93  std::cerr << "Error decoding json object" << std::endl << " Body: " << result << std::endl;
94  return "";
95  }
96  return result.substr(index);
97  }
98 
99  public:
100 
101  //Bridges object should have been initialized with correct
102  //credentials and server at this point.
104  : bridges(b) {
105  client.set_open_listener(std::bind(&SocketConnection::on_connected, this));
106  client.set_close_listener(std::bind(&SocketConnection::on_close, this, std::placeholders::_1));
107  client.set_fail_listener(std::bind(&SocketConnection::on_fail, this));
108  client.set_reconnect_listener(std::bind(&SocketConnection::on_reconnect, this, std::placeholders::_1, std::placeholders::_2));
109  client.set_socket_open_listener(std::bind(&SocketConnection::on_socketopen, this, std::placeholders::_1));
110 
111  //client.set_logs_verbose();
112 
113  std::string serverURL = bridges.getServerURL();
114 
115  if (debug)
116  std::cerr << "connecting SocketIO with " << serverURL << "\n";
117 
118  //serverURL="https://bridges-games.herokuapp.com";
119  client.connect(serverURL); //get from bridges object
120 
122 
123  usleep(100000);
124 
126 
127  }
128 
130  std::lock_guard< std::mutex > guard( _lock );
131 
132  key_listeners.push_back(p);
133  }
134 
135  void forwardKeyUp(sio::event & e) {
136  std::lock_guard< std::mutex > guard( _lock );
137 
138  std::string jsonmsg = getJSON(e.get_message());
139 
140  if (debug)
141  std::cerr << "forwardKeyUp:" << e.get_nsp() << " " << e.get_name() << " : " << jsonmsg << "\n";
142 
143  for (auto& ptr : key_listeners)
144  ptr->keyup(jsonmsg);
145  }
146 
147  void forwardKeyDown(sio::event & e) {
148  std::lock_guard< std::mutex > guard( _lock );
149 
150  std::string jsonmsg = getJSON(e.get_message());
151 
152  if (debug)
153  std::cerr << "forwardKeyDown:" << e.get_nsp() << " " << e.get_name() << " : " << jsonmsg << "\n";
154 
155  for (auto& ptr : key_listeners)
156  ptr->keydown(jsonmsg);
157  }
158 
160  client.clear_con_listeners();
161  client.sync_close();
162  }
163 
165  current_socket = client.socket();
166 
167  current_socket->on("keyup", std::bind(&SocketConnection::forwardKeyUp, this, std::placeholders::_1));
168  current_socket->on("keydown", std::bind(&SocketConnection::forwardKeyDown, this, std::placeholders::_1));
169  current_socket->on("announcement", std::bind(&SocketConnection::on_announcement, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
170  current_socket->on_error(std::bind(&SocketConnection::on_socketerror, this, std::placeholders::_1));
171  sendCredentials();
172 
173  }
174 
176 
177  if (debug)
178  std::cerr << "Sending credentials\n";
179 
180  std::string user = bridges.getUserName();
181  std::string apikey = bridges.getApiKey();
182 
183  auto assID = bridges.getAssignment();
184 
185  current_socket->emit("credentials",
186  "{\"user\":\"" + user
187  + "\",\"apikey\":\"" + apikey
188  + "\",\"assignment\":\"" + std::to_string(assID)
189  + "\"}");
190  if (debug)
191  std::cerr << "Credentials sent\n";
192  }
193 
194  void on_reconnect(unsigned, unsigned) {
195  std::cout << "reconnect..." << std::endl;
196  //reconfigure_socket();
197  }
198 
199  void on_socketopen(const std::string & nsp) {
200  std::lock_guard< std::mutex > guard( _lock );
201 
202  std::cout << "sockopen on namespace " << nsp << std::endl;
203 
205  }
206 
207  void on_connected() {
208  std::lock_guard< std::mutex > guard( _lock );
209  if (debug)
210  std::cout << "connected!!\n";
211 
212  _cond.notify_all();
213  connect_finish = true;
214  }
215 
216  void on_close(sio::client::close_reason const& reason) {
217  std::cout << "sio closed\n";
218  exit(0);
219  }
220 
221  void on_socketerror(sio::message::ptr const& message) {
222  std::cout << "socket errror\n";
223 
224  }
225 
226  void on_fail() {
227  std::cout << "sio failed\n";
228  exit(0);
229  }
230 
231  void on_announcement (std::string const& name, sio::message::ptr const& data, bool isAck, sio::message::list &ack_resp) {
232  if (debug)
233  std::cerr << "announcement something\n";
234  }
235 
237  //can't use lock guard since we need to wait on a condition
238  _lock.lock();
239  if (!connect_finish) {
240  _cond.wait(_lock);
241  }
242  _lock.unlock();
243 
244  }
245 
246  void sendDataToServer(const GameGrid& gg) {
247  if (debug && debugVerbose)
248  std::cerr << "Sending GameGrid\n";
249  std::string gridjson = "{" + gg.getDataStructureRepresentation();
250 
251  current_socket->emit("gamegrid:recv", gridjson);
252  }
253 
254  void sendSceneDataToServer(const Scene& s) {
255  if (debug && debugVerbose)
256  std::cerr << "Sending Scene\n";
257  std::string scenejson = "{" + s.getDataStructureRepresentation();
258 
259  current_socket->emit("scene:recv", scenejson);
260  }
261  };
262  }
263 }
264 
265 #endif
This class contains methods to connect and transmit a user's data structure representation to the Bri...
Definition: Bridges.h:50
Definition: Scene.h:14
This is a class in BRIDGES for representing an (n x n)game grid.
Definition: GameGrid.h:398
virtual const string getDataStructureRepresentation() const override
Definition: GameGrid.h:522
This is meant to be an internal class, not something that the library user will use....
Definition: SocketConnection.h:34
virtual void keyup(std::string JSONmessage)=0
virtual void keydown(std::string JSONmessage)=0
This is meant to be an internal class, not something that the library user will use.
Definition: SocketConnection.h:48
void sendSceneDataToServer(const Scene &s)
Definition: SocketConnection.h:254
void reconfigure_socket()
Definition: SocketConnection.h:164
void sendCredentials()
Definition: SocketConnection.h:175
void forwardKeyDown(sio::event &e)
Definition: SocketConnection.h:147
void on_fail()
Definition: SocketConnection.h:226
void on_connected()
Definition: SocketConnection.h:207
SocketConnection(bridges::Bridges &b)
Definition: SocketConnection.h:103
void registerKeyListener(KeypressListener *p)
Definition: SocketConnection.h:129
void on_announcement(std::string const &name, sio::message::ptr const &data, bool isAck, sio::message::list &ack_resp)
Definition: SocketConnection.h:231
void on_socketopen(const std::string &nsp)
Definition: SocketConnection.h:199
void wait_on_connection()
Definition: SocketConnection.h:236
void on_close(sio::client::close_reason const &reason)
Definition: SocketConnection.h:216
void on_reconnect(unsigned, unsigned)
Definition: SocketConnection.h:194
void sendDataToServer(const GameGrid &gg)
Definition: SocketConnection.h:246
~SocketConnection()
Definition: SocketConnection.h:159
void on_socketerror(sio::message::ptr const &message)
Definition: SocketConnection.h:221
void forwardKeyUp(sio::event &e)
Definition: SocketConnection.h:135
Support for drawing Bar charts.
Definition: alltypes.h:4