console_server.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c) 2012-2014 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #pragma once
  6. #include "socket.h"
  7. #include "container_types.h"
  8. #include "queue.h"
  9. #include "id_array.h"
  10. namespace crown
  11. {
  12. /// Enumerates log levels.
  13. struct LogSeverity
  14. {
  15. enum Enum
  16. {
  17. INFO = 0,
  18. WARN = 1,
  19. ERROR = 2,
  20. DEBUG = 3
  21. };
  22. };
  23. struct Client
  24. {
  25. Id id;
  26. TCPSocket socket;
  27. void close()
  28. {
  29. socket.close();
  30. }
  31. };
  32. typedef IdArray<CE_MAX_CONSOLE_CLIENTS, Client> ClientArray;
  33. class ConsoleServer
  34. {
  35. public:
  36. /// Listens on the given @a port. If @a wait is true, this function
  37. /// blocks until a client is connected.
  38. ConsoleServer(uint16_t port, bool wait);
  39. void shutdown();
  40. void log_to_all(const char* msg, LogSeverity::Enum severity = LogSeverity::INFO);
  41. /// Collects requests from clients and processes them all.
  42. void update();
  43. /// Sends the given JSON-encoded string to all clients.
  44. void send_to_all(const char* json);
  45. private:
  46. void send(TCPSocket client, const char* message);
  47. void add_client(TCPSocket socket);
  48. ReadResult update_client(TCPSocket client);
  49. void process(TCPSocket client, const char* request);
  50. void process_ping(TCPSocket client, const char* msg);
  51. void process_script(TCPSocket client, const char* msg);
  52. void process_command(TCPSocket client, const char* msg);
  53. private:
  54. TCPSocket m_server;
  55. ClientArray m_clients;
  56. };
  57. /// Functions for accessing global console.
  58. namespace console_server_globals
  59. {
  60. // Creates the global console server.
  61. void init(uint16_t port, bool wait);
  62. /// Destroys the global console server.
  63. void shutdown();
  64. /// Updates the global console server.
  65. void update();
  66. /// Returns the global console server object.
  67. ConsoleServer& console();
  68. } // namespace console_server_globals
  69. } // namespace crown