Subversion Repositories HomeAutomation

Rev

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

Rev 1656 Rev 1657
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 "Manager.h"
21
#include "Manager.h"
22
 
22
 
23
#include <fstream>
23
#include <fstream>
24
 
24
 
25
#include <boost/lexical_cast.hpp>
25
#include <boost/lexical_cast.hpp>
26
#include <boost/bind.hpp>
26
#include <boost/bind.hpp>
27
 
27
 
28
namespace atom {
28
namespace atom {
29
namespace vm {
29
namespace vm {
30
 
30
 
31
Manager::Pointer Manager::instance_;
31
Manager::Pointer Manager::instance_;
32
 
32
 
33
Manager::Manager() : LOG("vm::Manager")
33
Manager::Manager() : LOG("vm::Manager")
34
{
34
{
35
}
35
}
36
 
36
 
37
Manager::~Manager()
37
Manager::~Manager()
38
{
38
{
39
    this->io_service_.stop();
39
    this->io_service_.stop();
40
   
40
   
41
    this->plugins_.clear();
41
    this->plugins_.clear();
42
    this->context_.Dispose();
42
    this->context_.Dispose();
43
 
43
 
44
    for (ImportFunctionList::iterator it = this->functions_.begin(); it != this->functions_.end(); it++)
44
    for (ImportFunctionList::iterator it = this->functions_.begin(); it != this->functions_.end(); it++)
45
    {
45
    {
46
        it->second.Dispose();
46
        it->second.Dispose();
47
    }
47
    }
48
}
48
}
49
 
49
 
50
void Manager::Create()
50
void Manager::Create()
51
{
51
{
52
    Manager::instance_ = Manager::Pointer(new Manager());
52
    Manager::instance_ = Manager::Pointer(new Manager());
53
}
53
}
54
 
54
 
55
Manager::Pointer Manager::Instance()
55
Manager::Pointer Manager::Instance()
56
{
56
{
57
    return Manager::instance_;
57
    return Manager::instance_;
58
}
58
}
59
 
59
 
60
void Manager::Delete()
60
void Manager::Delete()
61
{
61
{
62
    Manager::instance_.reset();
62
    Manager::instance_.reset();
63
}
63
}
64
 
64
 
65
v8::Persistent<v8::Context>& Manager::GetContext()
65
v8::Persistent<v8::Context>& Manager::GetContext()
66
{
66
{
67
    return this->context_;
67
    return this->context_;
68
}
68
}
69
 
69
 
70
void Manager::AddPlugin(Plugin::Pointer plugin)
70
void Manager::AddPlugin(Plugin::Pointer plugin)
71
{
71
{
72
    this->plugins_.push_back(plugin);
72
    this->plugins_.push_back(plugin);
73
}
73
}
74
 
74
 
75
void Manager::Start(std::string script_path, std::string user_script_path)
75
void Manager::Start(std::string script_path, std::string user_script_path)
76
{
76
{
77
    this->script_path_ = script_path;
77
    this->script_path_ = script_path;
78
    this->user_script_path_ = user_script_path;
78
    this->user_script_path_ = user_script_path;
79
    this->io_service_.post(boost::bind(&Manager::StartHandler, this));
79
    this->io_service_.post(boost::bind(&Manager::StartHandler, this));
80
}
80
}
81
 
81
 
82
void Manager::CallOutput(std::string output)
82
void Manager::CallOutput(std::string output)
83
{
83
{
84
    if (this->current_plugin_name_ != "")
84
    if (this->current_plugin_name_ != "")
85
    {
85
    {
86
        for (unsigned int n = 0; n < this->plugins_.size(); n++)
86
        for (unsigned int n = 0; n < this->plugins_.size(); n++)
87
        {
87
        {
88
            if (this->plugins_[n]->GetName() == this->current_plugin_name_)
88
            if (this->plugins_[n]->GetName() == this->current_plugin_name_)
89
            {
89
            {
90
                this->plugins_[n]->CallOutput(this->current_request_id_, output);
90
                this->plugins_[n]->CallOutput(this->current_request_id_, output);
91
                return;
91
                return;
92
            }
92
            }
93
        }
93
        }
94
    }
94
    }
95
    else
95
    else
96
    {
96
    {
97
        LOG.Info(output);
97
        LOG.Info(output);
98
    }
98
    }
99
}
99
}
100
 
100
 
101
Value Manager::Export_Log(const v8::Arguments& args)
101
Value Manager::Export_Log(const v8::Arguments& args)
102
{
102
{
103
    v8::Context::Scope context_scope(Manager::Instance()->GetContext());
103
    v8::Context::Scope context_scope(Manager::Instance()->GetContext());
104
   
104
   
105
    //LOG.Debug(std::string(__FUNCTION__) + " called!");
105
    //LOG.Debug(std::string(__FUNCTION__) + " called!");
106
   
106
   
107
    if (args.Length() < 1)
107
    if (args.Length() < 1)
108
    {
108
    {
109
        Manager::instance_->LOG.Error(std::string(__FUNCTION__) + ": To few arguments to log.");
109
        Manager::instance_->LOG.Error(std::string(__FUNCTION__) + ": To few arguments to log.");
110
        return v8::Undefined();
110
        return v8::Undefined();
111
    }
111
    }
112
   
112
   
113
    v8::String::AsciiValue str(args[0]);
113
    v8::String::AsciiValue str(args[0]);
114
       
114
       
115
    Manager::instance_->CallOutput(*str);
115
    Manager::instance_->CallOutput(*str);
116
   
116
   
117
    return v8::Undefined();
117
    return v8::Undefined();
118
}
118
}
119
 
119
 
120
void Manager::Call(std::string plugin_name, unsigned int request_id, std::string name, ArgumentListPointer arguments)
120
void Manager::Call(std::string plugin_name, unsigned int request_id, std::string name, ArgumentListPointer arguments)
121
{
121
{
122
    this->io_service_.post(boost::bind(&Manager::CallHandler, this, plugin_name, request_id, name, arguments));
122
    this->io_service_.post(boost::bind(&Manager::CallHandler, this, plugin_name, request_id, name, arguments));
123
}
123
}
124
 
124
 
125
void Manager::Execute(std::string plugin_name, unsigned int request_id, std::string code)
125
void Manager::Execute(std::string plugin_name, unsigned int request_id, std::string code)
126
{
126
{
127
    this->io_service_.post(boost::bind(&Manager::ExecuteHandler, this, plugin_name, request_id, code));
127
    this->io_service_.post(boost::bind(&Manager::ExecuteHandler, this, plugin_name, request_id, code));
128
}
128
}
129
 
129
 
130
bool Manager::CallHandler(std::string plugin_name, unsigned int request_id, std::string name, ArgumentListPointer arguments)
130
bool Manager::CallHandler(std::string plugin_name, unsigned int request_id, std::string name, ArgumentListPointer arguments)
131
{
131
{
132
    v8::Context::Scope context_scope(this->context_);
132
    v8::Context::Scope context_scope(this->context_);
133
    v8::TryCatch try_catch;
133
    v8::TryCatch try_catch;
134
   
134
   
135
    this->current_plugin_name_ = plugin_name;
135
    this->current_plugin_name_ = plugin_name;
136
    this->current_request_id_ = request_id;
136
    this->current_request_id_ = request_id;
137
   
137
   
138
    if (this->functions_.find(name) == this->functions_.end())
138
    if (this->functions_.find(name) == this->functions_.end())
139
    {
139
    {
140
        this->CallOutput("No such function found, " + name);
140
        this->CallOutput("No such function found, " + name);
141
       
141
       
142
        this->current_plugin_name_ = "";
142
        this->current_plugin_name_ = "";
143
        this->current_request_id_ = 0;
143
        this->current_request_id_ = 0;
144
        return false;
144
        return false;
145
    }
145
    }
146
 
146
 
147
    //LOG.Debug("Call: " + name);
147
    //LOG.Debug("Call: " + name);
148
 
148
 
149
    Value result = this->functions_[name]->Call(this->context_->Global(), arguments->size(), arguments->data());
149
    Value result = this->functions_[name]->Call(this->context_->Global(), arguments->size(), arguments->data());
150
   
150
   
151
    if (result.IsEmpty())
151
    if (result.IsEmpty())
152
    {
152
    {
153
        this->CallOutput(this->FormatException(try_catch));
153
        this->CallOutput(this->FormatException(try_catch));
154
       
154
       
155
        this->current_plugin_name_ = "";
155
        this->current_plugin_name_ = "";
156
        this->current_request_id_ = 0;
156
        this->current_request_id_ = 0;
157
        return false;
157
        return false;
158
    }
158
    }
159
   
159
   
160
    //v8::String::AsciiValue response(result->ToString());
160
    //v8::String::AsciiValue response(result->ToString());
161
    //this->CallOutput(plugin_name, request_id, std::string(*response));
161
    //this->CallOutput(plugin_name, request_id, std::string(*response));
162
   
162
   
163
    this->current_plugin_name_ = "";
163
    this->current_plugin_name_ = "";
164
    this->current_request_id_ = 0;
164
    this->current_request_id_ = 0;
165
    return true;
165
    return true;
166
}
166
}
167
 
167
 
168
void Manager::StartHandler()
168
void Manager::StartHandler()
169
{
169
{
170
    v8::Handle<v8::ObjectTemplate> raw_template = v8::ObjectTemplate::New();
170
    v8::Handle<v8::ObjectTemplate> raw_template = v8::ObjectTemplate::New();
171
   
171
   
172
    raw_template->Set(v8::String::New("Log"), v8::FunctionTemplate::New(Manager::Export_Log));
172
    raw_template->Set(v8::String::New("Log"), v8::FunctionTemplate::New(Manager::Export_Log));
173
   
173
   
174
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
174
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
175
    {
175
    {
176
        ExportFunctionList export_functions = this->plugins_[c]->GetExportFunctions();
176
        ExportFunctionList export_functions = this->plugins_[c]->GetExportFunctions();
177
       
177
       
178
        for (ExportFunctionList::iterator it = export_functions.begin(); it != export_functions.end(); it++)
178
        for (ExportFunctionList::iterator it = export_functions.begin(); it != export_functions.end(); it++)
179
        {
179
        {
180
            raw_template->Set(v8::String::New(it->first.data()), v8::FunctionTemplate::New(it->second));
180
            raw_template->Set(v8::String::New(it->first.data()), v8::FunctionTemplate::New(it->second));
181
        }
181
        }
182
    }
182
    }
183
   
183
   
184
    this->context_ = v8::Context::New(NULL, raw_template);
184
    this->context_ = v8::Context::New(NULL, raw_template);
185
   
185
   
186
    v8::Context::Scope context_scope(this->context_);
186
    v8::Context::Scope context_scope(this->context_);
187
   
187
   
188
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
188
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
189
    {
189
    {
190
        this->LoadScript("plugin/" + this->plugins_[c]->GetName() + ".js");
190
        this->LoadScript("plugin/" + this->plugins_[c]->GetName() + ".js");
191
    }
191
    }
192
   
192
   
193
    this->object_template_ = v8::Persistent<v8::ObjectTemplate>::New(raw_template);
193
    this->object_template_ = v8::Persistent<v8::ObjectTemplate>::New(raw_template);
194
   
194
   
195
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
195
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
196
    {
196
    {
197
        this->plugins_[c]->InitializeDone();
197
        this->plugins_[c]->InitializeDone();
198
    }
198
    }
199
   
-
 
200
    LOG.Info("VM initialized.");
-
 
201
}
199
}
202
 
200
 
203
bool Manager::ImportFunction(std::string functionname)
201
bool Manager::ImportFunction(std::string functionname)
204
{
202
{
205
    v8::Context::Scope context_scope(this->context_);
203
    v8::Context::Scope context_scope(this->context_);
206
   
204
   
207
    v8::TryCatch try_catch;
205
    v8::TryCatch try_catch;
208
   
206
   
209
    v8::Handle<v8::String> process_name = v8::String::New(functionname.data());
207
    v8::Handle<v8::String> process_name = v8::String::New(functionname.data());
210
    v8::Handle<v8::Value> process_val = this->context_->Global()->Get(process_name);
208
    v8::Handle<v8::Value> process_val = this->context_->Global()->Get(process_name);
211
   
209
   
212
    if (!process_val->IsFunction())
210
    if (!process_val->IsFunction())
213
    {
211
    {
214
        LOG.Error(functionname + " was not found to be a function!");
212
        LOG.Error(functionname + " was not found to be a function!");
215
        return false;
213
        return false;
216
    }
214
    }
217
   
215
   
218
    v8::Handle<v8::Function> process_fun = v8::Handle<v8::Function>::Cast(process_val);
216
    v8::Handle<v8::Function> process_fun = v8::Handle<v8::Function>::Cast(process_val);
219
   
217
   
220
    this->functions_[functionname] = v8::Persistent<v8::Function>::New(process_fun);
218
    this->functions_[functionname] = v8::Persistent<v8::Function>::New(process_fun);
221
   
219
   
222
    return true;
220
    return true;
223
}
221
}
224
 
222
 
225
bool Manager::LoadScript(std::string scriptname)
223
bool Manager::LoadScript(std::string scriptname)
226
{
224
{
227
    for (unsigned int n = 0; n < this->loaded_scripts_.size(); n++)
225
    for (unsigned int n = 0; n < this->loaded_scripts_.size(); n++)
228
    {
226
    {
229
        if (this->loaded_scripts_[n] == scriptname)
227
        if (this->loaded_scripts_[n] == scriptname)
230
        {
228
        {
231
            LOG.Info(scriptname + " is already loaded.");
229
            LOG.Debug(scriptname + " is already loaded.");
232
            return true;
230
            return true;
233
        }
231
        }
234
    }
232
    }
235
   
233
   
236
    std::string path = this->user_script_path_ + scriptname;
234
    std::string path = this->user_script_path_ + scriptname;
237
    std::ifstream file(path.data());
235
    std::ifstream file(path.data());
238
   
236
   
239
    if (!file.is_open())
237
    if (!file.is_open())
240
    {
238
    {
241
        path = this->script_path_ + scriptname;
239
        path = this->script_path_ + scriptname;
242
        file.open(path.data());
240
        file.open(path.data());
243
       
241
       
244
        if (!file.is_open())
242
        if (!file.is_open())
245
        {
243
        {
246
            file.close();
244
            file.close();
247
            LOG.Warning("Could not load " + scriptname + ".");
245
            LOG.Warning("Could not load " + scriptname + ".");
248
            return false;
246
            return false;
249
        }
247
        }
250
    }
248
    }
251
   
249
   
252
    std::string code = "";
250
    std::string code = "";
253
    std::string line;
251
    std::string line;
254
   
252
   
255
    while (!file.eof())
253
    while (!file.eof())
256
    {
254
    {
257
        std::getline(file, line);
255
        std::getline(file, line);
258
       
256
       
259
        if (file.eof())
257
        if (file.eof())
260
        {
258
        {
261
            break;
259
            break;
262
        }
260
        }
263
       
261
       
264
        code += line + "\n";
262
        code += line + "\n";
265
    }
263
    }
266
   
264
   
267
    code += "\n";
265
    code += "\n";
268
   
266
   
269
    file.close();
267
    file.close();
270
   
268
   
271
    v8::Context::Scope context_scope(this->context_);
269
    v8::Context::Scope context_scope(this->context_);
272
   
270
   
273
    v8::TryCatch try_catch;
271
    v8::TryCatch try_catch;
274
   
272
   
275
    v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(code.data(), code.length()),
273
    v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(code.data(), code.length()),
276
                                                        v8::String::New(scriptname.data(), scriptname.length()));
274
                                                        v8::String::New(scriptname.data(), scriptname.length()));
277
   
275
   
278
    if (script.IsEmpty())
276
    if (script.IsEmpty())
279
    {
277
    {
280
        LOG.Error(this->FormatException(try_catch));
278
        LOG.Error(this->FormatException(try_catch));
281
        return false;
279
        return false;
282
    }
280
    }
283
    else
281
    else
284
    {
282
    {
285
        Value result = script->Run();
283
        Value result = script->Run();
286
       
284
       
287
        if (result.IsEmpty())
285
        if (result.IsEmpty())
288
        {
286
        {
289
            LOG.Error(this->FormatException(try_catch));
287
            LOG.Error(this->FormatException(try_catch));
290
            return false;
288
            return false;
291
        }
289
        }
292
    }
290
    }
293
   
291
   
294
    this->loaded_scripts_.push_back(scriptname);
292
    this->loaded_scripts_.push_back(scriptname);
295
   
293
   
296
    LOG.Info("Loaded " + scriptname + " successfully.");
294
    LOG.Info("\033[32mLoaded " + scriptname + " successfully.\033[0m");
297
    return true;
295
    return true;
298
}
296
}
299
 
297
 
300
void Manager::ExecuteHandler(std::string plugin_name, unsigned int request_id, std::string code)
298
void Manager::ExecuteHandler(std::string plugin_name, unsigned int request_id, std::string code)
301
{
299
{
302
    std::string scriptname = "execute_" + plugin_name + ".js";
300
    std::string scriptname = "execute_" + plugin_name + ".js";
303
   
301
   
304
    v8::Context::Scope context_scope(this->context_);
302
    v8::Context::Scope context_scope(this->context_);
305
   
303
   
306
    v8::TryCatch try_catch;
304
    v8::TryCatch try_catch;
307
   
305
   
308
    v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(code.data(), code.length()),
306
    v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(code.data(), code.length()),
309
                                                        v8::String::New(scriptname.data(), scriptname.length()));
307
                                                        v8::String::New(scriptname.data(), scriptname.length()));
310
   
308
   
311
    this->current_plugin_name_ = plugin_name;
309
    this->current_plugin_name_ = plugin_name;
312
    this->current_request_id_ = request_id;
310
    this->current_request_id_ = request_id;
313
   
311
   
314
    if (script.IsEmpty())
312
    if (script.IsEmpty())
315
    {
313
    {
316
        this->CallOutput(this->FormatException(try_catch));
314
        this->CallOutput(this->FormatException(try_catch));
317
    }
315
    }
318
    else
316
    else
319
    {
317
    {
320
        Value result = script->Run();
318
        Value result = script->Run();
321
       
319
       
322
        if (result.IsEmpty())
320
        if (result.IsEmpty())
323
        {
321
        {
324
            this->CallOutput(this->FormatException(try_catch));
322
            this->CallOutput(this->FormatException(try_catch));
325
        }
323
        }
326
        else
324
        else
327
        {
325
        {
328
            //v8::String::AsciiValue response(result->ToString());
326
            //v8::String::AsciiValue response(result->ToString());
329
            //this->CallOutput(std::string(*response));
327
            //this->CallOutput(std::string(*response));
330
        }
328
        }
331
    }
329
    }
332
   
330
   
333
    this->current_plugin_name_ = "";
331
    this->current_plugin_name_ = "";
334
    this->current_request_id_ = 0;
332
    this->current_request_id_ = 0;
335
}
333
}
336
 
334
 
337
std::string Manager::FormatException(v8::TryCatch& try_catch)
335
std::string Manager::FormatException(v8::TryCatch& try_catch)
338
{
336
{
339
    v8::Context::Scope context_scope(this->context_);
337
    v8::Context::Scope context_scope(this->context_);
340
   
338
   
341
    std::string result;
339
    std::string result;
342
   
340
   
343
    v8::HandleScope handle_scope;
341
    v8::HandleScope handle_scope;
344
    v8::String::Utf8Value exception(try_catch.Exception());
342
    v8::String::Utf8Value exception(try_catch.Exception());
345
    v8::Handle<v8::Message> message = try_catch.Message();
343
    v8::Handle<v8::Message> message = try_catch.Message();
346
   
344
   
347
    if (message.IsEmpty())
345
    if (message.IsEmpty())
348
    {
346
    {
349
        result = *exception;
347
        result = *exception;
350
    }
348
    }
351
    else
349
    else
352
    {
350
    {
353
        v8::String::Utf8Value filename(message->GetScriptResourceName());
351
        v8::String::Utf8Value filename(message->GetScriptResourceName());
354
       
352
       
355
        result = std::string(*filename) + ":" + boost::lexical_cast<std::string>(message->GetLineNumber()) + ": " + std::string(*exception);
353
        result = std::string(*filename) + ":" + boost::lexical_cast<std::string>(message->GetLineNumber()) + ": " + std::string(*exception);
356
       
354
       
357
        /*v8::String::Utf8Value sourceline(message->GetSourceLine());
355
        /*v8::String::Utf8Value sourceline(message->GetSourceLine());
358
        string strSourceline = *sourceline;
356
        string strSourceline = *sourceline;
359
       
357
       
360
        result += strSourceline + "\n";
358
        result += strSourceline + "\n";
361
       
359
       
362
        string underline = rpad("", message->GetStartColumn(), ' ');
360
        string underline = rpad("", message->GetStartColumn(), ' ');
363
        underline = rpad(underline, message->GetEndColumn(), '^');
361
        underline = rpad(underline, message->GetEndColumn(), '^');
364
       
362
       
365
        result += underline + "\n";*/
363
        result += underline + "\n";*/
366
    }
364
    }
367
   
365
   
368
    return result;
366
    return result;
369
}
367
}
370
   
368
   
371
}; // namespace vm
369
}; // namespace vm
372
}; // namespace atom
370
}; // namespace atom
373
 
371