console_server.h 1.6 KB

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