Subversion Repositories HomeAutomation

Rev

Rev 1959 | Rev 1987 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | SVN | RSS feed

  1. /*
  2.  *
  3.  *  Copyright (C) 2010  Mattias Runge
  4.  *
  5.  *  This program is free software; you can redistribute it and/or modify
  6.  *  it under the terms of the GNU General Public License as published by
  7.  *  the Free Software Foundation; either version 2 of the License, or
  8.  *  (at your option) any later version.
  9.  *
  10.  *  This program is distributed in the hope that it will be useful,
  11.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13.  *  GNU General Public License for more details.
  14.  *
  15.  *  You should have received a copy of the GNU General Public License along
  16.  *  with this program; if not, write to the Free Software Foundation, Inc.,
  17.  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18.  *
  19.  */
  20.  
  21. #include "Console.h"
  22.  
  23. #include <boost/lexical_cast.hpp>
  24. #include <boost/algorithm/string/trim.hpp>
  25. #include <boost/algorithm/string/split.hpp>
  26.  
  27. #include "net/Manager.h"
  28. #include "vm/Manager.h"
  29. #include "common/common.h"
  30.  
  31. namespace atom {
  32. namespace vm {
  33. namespace plugin {
  34.    
  35. logging::Logger Console::LOG("vm::plugin::Console");
  36. net::SocketId Console::current_client_id_;
  37.    
  38. Console::Console(boost::asio::io_service& io_service, unsigned int port) : Plugin(io_service)
  39. {
  40.     this->name_ = "console";
  41.     Console::current_client_id_ = 0;
  42.    
  43.     net::Manager::Instance()->ConnectSlots(net::Manager::SignalOnNewState::slot_type(&Console::SlotOnNewState, this, _1, _2).track(this->tracker_),
  44.                                            net::Manager::SignalOnNewClient::slot_type(&Console::SlotOnNewClient, this, _1, _2).track(this->tracker_),
  45.                                            net::Manager::SignalOnNewData::slot_type(&Console::SlotOnNewData, this, _1, _2).track(this->tracker_));
  46.    
  47.     this->ExportFunction("ConsoleExport_PromptRequest",        Console::Export_PromptRequest);
  48.     this->ExportFunction("ConsoleExport_AutoCompleteResponse", Console::Export_AutoCompleteResponse);
  49.     this->ExportFunction("ConsoleExport_LogToClient",          Console::Export_LogToClient);
  50.     this->ExportFunction("ConsoleExport_DisconnectClient",     Console::Export_DisconnectClient);
  51.    
  52.     try
  53.     {
  54.         this->server_id_ = net::Manager::Instance()->StartServer(net::PROTOCOL_TCP, port);
  55.         LOG.Info("Started TCP server on port " + boost::lexical_cast<std::string>(port) + ".");
  56.         LOG.Debug("Server id is " + boost::lexical_cast<std::string>(this->server_id_) + ".");
  57.     }
  58.     catch (std::runtime_error& e)
  59.     {
  60.         LOG.Error(e.what());
  61.     }
  62. }
  63.  
  64. Console::~Console()
  65. {
  66.     net::Manager::Instance()->StopServer(this->server_id_);
  67.     this->server_id_ = 0;
  68. }
  69.  
  70. void Console::InitializeDone()
  71. {
  72.     Plugin::InitializeDone();
  73.    
  74.     this->ImportFunction("Console_AutocompleteRequest");
  75.     this->ImportFunction("Console_PromptResponse");
  76.     this->ImportFunction("Console_NewConnection");
  77. }
  78.  
  79. void Console::CallOutput(unsigned int request_id, std::string output)
  80. {
  81.     std::string packet = "TEXT";
  82.     packet += common::PadNumber(output.length() + 1, 4);
  83.     packet += output;
  84.    
  85.     net::Manager::Instance()->SendTo(request_id, packet);
  86. }
  87.  
  88. void Console::SlotOnNewData(net::SocketId id, common::Byteset data)
  89. {
  90.     this->io_service_.post(boost::bind(&Console::SlotOnNewDataHandler, this, id, data));
  91. }
  92.  
  93. void Console::SlotOnNewClient(net::SocketId id, net::SocketId server_id)
  94. {
  95.   this->io_service_.post(boost::bind(&Console::SlotOnNewClientHandler, this, id, server_id));
  96. }
  97.  
  98. void Console::SlotOnNewState(net::SocketId id, net::ClientState client_state)
  99. {
  100.     this->io_service_.post(boost::bind(&Console::SlotOnNewStateHandler, this, id, client_state));
  101. }
  102.  
  103. void Console::SlotOnNewDataHandler(net::SocketId id, common::Byteset data)
  104. {
  105.     v8::Locker lock;
  106.     v8::Context::Scope context_scope(vm::Manager::Instance()->GetContext());
  107.     v8::HandleScope handle_scope;
  108.  
  109.     if (std::find(this->clients_.begin(), this->clients_.end(), id) == this->clients_.end())
  110.     {
  111.       return;
  112.     }
  113.      
  114.    
  115.     //LOG.Debug(std::string(__FUNCTION__) + " called!");
  116.  
  117.     if (data.GetSize() == 0)
  118.     {
  119.         LOG.Error(std::string(__FUNCTION__) + " got empty data!");
  120.         return;
  121.     }
  122.    
  123.     std::string s(data.ToCharString());
  124.    
  125.     if (s.length() < 8)
  126.     {
  127.         LOG.Error(std::string(__FUNCTION__) + " got a packet which is to short, less then 8 bytes: \"" + s + "\"");
  128.         return;
  129.     }
  130.    
  131.     std::string command = s.substr(0, 4);
  132.    
  133.     LOG.Debug(std::string(__FUNCTION__) + " parsed command: \"" + command + "\"");
  134.    
  135.     // TODO: Check cast exception!
  136.     unsigned int payload_length = boost::lexical_cast<unsigned int>(s.substr(4, 4));
  137.  
  138.     LOG.Debug(std::string(__FUNCTION__) + " parsed payload_length: \"" + boost::lexical_cast<std::string>(payload_length) + "\"");
  139.  
  140.    
  141.     Console::current_client_id_ = id;
  142.    
  143.     if (command == "COMP")
  144.     {
  145.         ArgumentListPointer call_arguments = ArgumentListPointer(new ArgumentList);
  146.        
  147.         call_arguments->push_back(v8::Integer::New(boost::lexical_cast<unsigned int>(id)));
  148.         call_arguments->push_back(v8::Integer::New(boost::lexical_cast<unsigned int>(s.substr(8, 4))));
  149.         call_arguments->push_back(v8::String::New(s.substr(12).data()));
  150.        
  151.         if (!this->Call(id, "Console_AutocompleteRequest", call_arguments))
  152.         {
  153.             LOG.Error("Console_AutocompleteRequest failed, we are now in an undefined state!");
  154.         }
  155.     }
  156.     else if (command == "RESP")
  157.     {
  158.         LOG.Debug(std::string(__FUNCTION__) + " parsed data: \"" + s.substr(8).data() + "\"");
  159.        
  160.         ArgumentListPointer call_arguments = ArgumentListPointer(new ArgumentList);
  161.        
  162.         call_arguments->push_back(v8::Integer::New(boost::lexical_cast<unsigned int>(id)));
  163.         call_arguments->push_back(v8::String::New(s.substr(8).data()));
  164.        
  165.         if (!this->Call(id, "Console_PromptResponse", call_arguments))
  166.         {
  167.             LOG.Error("Console_PromptResponse failed, we are now in an undefined state!");
  168.         }
  169.     }
  170.     else
  171.     {
  172.         LOG.Error("Unknown packat received, we are now in an undefined state!");
  173.     }
  174.    
  175.     Console::current_client_id_ = 0;
  176. }
  177.  
  178. void Console::SlotOnNewClientHandler(net::SocketId id, net::SocketId server_id)
  179. {
  180.   if (server_id == this->server_id_)
  181.   {
  182.     this->clients_.insert(id);
  183.   }
  184. }
  185.  
  186. void Console::SlotOnNewStateHandler(net::SocketId id, net::ClientState client_state)
  187. {
  188.     v8::Locker lock;
  189.     v8::Context::Scope context_scope(vm::Manager::Instance()->GetContext());
  190.     v8::HandleScope handle_scope;
  191.  
  192.     if (std::find(this->clients_.begin(), this->clients_.end(), id) == this->clients_.end())
  193.     {
  194.       return;
  195.     }
  196.    
  197.     //LOG.Debug(std::string(__FUNCTION__) + " called!");
  198.    
  199.     if (client_state == net::CLIENT_STATE_DISCONNECTED)
  200.     {
  201.         LOG.Info("Client " + boost::lexical_cast<std::string>(id) + " has disconnected.");
  202.         this->clients_.erase(id);
  203.     }
  204.     else if (client_state == net::CLIENT_STATE_CONNECTED)
  205.     {
  206.         LOG.Info("Client " + boost::lexical_cast<std::string>(id) + " has connected.");
  207.      
  208.         Console::current_client_id_ = id;
  209.        
  210.         ArgumentListPointer call_arguments = ArgumentListPointer(new ArgumentList);
  211.        
  212.         call_arguments->push_back(v8::Integer::New(boost::lexical_cast<unsigned int>(id)));
  213.        
  214.         if (!this->Call(id, "Console_NewConnection", call_arguments))
  215.         {
  216.             LOG.Error("Console_NewConnection failed, we are now in an undefined state!");
  217.         }
  218.        
  219.         Console::current_client_id_ = 0;
  220.     }
  221.     else
  222.     {
  223.         LOG.Debug("Got state: " + boost::lexical_cast<std::string>((int)client_state));
  224.     }
  225. }
  226.  
  227. Value Console::Export_PromptRequest(const v8::Arguments& args)
  228. {
  229.     v8::Locker lock;
  230.     v8::Context::Scope context_scope(vm::Manager::Instance()->GetContext());
  231.     v8::HandleScope handle_scope;
  232.    
  233.     //LOG.Debug(std::string(__FUNCTION__) + " called!");
  234.    
  235.     if (args.Length() < 2)
  236.     {
  237.         LOG.Error(std::string(__FUNCTION__) + ": To few arguments.");
  238.         return handle_scope.Close(v8::Boolean::New(false));
  239.     }
  240.    
  241.     v8::String::AsciiValue prompt(args[1]);
  242.    
  243.     std::string packet = "PROM";
  244.     packet += common::PadNumber(prompt.length() + 1, 4);
  245.     packet += *prompt;
  246.    
  247.     net::Manager::Instance()->SendTo(args[0]->Uint32Value(), packet);
  248.     return handle_scope.Close(v8::Boolean::New(true));
  249. }
  250.  
  251. Value Console::Export_AutoCompleteResponse(const v8::Arguments& args)
  252. {
  253.     v8::Locker lock;
  254.     v8::Context::Scope context_scope(vm::Manager::Instance()->GetContext());
  255.     v8::HandleScope handle_scope;
  256.    
  257.     //LOG.Debug(std::string(__FUNCTION__) + " called!");
  258.    
  259.     if (args.Length() < 2)
  260.     {
  261.         LOG.Error(std::string(__FUNCTION__) + ": To few arguments.");
  262.         return handle_scope.Close(v8::Boolean::New(false));
  263.     }
  264.    
  265.     v8::String::AsciiValue result(args[1]);
  266.    
  267.     std::string packet = "COMP";
  268.     packet += common::PadNumber(result.length() + 1, 4);
  269.     packet += *result;
  270.    
  271.     net::Manager::Instance()->SendTo(args[0]->Uint32Value(), packet);
  272.     return handle_scope.Close(v8::Boolean::New(true));
  273. }
  274.  
  275. Value Console::Export_LogToClient(const v8::Arguments& args)
  276. {
  277.     v8::Locker lock;
  278.     v8::Context::Scope context_scope(vm::Manager::Instance()->GetContext());
  279.     v8::HandleScope handle_scope;
  280.    
  281.     //LOG.Debug(std::string(__FUNCTION__) + " called!");
  282.    
  283.     if (args.Length() < 2)
  284.     {
  285.         LOG.Error(std::string(__FUNCTION__) + ": To few arguments.");
  286.         return handle_scope.Close(v8::Boolean::New(false));
  287.     }
  288.    
  289.     v8::String::AsciiValue text(args[1]);
  290.    
  291.     std::string line = *text;
  292.    
  293.     std::string packet = "TEXT";
  294.     packet += common::PadNumber(line.length() + 1, 4);
  295.     packet += line;
  296.    
  297.     net::Manager::Instance()->SendTo(args[0]->Uint32Value(), packet);
  298.     return handle_scope.Close(v8::Boolean::New(true));
  299. }
  300.  
  301. Value Console::Export_DisconnectClient(const v8::Arguments& args)
  302. {
  303.     v8::Locker lock;
  304.     v8::Context::Scope context_scope(vm::Manager::Instance()->GetContext());
  305.     v8::HandleScope handle_scope;
  306.    
  307.     //LOG.Debug(std::string(__FUNCTION__) + " called!");
  308.    
  309.     if (args.Length() < 1)
  310.     {
  311.         LOG.Error(std::string(__FUNCTION__) + ": To few arguments.");
  312.         return handle_scope.Close(v8::Boolean::New(false));
  313.     }
  314.     net::Manager::Instance()->Disconnect(args[0]->Uint32Value());
  315.     return handle_scope.Close(v8::Boolean::New(true));
  316. }
  317.  
  318. }; // namespace plugin
  319. }; // namespace vm
  320. }; // namespace atom
  321.