Subversion Repositories HomeAutomation

Rev

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

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