2
0

ConsoleServer.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include "ConsoleServer.h"
  24. #include "JSONParser.h"
  25. #include "TempAllocator.h"
  26. #include "StringStream.h"
  27. #include "Log.h"
  28. #include "Device.h"
  29. #include "ProxyAllocator.h"
  30. #include "LuaEnvironment.h"
  31. namespace crown
  32. {
  33. //-----------------------------------------------------------------------------
  34. ConsoleServer::ConsoleServer()
  35. : m_num_clients(0)
  36. , m_receive_buffer(default_allocator())
  37. , m_send_buffer(default_allocator())
  38. , m_receive_callbacks(default_allocator())
  39. , m_send_callbacks(default_allocator())
  40. {
  41. }
  42. //-----------------------------------------------------------------------------
  43. void ConsoleServer::init(bool wait)
  44. {
  45. m_listener.open(10001);
  46. if (wait)
  47. {
  48. TCPSocket client;
  49. while (!m_listener.listen(client)) ;
  50. add_client(client);
  51. }
  52. }
  53. //-----------------------------------------------------------------------------
  54. void ConsoleServer::shutdown()
  55. {
  56. for (uint32_t i = 0; i < MAX_CONSOLE_CLIENTS; i++)
  57. {
  58. m_clients[i].close();
  59. }
  60. m_listener.close();
  61. }
  62. //-----------------------------------------------------------------------------
  63. void ConsoleServer::log_to_all(const char* message, LogSeverity::Enum severity)
  64. {
  65. TempAllocator2048 alloc;
  66. StringStream json(alloc);
  67. static const char* severity_to_text[] = { "info", "warning", "error", "debug" };
  68. json << "{\"type\":\"message\",";
  69. json << "\"severity\":\"" << severity_to_text[severity] << "\",";
  70. char buf[1024];
  71. string::strncpy(buf, message, 1024);
  72. for (uint32_t i = 0; i < string::strlen(message); i++)
  73. {
  74. if (buf[i] == '"')
  75. buf[i] = '\'';
  76. }
  77. json << "\"message\":\"" << buf << "\"}";
  78. send_message_to_all(json.c_str());
  79. }
  80. //-----------------------------------------------------------------------------
  81. void ConsoleServer::send_message_to(ClientId client, const char* message)
  82. {
  83. RPCCallback cb;
  84. cb.client = client;
  85. cb.message_index = m_send_buffer.size();
  86. m_send_buffer.push(message, string::strlen(message));
  87. m_send_buffer.push_back('\0');
  88. m_send_callbacks.push_back(cb);
  89. }
  90. //-----------------------------------------------------------------------------
  91. void ConsoleServer::send_message_to_all(const char* message)
  92. {
  93. // Update all clients
  94. for (uint32_t i = 0; i < MAX_CONSOLE_CLIENTS; i++)
  95. {
  96. ClientId id = *(m_clients_table.begin() + i);
  97. if (id.id != INVALID_ID)
  98. {
  99. send_message_to(id, message);
  100. }
  101. }
  102. }
  103. //-----------------------------------------------------------------------------
  104. void ConsoleServer::update()
  105. {
  106. // Check for new clients
  107. TCPSocket client;
  108. if (m_listener.listen(client))
  109. {
  110. add_client(client);
  111. }
  112. // Update all clients
  113. for (uint32_t i = 0; i < MAX_CONSOLE_CLIENTS; i++)
  114. {
  115. ClientId id = *(m_clients_table.begin() + i);
  116. if (id.id != INVALID_ID)
  117. {
  118. update_client(id);
  119. }
  120. }
  121. }
  122. //-----------------------------------------------------------------------------
  123. void ConsoleServer::process_requests()
  124. {
  125. for (uint32_t i = 0; i < m_receive_callbacks.size(); i++)
  126. {
  127. RPCCallback cb = m_receive_callbacks.front();
  128. m_receive_callbacks.pop_front();
  129. const char* request = &m_receive_buffer[cb.message_index];
  130. JSONParser parser(request);
  131. JSONElement request_type = parser.root().key("type");
  132. const char* type = request_type.string_value();
  133. // Determine request type
  134. if (string::strcmp("ping", type) == 0) process_ping(cb.client, request);
  135. else if (string::strcmp("script", type) == 0) process_script(cb.client, request);
  136. else if (string::strcmp("stats", type) == 0) process_stats(cb.client, request);
  137. else if (string::strcmp("command", type) == 0) process_command(cb.client, request);
  138. else continue;
  139. }
  140. m_receive_callbacks.clear();
  141. m_receive_buffer.clear();
  142. for (uint32_t i = 0; i < m_send_callbacks.size(); i++)
  143. {
  144. RPCCallback cb = m_send_callbacks.front();
  145. m_send_callbacks.pop_front();
  146. m_clients[cb.client.index].write(&m_send_buffer[cb.message_index], string::strlen(&m_send_buffer[cb.message_index]));
  147. }
  148. m_send_callbacks.clear();
  149. m_send_buffer.clear();
  150. }
  151. //-----------------------------------------------------------------------------
  152. void ConsoleServer::update_client(ClientId id)
  153. {
  154. size_t total_read = 0;
  155. uint32_t message_index = m_receive_buffer.size();
  156. TCPSocket& client = m_clients[id.index];
  157. char buf[1024];
  158. while (true)
  159. {
  160. ReadResult result = client.read(buf, 32);
  161. if (result.error == ReadResult::NO_RESULT_ERROR)
  162. {
  163. if (result.received_bytes > 0)
  164. {
  165. m_receive_buffer.push(buf, result.received_bytes);
  166. total_read += result.received_bytes;
  167. continue;
  168. }
  169. break;
  170. }
  171. else
  172. {
  173. // Close remote connection
  174. client.close();
  175. remove_client(id);
  176. return;
  177. }
  178. }
  179. // Ensure NUL-terminated
  180. m_receive_buffer.push_back('\0');
  181. // Process only if received something
  182. if (total_read > 0)
  183. {
  184. add_request(id, message_index);
  185. }
  186. }
  187. //-----------------------------------------------------------------------------
  188. void ConsoleServer::add_client(TCPSocket& client)
  189. {
  190. if (m_num_clients < MAX_CONSOLE_CLIENTS)
  191. {
  192. ClientId id = m_clients_table.create();
  193. m_clients[id.index] = client;
  194. m_num_clients++;
  195. }
  196. else
  197. {
  198. Log::e("Too many clients, connection denied");
  199. }
  200. }
  201. //-----------------------------------------------------------------------------
  202. void ConsoleServer::remove_client(ClientId id)
  203. {
  204. CE_ASSERT(m_num_clients > 0, "No client connected");
  205. m_clients[id.index].close();
  206. m_clients_table.destroy(id);
  207. m_num_clients--;
  208. }
  209. //-----------------------------------------------------------------------------
  210. void ConsoleServer::add_request(ClientId client, uint32_t message_index)
  211. {
  212. RPCCallback cb;
  213. cb.client = client;
  214. cb.message_index = message_index;
  215. m_receive_callbacks.push_back(cb);
  216. }
  217. //-----------------------------------------------------------------------------
  218. void ConsoleServer::process_ping(ClientId client, const char* /*msg*/)
  219. {
  220. send_message_to(client, "{\"type\":\"pong\"}");
  221. }
  222. //-----------------------------------------------------------------------------
  223. void ConsoleServer::process_script(ClientId /*client*/, const char* msg)
  224. {
  225. JSONParser parser(msg);
  226. JSONElement root = parser.root();
  227. const char* script = root.key("script").string_value();
  228. device()->lua_environment()->execute_string(script);
  229. }
  230. //-----------------------------------------------------------------------------
  231. void ConsoleServer::process_stats(ClientId client, const char* /*msg*/)
  232. {
  233. TempAllocator2048 alloc;
  234. StringStream response(alloc);
  235. response << "{\"type\":\"response\",";
  236. response << "{\"allocators\":[";
  237. // Walk all proxy allocators
  238. ProxyAllocator* proxy = ProxyAllocator::begin();
  239. while (proxy != NULL)
  240. {
  241. response << "{";
  242. response << "\"name\":\"" << proxy->name() << "\",";
  243. response << "\"allocated_size\":\"" << proxy->allocated_size() << "\"";
  244. response << "},";
  245. proxy = ProxyAllocator::next(proxy);
  246. }
  247. response << "]" << "}";
  248. send_message_to(client, response.c_str());
  249. }
  250. //-----------------------------------------------------------------------------
  251. void ConsoleServer::process_command(ClientId /*client*/, const char* msg)
  252. {
  253. JSONParser parser(msg);
  254. JSONElement root = parser.root();
  255. JSONElement command = root.key("command");
  256. const char* cmd = command.string_value();
  257. if (string::strcmp("reload", cmd) == 0)
  258. {
  259. JSONElement resource_type = root.key_or_nil("resource_type");
  260. JSONElement resource_name = root.key_or_nil("resource_name");
  261. char t[256];
  262. char n[256];
  263. string::strncpy(t, resource_type.string_value(), 256);
  264. string::strncpy(n, resource_name.string_value(), 256);
  265. device()->reload(t, n);
  266. }
  267. else if (string::strcmp("pause", cmd) == 0)
  268. {
  269. device()->pause();
  270. }
  271. else if (string::strcmp("unpause", cmd) == 0)
  272. {
  273. device()->unpause();
  274. }
  275. }
  276. } // namespace crown