Subversion Repositories HomeAutomation

Rev

Rev 1664 | Rev 1675 | 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 <string>
  22. #include <vector>
  23. #include <iostream>
  24.  
  25. #include <signal.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <pwd.h>
  29.  
  30. #include <boost/lexical_cast.hpp>
  31. #include <boost/thread/mutex.hpp>
  32. #include <boost/thread/condition.hpp>
  33. #include <boost/thread/locks.hpp>
  34. #include <boost/algorithm/string.hpp>
  35. #include <boost/program_options.hpp>
  36.  
  37. #include "config.h"
  38.  
  39. #include "net/Manager.h"
  40. #include "net/Subscriber.h"
  41. #include "net/types.h"
  42.  
  43. #include "common/common.h"
  44.  
  45. #include <readline/readline.h>
  46. #include <readline/history.h>
  47.  
  48. using namespace atom;
  49.  
  50. bool finish = false;
  51. common::StringList autocomplete_list;
  52. char* buffer = NULL;
  53. boost::condition on_message_condition;
  54. struct termios original_flags;
  55. std::string history_filename;
  56.  
  57. void Handler(int status);
  58. void CleanUp();
  59.  
  60. char* AutoCompleteGet(const char* text, int state);
  61. static char** AutoComplete(const char* text, int start, int end);
  62.  
  63. std::string GetUserHomeDirectory()
  64. {
  65.     return std::string(getpwuid(getuid())->pw_dir);
  66. }
  67.  
  68. class ConsoleClient : public net::Subscriber
  69. {
  70. public:
  71.     typedef boost::shared_ptr<ConsoleClient> Pointer;
  72.    
  73.     ConsoleClient(std::string address, unsigned int port)
  74.     {
  75.         this->client_id_ = net::Manager::Instance()->Connect(net::PROTOCOL_TCP, address, port);
  76.     }
  77.    
  78.     virtual ~ConsoleClient()
  79.     {
  80.         net::Manager::Instance()->Disconnect(this->client_id_);
  81.  
  82.         this->io_service_.stop();
  83.     }
  84.    
  85.     std::string GetPrompt()
  86.     {
  87.         return this->prompt_;
  88.     }
  89.    
  90.     void SendResponse(std::string payload)
  91.     {
  92.         std::string packet = "RESP";
  93.         packet += common::PadNumber(payload.length() + 1, 4);
  94.         packet += payload;
  95.        
  96.         net::Manager::Instance()->SendTo(this->client_id_, packet);
  97.     }
  98.    
  99.     void AutoCompleteRequest(unsigned int arg_index, std::string commandline)
  100.     {
  101.         std::string payload = common::PadNumber(arg_index, 4);
  102.         payload += commandline;
  103.        
  104.         std::string packet = "COMP";
  105.         packet += common::PadNumber(payload.length() + 1, 4);
  106.         packet += payload;
  107.        
  108.         net::Manager::Instance()->SendTo(this->client_id_, packet);
  109.     }
  110.    
  111. private:
  112.     net::ClientId client_id_;
  113.     std::string prompt_;
  114.    
  115.     void SlotOnNewStateHandler(net::ClientId client_id, net::ServerId server_id, net::ClientState client_state)
  116.     {
  117.         if (client_state != net::CLIENT_STATE_CONNECTED)
  118.         {
  119.             std::cout << "Disconnected from server." << std::endl;
  120.            
  121.             this->client_id_ = 0;
  122.             finish = true;
  123.             on_message_condition.notify_all();
  124.         }
  125.     }
  126.    
  127.     void SlotOnNewDataHandler(net::ClientId client_id, net::ServerId server_id, common::Byteset data)
  128.     {
  129.         std::string s(data.ToCharString());
  130.  
  131.         while (s.length() > 0)
  132.         {
  133.             std::string command = s.substr(0, 4);
  134.             unsigned int payload_length = boost::lexical_cast<unsigned int>(s.substr(4, 4));
  135.            
  136.             if (command == "TEXT")
  137.             {
  138.                 std::cout << s.substr(8, payload_length - 1) << std::flush;
  139.             }
  140.             else if (command == "PROM")
  141.             {
  142.                 this->prompt_ = s.substr(8, payload_length - 1);
  143.                 on_message_condition.notify_all();
  144.             }
  145.             else if (command == "COMP")
  146.             {
  147.                 autocomplete_list.clear();
  148.                
  149.                 if (payload_length > 0)
  150.                 {
  151.                     std::string payload = s.substr(8, payload_length - 1);
  152.                    
  153.                     if (payload.length() > 0)
  154.                     {
  155.                         boost::algorithm::split(autocomplete_list, payload, boost::is_any_of("\n"), boost::algorithm::token_compress_on);
  156.                     }
  157.                 }
  158.                
  159.                 on_message_condition.notify_all();
  160.             }
  161.             else
  162.             {
  163.                 std::cerr << "Unknown data received: " << s << std::endl;
  164.                 finish = true;
  165.                 on_message_condition.notify_all();
  166.                 break;
  167.             }
  168.            
  169.             if (8 + payload_length >= s.length())
  170.             {
  171.                 break;
  172.             }
  173.            
  174.             s = s.substr(8 + payload_length);
  175.         }
  176.     }
  177. };
  178.  
  179. ConsoleClient::Pointer cc;
  180.  
  181.  
  182. int main(int argc, char **argv)
  183. {
  184.     // Signal handlers
  185.     signal(SIGTERM, Handler);
  186.     signal(SIGINT, Handler);
  187.     signal(SIGQUIT, Handler);
  188.     signal(SIGABRT, Handler);
  189.     signal(SIGPIPE, Handler);
  190.    
  191.     boost::mutex guard_mutex;
  192.    
  193.     // Setup readline
  194.     history_filename = GetUserHomeDirectory() + "/.atomic_history";
  195.     read_history(history_filename.data());
  196.    
  197.     rl_attempted_completion_function = AutoComplete;
  198.    
  199.     // Save command line state
  200.     tcgetattr(fileno(stdin), &original_flags);
  201.    
  202.     // Parse commandline
  203.     boost::program_options::options_description command_line;
  204.     boost::program_options::variables_map variable_map;
  205.    
  206.     command_line.add_options()
  207.     ("help,h",    "produce help message")
  208.     ("command,c", boost::program_options::value<std::string>()->default_value(""), "command")
  209.     ("server,s",  boost::program_options::value<std::string>()->default_value("localhost"), "server address")
  210.     ("port,p",    boost::program_options::value<unsigned int>()->default_value(1202), "server port");
  211.    
  212.     try
  213.     {
  214.         boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(command_line).run(), variable_map);
  215.     }
  216.     catch (boost::program_options::unknown_option e)
  217.     {
  218.         std::cerr << e.what() << std::endl;
  219.         std::cout << command_line << std::endl;
  220.         CleanUp();
  221.         return EXIT_FAILURE;
  222.     }
  223.     catch (boost::program_options::invalid_syntax e)
  224.     {
  225.         std::cerr << e.what() << std::endl;
  226.         std::cout << command_line << std::endl;
  227.         CleanUp();
  228.         return EXIT_FAILURE;
  229.     }
  230.    
  231.     if (variable_map.count("help") != 0)
  232.     {
  233.         std::cout << command_line << std::endl;
  234.         CleanUp();
  235.         return EXIT_SUCCESS;
  236.     }
  237.    
  238.     net::Manager::Create();
  239.  
  240.     if (variable_map["command"].as<std::string>() == "")
  241.     {
  242.         std::cout << "\033[29;1mAtom Interactive Console, version " + std::string(VERSION) + " starting...\033[0m" << std::endl;
  243.         std::cout << "\033[29;1mReleased under GPL version 2.\033[0m" << std::endl;
  244.         std::cout << "Written by Mattias Runge 2010." << std::endl;
  245.        
  246.         std::cout << "Connecting to " << variable_map["server"].as<std::string>().data() << ":" << variable_map["port"].as<unsigned int>() << "..." << std::endl;
  247.     }
  248.    
  249.     try
  250.     {
  251.         cc = ConsoleClient::Pointer(new ConsoleClient(variable_map["server"].as<std::string>(), variable_map["port"].as<unsigned int>()));
  252.     }
  253.     catch (std::runtime_error& e)
  254.     {
  255.         std::cerr << "Connection error: " << e.what() << std::endl;
  256.         CleanUp();
  257.         return EXIT_FAILURE;
  258.     }
  259.    
  260.     if (variable_map["command"].as<std::string>() != "")
  261.     {
  262.         boost::mutex::scoped_lock guard(guard_mutex);
  263.         on_message_condition.wait(guard);
  264.        
  265.         if (!finish)
  266.         {
  267.             cc->SendResponse(variable_map["command"].as<std::string>());
  268.            
  269.             if (!finish)
  270.             {
  271.                 on_message_condition.wait(guard);
  272.             }
  273.         }
  274.     }
  275.     else
  276.     {
  277.         while (true)
  278.         {
  279.             boost::mutex::scoped_lock guard(guard_mutex);
  280.             on_message_condition.wait(guard);
  281.            
  282.             if (finish)
  283.             {
  284.                 break;
  285.             }
  286.            
  287.             while ((buffer = readline(cc->GetPrompt().data())) != NULL)
  288.             {
  289.                 if (finish)
  290.                 {
  291.                     break;
  292.                 }
  293.                
  294.                 if (strlen(buffer) == 0)
  295.                 {
  296.                     continue;
  297.                 }
  298.                
  299.                 break;
  300.             }
  301.            
  302.             if (finish)
  303.             {
  304.                 break;
  305.             }
  306.            
  307.             cc->SendResponse(buffer);
  308.             add_history(buffer);
  309.         }
  310.     }
  311.    
  312.     CleanUp();
  313.    
  314.     return EXIT_SUCCESS;
  315. }
  316.  
  317. static char** AutoComplete(const char* text, int start, int end)
  318. {
  319.     unsigned int count = 0;
  320.     boost::mutex guard_mutex;
  321.  
  322.     for (unsigned int n = 0; n < start; n++)
  323.     {
  324.         if (rl_line_buffer[n] == ' ')
  325.         {
  326.             count++;
  327.         }
  328.     }
  329.    
  330.     cc->AutoCompleteRequest(count, rl_line_buffer);
  331.    
  332.     boost::mutex::scoped_lock guard(guard_mutex);
  333.     on_message_condition.wait(guard);
  334.    
  335.     /*if (autocomplete_list.size() == 0)
  336.     {
  337.         return NULL;
  338.     }*/
  339.    
  340.     return rl_completion_matches(text, &AutoCompleteGet);
  341. }
  342.  
  343. char* AutoCompleteGet(const char* text, int state)
  344. {
  345.     static int index = 0;
  346.     int length = strlen(text);
  347.     std::string name;
  348.    
  349.     if (!state) // First run
  350.     {
  351.         index = 0;
  352.     }
  353.    
  354.     while (autocomplete_list.size() > index)
  355.     {
  356.         name = autocomplete_list[index];
  357.        
  358.         index++;
  359.        
  360.         if (strncmp(name.data(), text, length) == 0)
  361.         {
  362.             char *result = (char*)malloc(name.size() + 1);
  363.             strcpy(result, name.data());
  364.            
  365.             return result;
  366.         }
  367.     }
  368.    
  369.     return NULL;
  370. }
  371.  
  372. void CleanUp()
  373. {
  374.     std::cout << std::endl;
  375.     //std::cout << "Cleaning up..." << std::endl;
  376.  
  377.     write_history(history_filename.data());
  378.    
  379.     cc.reset();
  380.    
  381.     net::Manager::Delete();
  382.    
  383.     if (buffer != NULL)
  384.     {
  385.         free(buffer);
  386.     }
  387.    
  388.     //std::cout << "Thank you for using Atom. Goodbye!" << std::endl;
  389.    
  390.     tcsetattr(fileno(stdin), TCSANOW, &original_flags); // Restore
  391. }
  392.  
  393. void Handler(int status)
  394. {
  395.     std::string signal_name = "Unknown";
  396.    
  397.     switch (status)
  398.     {
  399.         case SIGTERM:
  400.         {
  401.             signal_name = "Terminate";
  402.             break;
  403.         }  
  404.         case SIGINT:
  405.         {
  406.             signal_name = "Interupt";
  407.             break;
  408.         }  
  409.         case SIGQUIT:
  410.         {
  411.             signal_name = "Quit";
  412.             break;
  413.         }  
  414.         case SIGABRT:
  415.         {
  416.             signal_name = "Abort";
  417.             break;
  418.         }  
  419.         case SIGIO:
  420.         {
  421.             signal_name = "I/O";
  422.             break;
  423.         }  
  424.         case SIGPIPE:
  425.         {
  426.             signal_name = "Pipe";
  427.             break;
  428.         }
  429.     }
  430.    
  431.    
  432.     if (status != SIGPIPE)
  433.     {
  434.         CleanUp();
  435.         exit(0);
  436.     }
  437. }