Subversion Repositories HomeAutomation

Rev

Rev 1642 | Rev 1649 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | SVN | RSS feed

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