console_server.h 1.9 KB

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