console_server.h 1.7 KB

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