Subversion Repositories HomeAutomation

Rev

Rev 1649 | Rev 1657 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | SVN | RSS feed

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