Subversion Repositories HomeAutomation

Rev

Rev 983 | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | SVN | RSS feed

Rev 983 Rev 986
1
/***************************************************************************
1
/***************************************************************************
2
 *   Copyright (C) December 10, 2008 by Mattias Runge                             *
2
 *   Copyright (C) December 10, 2008 by Mattias Runge                             *
3
 *   mattias@runge.se                                                      *
3
 *   mattias@runge.se                                                      *
4
 *   virtualmachine.cpp                                            *
4
 *   virtualmachine.cpp                                            *
5
 *                                                                         *
5
 *                                                                         *
6
 *   This program is free software; you can redistribute it and/or modify  *
6
 *   This program is free software; you can redistribute it and/or modify  *
7
 *   it under the terms of the GNU General Public License as published by  *
7
 *   it under the terms of the GNU General Public License as published by  *
8
 *   the Free Software Foundation; either version 2 of the License, or     *
8
 *   the Free Software Foundation; either version 2 of the License, or     *
9
 *   (at your option) any later version.                                   *
9
 *   (at your option) any later version.                                   *
10
 *                                                                         *
10
 *                                                                         *
11
 *   This program is distributed in the hope that it will be useful,       *
11
 *   This program is distributed in the hope that it will be useful,       *
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14
 *   GNU General Public License for more details.                          *
14
 *   GNU General Public License for more details.                          *
15
 *                                                                         *
15
 *                                                                         *
16
 *   You should have received a copy of the GNU General Public License     *
16
 *   You should have received a copy of the GNU General Public License     *
17
 *   along with this program; if not, write to the                         *
17
 *   along with this program; if not, write to the                         *
18
 *   Free Software Foundation, Inc.,                                       *
18
 *   Free Software Foundation, Inc.,                                       *
19
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
20
 ***************************************************************************/
20
 ***************************************************************************/
21
 
21
 
22
#include "virtualmachine.h"
22
#include "virtualmachine.h"
23
 
23
 
24
VirtualMachine* VirtualMachine::myInstance = NULL;
24
VirtualMachine* VirtualMachine::myInstance = NULL;
25
 
25
 
26
VirtualMachine& VirtualMachine::getInstance()
26
VirtualMachine& VirtualMachine::getInstance()
27
{
27
{
28
    if (myInstance == NULL)
28
    if (myInstance == NULL)
29
    {
29
    {
30
        myInstance = new VirtualMachine();
30
        myInstance = new VirtualMachine();
31
    }
31
    }
32
 
32
 
33
    return *myInstance;
33
    return *myInstance;
34
}
34
}
35
 
35
 
36
void VirtualMachine::deleteInstance()
36
void VirtualMachine::deleteInstance()
37
{
37
{
38
    if (myInstance != NULL)
38
    if (myInstance != NULL)
39
    {
39
    {
40
        delete myInstance;
40
        delete myInstance;
41
        myInstance = NULL;
41
        myInstance = NULL;
42
    }
42
    }
43
}
43
}
44
 
44
 
45
VirtualMachine::VirtualMachine()
45
VirtualMachine::VirtualMachine()
46
{
46
{
47
    Thread<VirtualMachine>();
47
    Thread<VirtualMachine>();
48
}
48
}
49
 
49
 
50
VirtualMachine::~VirtualMachine()
50
VirtualMachine::~VirtualMachine()
51
{
51
{
52
    stop();
52
    stop();
53
}
53
}
54
 
54
 
55
void VirtualMachine::run()
55
void VirtualMachine::run()
56
{
56
{
57
    SyslogStream &slog = SyslogStream::getInstance();
57
    SyslogStream &slog = SyslogStream::getInstance();
58
 
58
 
59
    string basePath = Settings::get("BasePath") + "Services/";
59
    string basePath = Settings::get("BasePath") + "Services/";
60
    string scriptName = "Base.js";
60
    string scriptName = "Base.js";
61
    string scriptFileName = basePath + "System/" + scriptName;
61
    string scriptFileName = basePath + "System/" + scriptName;
62
 
62
 
63
    if (!file_exists(scriptFileName))
63
    if (!file_exists(scriptFileName))
64
    {
64
    {
65
        slog << "Failed to load :" + scriptFileName + "\n";
65
        slog << "Failed to load :" + scriptFileName + "\n";
66
    }
66
    }
67
 
67
 
68
    string scriptSource = file_get_contents(scriptFileName);
68
    string scriptSource = file_get_contents(scriptFileName);
69
 
69
 
70
    Handle<String> source =  String::New(scriptSource.c_str(), scriptSource.length());
70
    Handle<String> source =  String::New(scriptSource.c_str(), scriptSource.length());
71
    //each script name must be unique , for this demo I just run one embedded script, so the name can be fixed
71
    //each script name must be unique , for this demo I just run one embedded script, so the name can be fixed
72
    Handle<String> name = String::New(scriptName.c_str(), scriptName.length());
72
    Handle<String> name = String::New(scriptName.c_str(), scriptName.length());
73
 
73
 
74
    // Create a template for the global object.
74
    // Create a template for the global object.
75
    myGlobal = ObjectTemplate::New();
75
    myGlobal = ObjectTemplate::New();
76
 
76
 
77
    //associates "print" on script to the Print function
77
    //associates "print" on script to the Print function
78
    myGlobal->Set(String::New("log"), FunctionTemplate::New(VirtualMachine_log));
78
    myGlobal->Set(String::New("log"), FunctionTemplate::New(VirtualMachine_log));
79
    myGlobal->Set(String::New("sendCanMessage"), FunctionTemplate::New(VirtualMachine_sendCanMessage));
79
    myGlobal->Set(String::New("sendCanMessage"), FunctionTemplate::New(VirtualMachine_sendCanMessage));
-
 
80
    myGlobal->Set(String::New("sendCanNMTMessage"), FunctionTemplate::New(VirtualMachine_sendCanNMTMessage));
80
    myGlobal->Set(String::New("loadScript"), FunctionTemplate::New(VirtualMachine_loadScript));
81
    myGlobal->Set(String::New("loadScript"), FunctionTemplate::New(VirtualMachine_loadScript));
81
    myGlobal->Set(String::New("startIntervalThread"), FunctionTemplate::New(VirtualMachine_startIntervalThread));
82
    myGlobal->Set(String::New("startIntervalThread"), FunctionTemplate::New(VirtualMachine_startIntervalThread));
82
    myGlobal->Set(String::New("stopIntervalThread"), FunctionTemplate::New(VirtualMachine_stopIntervalThread));
83
    myGlobal->Set(String::New("stopIntervalThread"), FunctionTemplate::New(VirtualMachine_stopIntervalThread));
83
    myGlobal->Set(String::New("startSocketThread"), FunctionTemplate::New(VirtualMachine_startSocketThread));
84
    myGlobal->Set(String::New("startSocketThread"), FunctionTemplate::New(VirtualMachine_startSocketThread));
84
    myGlobal->Set(String::New("stopSocketThread"), FunctionTemplate::New(VirtualMachine_stopSocketThread));
85
    myGlobal->Set(String::New("stopSocketThread"), FunctionTemplate::New(VirtualMachine_stopSocketThread));
85
    myGlobal->Set(String::New("sendToSocketThread"), FunctionTemplate::New(VirtualMachine_sendToSocketThread));
86
    myGlobal->Set(String::New("sendToSocketThread"), FunctionTemplate::New(VirtualMachine_sendToSocketThread));
86
    myGlobal->Set(String::New("uint2hex"), FunctionTemplate::New(VirtualMachine_uint2hex));
87
    myGlobal->Set(String::New("uint2hex"), FunctionTemplate::New(VirtualMachine_uint2hex));
87
 
88
 
88
    //create context for the script
89
    //create context for the script
89
    myContext = Context::New(NULL, myGlobal);
90
    myContext = Context::New(NULL, myGlobal);
90
 
91
 
91
 
92
 
92
    //access global context within this scope
93
    //access global context within this scope
93
    Context::Scope context_scope(myContext);
94
    Context::Scope context_scope(myContext);
94
    //exception handler
95
    //exception handler
95
    TryCatch try_catch;
96
    TryCatch try_catch;
96
    //compile script to binary code - JIT
97
    //compile script to binary code - JIT
97
    Handle<Script> script = Script::Compile(source, name);
98
    Handle<Script> script = Script::Compile(source, name);
98
 
99
 
99
    //check if we got problems on compilation
100
    //check if we got problems on compilation
100
    if (script.IsEmpty())
101
    if (script.IsEmpty())
101
    {
102
    {
102
 
103
 
103
        // Print errors that happened during compilation.
104
        // Print errors that happened during compilation.
104
        String::AsciiValue error(try_catch.Exception());
105
        String::AsciiValue error(try_catch.Exception());
105
        string sError = *error;
106
        string sError = *error;
106
        slog << "Failed to compile script: " + sError + "\n";
107
        slog << "Failed to compile script: " + sError + "\n";
107
    }
108
    }
108
    else
109
    else
109
    {
110
    {
110
        //no errors , let's continue
111
        //no errors , let's continue
111
        Handle<Value> result = script->Run();
112
        Handle<Value> result = script->Run();
112
 
113
 
113
        //check if execution ended with errors
114
        //check if execution ended with errors
114
        if (result.IsEmpty())
115
        if (result.IsEmpty())
115
        {
116
        {
116
            // Print errors that happened during execution.
117
            // Print errors that happened during execution.
117
            String::AsciiValue error(try_catch.Exception());
118
            String::AsciiValue error(try_catch.Exception());
118
            string sError = *error;
119
            string sError = *error;
119
            slog << "Constructor: Failed to run script: " << sError << "\n";
120
            slog << "Constructor: Failed to run script: " << sError << "\n";
120
        }
121
        }
121
        else
122
        else
122
        {
123
        {
123
            loadScript("System/Startup.js");
124
            loadScript("System/Startup.js");
124
 
125
 
125
            if (file_exists(basePath + "Autostart.js"))
126
            if (file_exists(basePath + "Autostart.js"))
126
            {
127
            {
127
                loadScript("Autostart.js");
128
                loadScript("Autostart.js");
128
            }
129
            }
129
           
130
           
130
            myFunctionHandleHeartbeat = Handle<Function>::Cast(myContext->Global()->Get(String::New("handleHeartbeat")));
131
            myFunctionHandleNMTMessage = Handle<Function>::Cast(myContext->Global()->Get(String::New("handleNMTMessage")));
131
            myFunctionOfflineCheck = Handle<Function>::Cast(myContext->Global()->Get(String::New("offlineCheck")));
132
            myFunctionOfflineCheck = Handle<Function>::Cast(myContext->Global()->Get(String::New("offlineCheck")));
132
            myFunctionHandleMessage = Handle<Function>::Cast(myContext->Global()->Get(String::New("handleMessage")));
133
            myFunctionHandleMessage = Handle<Function>::Cast(myContext->Global()->Get(String::New("handleMessage")));
133
            myFunctionStartup = Handle<Function>::Cast(myContext->Global()->Get(String::New("startup")));
134
            myFunctionStartup = Handle<Function>::Cast(myContext->Global()->Get(String::New("startup")));
134
        }
135
        }
135
    }
136
    }
136
 
137
 
137
    const int argc = 0;
138
    const int argc = 0;
138
    Handle<Value> argv[argc] = { };
139
    Handle<Value> argv[argc] = { };
139
 
140
 
140
    Handle<Value> result = myFunctionStartup->Call(myFunctionStartup, argc, argv); // argc and argv are your standard arguments to a function
141
    Handle<Value> result = myFunctionStartup->Call(myFunctionStartup, argc, argv); // argc and argv are your standard arguments to a function
141
 
142
 
142
    mySemaphore.lock();
143
    mySemaphore.lock();
143
 
144
 
144
    while (1)
145
    while (1)
145
    {
146
    {
146
        string expression;
147
        string expression;
147
 
148
 
148
        while (myExpressions.size() > 0)
149
        while (myExpressions.size() > 0)
149
        {
150
        {
150
            expression = myExpressions.pop();
151
            expression = myExpressions.pop();
151
 
152
 
152
            runExpression(expression);
153
            runExpression(expression);
153
        }
154
        }
154
 
155
 
155
        CanMessage canMessage;
156
        CanMessage canMessage;
156
 
157
 
157
        while (myCanMessages.size() > 0)
158
        while (myCanMessages.size() > 0)
158
        {
159
        {
159
            canMessage = myCanMessages.pop();
160
            canMessage = myCanMessages.pop();
160
 
161
 
161
            if (canMessage.isHeartbeat())
162
            if (canMessage.getClassName() == "nmt")
162
            {
163
            {
163
                callHandleHeartbeat(stoi(canMessage.getData()["HardwareId"].getValue()));
164
                callHandleNMTMessage(canMessage);
164
            }
165
            }
165
            else
166
            else
166
            {
167
            {
167
                callHandleMessage(canMessage);
168
                callHandleMessage(canMessage);
168
            }
169
            }
169
        }
170
        }
170
 
171
 
171
        mySemaphore.wait();
172
        mySemaphore.wait();
172
    }
173
    }
173
 
174
 
174
    mySemaphore.unlock();
175
    mySemaphore.unlock();
175
}
176
}
176
 
177
 
177
void VirtualMachine::queueCanMessage(CanMessage canMessage)
178
void VirtualMachine::queueCanMessage(CanMessage canMessage)
178
{
179
{
179
    myCanMessages.push(canMessage);
180
    myCanMessages.push(canMessage);
180
    mySemaphore.broadcast();
181
    mySemaphore.broadcast();
181
}
182
}
182
 
183
 
183
void VirtualMachine::queueExpression(string expression)
184
void VirtualMachine::queueExpression(string expression)
184
{
185
{
185
    myExpressions.push(expression);
186
    myExpressions.push(expression);
186
    mySemaphore.broadcast();
187
    mySemaphore.broadcast();
187
}
188
}
188
 
189
 
189
bool VirtualMachine::loadScript(string scriptName)
190
bool VirtualMachine::loadScript(string scriptName)
190
{
191
{
191
    SyslogStream &slog = SyslogStream::getInstance();
192
    SyslogStream &slog = SyslogStream::getInstance();
192
 
193
 
193
    string basePath = Settings::get("BasePath") + "Services/";
194
    string basePath = Settings::get("BasePath") + "Services/";
194
    string scriptFileName = basePath + scriptName;
195
    string scriptFileName = basePath + scriptName;
195
 
196
 
196
    if (!file_exists(scriptFileName))
197
    if (!file_exists(scriptFileName))
197
    {
198
    {
198
        slog << "Failed to load " + scriptFileName + "\n";
199
        slog << "Failed to load " + scriptFileName + "\n";
199
        return false;
200
        return false;
200
    }
201
    }
201
 
202
 
202
    string scriptSource = file_get_contents(scriptFileName);
203
    string scriptSource = file_get_contents(scriptFileName);
203
 
204
 
204
    Handle<String> source =  String::New(scriptSource.c_str(), scriptSource.length());
205
    Handle<String> source =  String::New(scriptSource.c_str(), scriptSource.length());
205
    //each script name must be unique , for this demo I just run one embedded script, so the name can be fixed
206
    //each script name must be unique , for this demo I just run one embedded script, so the name can be fixed
206
    Handle<String> name = String::New(scriptName.c_str(), scriptName.length());
207
    Handle<String> name = String::New(scriptName.c_str(), scriptName.length());
207
 
208
 
208
    //access global context within this scope
209
    //access global context within this scope
209
    Context::Scope context_scope(myContext);
210
    Context::Scope context_scope(myContext);
210
    //exception handler
211
    //exception handler
211
    TryCatch try_catch;
212
    TryCatch try_catch;
212
    //compile script to binary code - JIT
213
    //compile script to binary code - JIT
213
    Handle<Script> script = Script::Compile(source, name);
214
    Handle<Script> script = Script::Compile(source, name);
214
 
215
 
215
    //check if we got problems on compilation
216
    //check if we got problems on compilation
216
    if (script.IsEmpty())
217
    if (script.IsEmpty())
217
    {
218
    {
218
        // Print errors that happened during compilation.
219
        // Print errors that happened during compilation.
219
        String::AsciiValue error(try_catch.Exception());
220
        String::AsciiValue error(try_catch.Exception());
220
        string sError = *error;
221
        string sError = *error;
221
        slog << "loadScript: Failed to compile script: " + sError + "\n";
222
        slog << "loadScript: Failed to compile script: " + sError + "\n";
222
        return false;
223
        return false;
223
    }
224
    }
224
    else
225
    else
225
    {
226
    {
226
        //no errors , let's continue
227
        //no errors , let's continue
227
        Handle<Value> result = script->Run();
228
        Handle<Value> result = script->Run();
228
 
229
 
229
        //check if execution ended with errors
230
        //check if execution ended with errors
230
        if (result.IsEmpty())
231
        if (result.IsEmpty())
231
        {
232
        {
232
            // Print errors that happened during execution.
233
            // Print errors that happened during execution.
233
            String::AsciiValue error(try_catch.Exception());
234
            String::AsciiValue error(try_catch.Exception());
234
            string sError = *error;
235
            string sError = *error;
235
            slog << "loadScript: Failed to run script: " + sError + "\n";
236
            slog << "loadScript: Failed to run script: " + sError + "\n";
236
            return false;
237
            return false;
237
        }
238
        }
238
 
239
 
239
        slog << "Loaded " + scriptName + "\n";
240
        slog << "Loaded " + scriptName + "\n";
240
    }
241
    }
241
 
242
 
242
    return true;
243
    return true;
243
}
244
}
244
 
245
 
245
void VirtualMachine::callHandleHeartbeat(int hardwareId)
246
void VirtualMachine::callHandleNMTMessage(CanMessage canMessage)
246
{
247
{
247
    const int argc = 1;
248
    const int argc = 3;
248
    Handle<Value> argv[argc] = { Integer::New(hardwareId) };
-
 
249
 
249
 
-
 
250
    string jsonData = canMessage.getJSONData();
-
 
251
 
-
 
252
    Handle<Value> argv[argc] = {String::New(canMessage.getClassName().c_str()),
-
 
253
                                String::New(canMessage.getCommandName().c_str()),
-
 
254
                                String::New(jsonData.c_str()) };
-
 
255
 
250
    Handle<Value> result = myFunctionHandleHeartbeat->Call(myFunctionHandleHeartbeat, argc, argv); // argc and argv are your standard arguments to a function
256
    Handle<Value> result = myFunctionHandleNMTMessage->Call(myFunctionHandleNMTMessage, argc, argv); // argc and argv are your standard arguments to a function
251
}
257
}
252
 
258
 
253
void VirtualMachine::callHandleMessage(CanMessage canMessage)
259
void VirtualMachine::callHandleMessage(CanMessage canMessage)
254
{
260
{
255
    const int argc = 6;
261
    const int argc = 6;
256
 
262
 
257
    string jsonData = canMessage.getJSONData();
263
    string jsonData = canMessage.getJSONData();
258
 
264
 
259
    Handle<Value> argv[argc] = {String::New(canMessage.getClassName().c_str()),
265
    Handle<Value> argv[argc] = {String::New(canMessage.getClassName().c_str()),
260
                                String::New(canMessage.getDirectionFlag().c_str()),
266
                                String::New(canMessage.getDirectionFlag().c_str()),
261
                                String::New(canMessage.getModuleName().c_str()),
267
                                String::New(canMessage.getModuleName().c_str()),
262
                                Integer::New(canMessage.getModuleId()),
268
                                Integer::New(canMessage.getModuleId()),
263
                                String::New(canMessage.getCommandName().c_str()),
269
                                String::New(canMessage.getCommandName().c_str()),
264
                                String::New(jsonData.c_str()) };
270
                                String::New(jsonData.c_str()) };
265
 
271
 
266
    Handle<Value> result = myFunctionHandleMessage->Call(myFunctionHandleMessage, argc, argv); // argc and argv are your standard arguments to a function
272
    Handle<Value> result = myFunctionHandleMessage->Call(myFunctionHandleMessage, argc, argv); // argc and argv are your standard arguments to a function
267
}
273
}
268
 
274
 
269
unsigned int VirtualMachine::startIntervalThread(unsigned int timeout)
275
unsigned int VirtualMachine::startIntervalThread(unsigned int timeout)
270
{
276
{
271
    IntervalThread intervalThread(timeout);
277
    IntervalThread intervalThread(timeout);
272
 
278
 
273
    myIntervalThreads[intervalThread.getId()] = intervalThread;
279
    myIntervalThreads[intervalThread.getId()] = intervalThread;
274
    myIntervalThreads[intervalThread.getId()].start();
280
    myIntervalThreads[intervalThread.getId()].start();
275
 
281
 
276
    return intervalThread.getId();
282
    return intervalThread.getId();
277
}
283
}
278
 
284
 
279
bool VirtualMachine::stopIntervalThread(unsigned int id)
285
bool VirtualMachine::stopIntervalThread(unsigned int id)
280
{
286
{
281
    if (myIntervalThreads.find(id) != myIntervalThreads.end())
287
    if (myIntervalThreads.find(id) != myIntervalThreads.end())
282
    {
288
    {
283
        myIntervalThreads.erase(id);
289
        myIntervalThreads.erase(id);
284
        return true;
290
        return true;
285
    }
291
    }
286
 
292
 
287
    return false;
293
    return false;
288
}
294
}
289
 
295
 
290
unsigned int VirtualMachine::startSocketThread(string address, int port, unsigned int reconnectTimeout)
296
unsigned int VirtualMachine::startSocketThread(string address, int port, unsigned int reconnectTimeout)
291
{
297
{
292
    SocketThread *socketThread = new SocketThread(address, port, reconnectTimeout);
298
    SocketThread *socketThread = new SocketThread(address, port, reconnectTimeout);
293
    mySocketThreads[socketThread->getId()] = socketThread;
299
    mySocketThreads[socketThread->getId()] = socketThread;
294
    mySocketThreads[socketThread->getId()]->start();
300
    mySocketThreads[socketThread->getId()]->start();
295
 
301
 
296
    return socketThread->getId();
302
    return socketThread->getId();
297
}
303
}
298
 
304
 
299
bool VirtualMachine::stopSocketThread(unsigned int id)
305
bool VirtualMachine::stopSocketThread(unsigned int id)
300
{
306
{
301
   
307
   
302
 
308
 
303
    if (mySocketThreads.find(id) != mySocketThreads.end())
309
    if (mySocketThreads.find(id) != mySocketThreads.end())
304
    {
310
    {
305
        //mySocketThreads[id]->stop();
311
        //mySocketThreads[id]->stop();
306
        delete mySocketThreads[id];
312
        delete mySocketThreads[id];
307
 
313
 
308
        mySocketThreads.erase(id);
314
        mySocketThreads.erase(id);
309
        return true;
315
        return true;
310
    }
316
    }
311
 
317
 
312
    return false;
318
    return false;
313
}
319
}
314
 
320
 
315
void VirtualMachine::sendToSocketThread(unsigned int id, string data)
321
void VirtualMachine::sendToSocketThread(unsigned int id, string data)
316
{
322
{
317
    if (mySocketThreads.find(id) != mySocketThreads.end())
323
    if (mySocketThreads.find(id) != mySocketThreads.end())
318
    {
324
    {
319
        mySocketThreads[id]->send(data);
325
        mySocketThreads[id]->send(data);
320
    }
326
    }
321
}
327
}
322
 
328
 
323
bool VirtualMachine::runExpression(string expression)
329
bool VirtualMachine::runExpression(string expression)
324
{
330
{
325
    SyslogStream &slog = SyslogStream::getInstance();
331
    SyslogStream &slog = SyslogStream::getInstance();
326
 
332
 
327
    string scriptName = "runExpression";
333
    string scriptName = "runExpression";
328
 
334
 
329
    Handle<String> source =  String::New(expression.c_str(), expression.length());
335
    Handle<String> source =  String::New(expression.c_str(), expression.length());
330
    //each script name must be unique , for this demo I just run one embedded script, so the name can be fixed
336
    //each script name must be unique , for this demo I just run one embedded script, so the name can be fixed
331
    Handle<String> name = String::New(scriptName.c_str(), scriptName.length());
337
    Handle<String> name = String::New(scriptName.c_str(), scriptName.length());
332
 
338
 
333
    //access global context within this scope
339
    //access global context within this scope
334
    Context::Scope context_scope(myContext);
340
    Context::Scope context_scope(myContext);
335
    //exception handler
341
    //exception handler
336
    TryCatch try_catch;
342
    TryCatch try_catch;
337
    //compile script to binary code - JIT
343
    //compile script to binary code - JIT
338
    Handle<Script> script = Script::Compile(source, name);
344
    Handle<Script> script = Script::Compile(source, name);
339
 
345
 
340
    //check if we got problems on compilation
346
    //check if we got problems on compilation
341
    if (script.IsEmpty())
347
    if (script.IsEmpty())
342
    {
348
    {
343
        // Print errors that happened during compilation.
349
        // Print errors that happened during compilation.
344
        String::AsciiValue error(try_catch.Exception());
350
        String::AsciiValue error(try_catch.Exception());
345
        string sError = *error;
351
        string sError = *error;
346
        slog << "runExpression: Failed to compile script: " + sError + "\n";
352
        slog << "runExpression: Failed to compile script: " + sError + "\n";
347
        slog << expression << "\n\n";
353
        slog << expression << "\n\n";
348
        return false;
354
        return false;
349
    }
355
    }
350
    else
356
    else
351
    {
357
    {
352
        //no errors , let's continue
358
        //no errors , let's continue
353
        Handle<Value> result = script->Run();
359
        Handle<Value> result = script->Run();
354
 
360
 
355
        //check if execution ended with errors
361
        //check if execution ended with errors
356
        if (result.IsEmpty())
362
        if (result.IsEmpty())
357
        {
363
        {
358
            // Print errors that happened during execution.
364
            // Print errors that happened during execution.
359
            String::AsciiValue error(try_catch.Exception());
365
            String::AsciiValue error(try_catch.Exception());
360
            string sError = *error;
366
            string sError = *error;
361
            slog << "runExpression: Failed to run script: " + sError + "\n";
367
            slog << "runExpression: Failed to run script: " + sError + "\n";
362
            return false;
368
            return false;
363
        }
369
        }
364
    }
370
    }
365
 
371
 
366
    return true;
372
    return true;
367
}
373
}
368
 
374
 
369
Handle<Value> VirtualMachine_log(const Arguments& args)
375
Handle<Value> VirtualMachine_log(const Arguments& args)
370
{
376
{
371
    SyslogStream &slog = SyslogStream::getInstance();
377
    SyslogStream &slog = SyslogStream::getInstance();
372
 
378
 
373
    String::AsciiValue str(args[0]);
379
    String::AsciiValue str(args[0]);
374
 
380
 
375
    slog << *str;
381
    slog << *str;
376
 
382
 
377
    return Undefined();
383
    return Undefined();
378
}
384
}
379
 
385
 
380
Handle<Value> VirtualMachine_sendCanMessage(const Arguments& args)
386
Handle<Value> VirtualMachine_sendCanMessage(const Arguments& args)
-
 
387
{
-
 
388
    //SyslogStream &slog = SyslogStream::getInstance();
-
 
389
    CanNetManager &canMan = CanNetManager::getInstance();
-
 
390
 
-
 
391
    CanMessage canMessage;
-
 
392
 
-
 
393
    String::AsciiValue className(args[0]);
-
 
394
    canMessage.setClassName(*className);
-
 
395
    String::AsciiValue directionFlag(args[1]);
-
 
396
    canMessage.setDirectionFlag(*directionFlag);
-
 
397
    String::AsciiValue moduleName(args[2]);
-
 
398
    canMessage.setModuleName(*moduleName);
-
 
399
    canMessage.setModuleId(args[3]->Uint32Value());
-
 
400
    String::AsciiValue commandName(args[4]);
-
 
401
    canMessage.setCommandName(*commandName);
-
 
402
 
-
 
403
    String::AsciiValue dataString(args[5]);
-
 
404
 
-
 
405
    vector<string> parts = explode(",", trim(*dataString, ','));
-
 
406
    map<string, CanVariable> data;
-
 
407
 
-
 
408
    for (int n = 0; n < parts.size(); n++)
-
 
409
    {
-
 
410
        vector<string> keyAndValue = explode(":", parts[n]);
-
 
411
 
-
 
412
        //string key = trim(keyAndValue[0], ' ');
-
 
413
        //string value = trim(keyAndValue[1], ' ');
-
 
414
        data[keyAndValue[0]] = CanVariable(keyAndValue[0], keyAndValue[1]);
-
 
415
    }
-
 
416
 
-
 
417
    canMessage.setData(data);
-
 
418
   
-
 
419
    canMan.sendMessage(canMessage);
-
 
420
 
-
 
421
    return Undefined();
-
 
422
}
-
 
423
 
-
 
424
Handle<Value> VirtualMachine_sendCanNMTMessage(const Arguments& args)
381
{
425
{
382
    //SyslogStream &slog = SyslogStream::getInstance();
426
    //SyslogStream &slog = SyslogStream::getInstance();
383
    CanNetManager &canMan = CanNetManager::getInstance();
427
    CanNetManager &canMan = CanNetManager::getInstance();
384
 
428
 
385
    CanMessage canMessage;
429
    CanMessage canMessage;
386
 
430
 
387
    String::AsciiValue className(args[0]);
431
    String::AsciiValue className(args[0]);
388
    canMessage.setClassName(*className);
432
    canMessage.setClassName(*className);
389
    String::AsciiValue directionFlag(args[1]);
-
 
390
    canMessage.setDirectionFlag(*directionFlag);
-
 
391
    String::AsciiValue moduleName(args[2]);
-
 
392
    canMessage.setModuleName(*moduleName);
-
 
393
    canMessage.setModuleId(args[3]->Uint32Value());
-
 
394
    String::AsciiValue commandName(args[4]);
433
    String::AsciiValue commandName(args[1]);
395
    canMessage.setCommandName(*commandName);
434
    canMessage.setCommandName(*commandName);
396
 
435
 
397
    String::AsciiValue dataString(args[5]);
436
    String::AsciiValue dataString(args[2]);
398
 
437
 
399
    vector<string> parts = explode(",", trim(*dataString, ','));
438
    vector<string> parts = explode(",", trim(*dataString, ','));
400
    map<string, CanVariable> data;
439
    map<string, CanVariable> data;
401
 
440
 
402
    for (int n = 0; n < parts.size(); n++)
441
    for (int n = 0; n < parts.size(); n++)
403
    {
442
    {
404
        vector<string> keyAndValue = explode(":", parts[n]);
443
        vector<string> keyAndValue = explode(":", parts[n]);
405
 
444
 
406
        //string key = trim(keyAndValue[0], ' ');
445
        //string key = trim(keyAndValue[0], ' ');
407
        //string value = trim(keyAndValue[1], ' ');
446
        //string value = trim(keyAndValue[1], ' ');
408
        data[keyAndValue[0]] = CanVariable(keyAndValue[0], keyAndValue[1]);
447
        data[keyAndValue[0]] = CanVariable(keyAndValue[0], keyAndValue[1]);
409
    }
448
    }
410
 
449
 
411
    canMessage.setData(data);
450
    canMessage.setData(data);
412
   
451
 
413
    canMan.sendMessage(canMessage);
452
    canMan.sendMessage(canMessage);
414
 
453
 
415
    return Undefined();
454
    return Undefined();
416
}
455
}
417
 
456
 
418
Handle<Value> VirtualMachine_loadScript(const Arguments& args)
457
Handle<Value> VirtualMachine_loadScript(const Arguments& args)
419
{
458
{
420
    VirtualMachine &vm = VirtualMachine::getInstance();
459
    VirtualMachine &vm = VirtualMachine::getInstance();
421
 
460
 
422
    String::AsciiValue str(args[0]);
461
    String::AsciiValue str(args[0]);
423
 
462
 
424
    return Boolean::New(vm.loadScript(*str));
463
    return Boolean::New(vm.loadScript(*str));
425
}
464
}
426
 
465
 
427
Handle<Value> VirtualMachine_startIntervalThread(const Arguments& args)
466
Handle<Value> VirtualMachine_startIntervalThread(const Arguments& args)
428
{
467
{
429
    VirtualMachine &vm = VirtualMachine::getInstance();
468
    VirtualMachine &vm = VirtualMachine::getInstance();
430
 
469
 
431
    unsigned int timeout = args[0]->Uint32Value();
470
    unsigned int timeout = args[0]->Uint32Value();
432
 
471
 
433
    return Integer::New(vm.startIntervalThread(timeout));
472
    return Integer::New(vm.startIntervalThread(timeout));
434
}
473
}
435
 
474
 
436
Handle<Value> VirtualMachine_stopIntervalThread(const Arguments& args)
475
Handle<Value> VirtualMachine_stopIntervalThread(const Arguments& args)
437
{
476
{
438
    VirtualMachine &vm = VirtualMachine::getInstance();
477
    VirtualMachine &vm = VirtualMachine::getInstance();
439
 
478
 
440
    unsigned int id = args[0]->Uint32Value();
479
    unsigned int id = args[0]->Uint32Value();
441
 
480
 
442
    return Boolean::New(vm.stopIntervalThread(id));
481
    return Boolean::New(vm.stopIntervalThread(id));
443
}
482
}
444
 
483
 
445
Handle<Value> VirtualMachine_startSocketThread(const Arguments& args)
484
Handle<Value> VirtualMachine_startSocketThread(const Arguments& args)
446
{
485
{
447
    VirtualMachine &vm = VirtualMachine::getInstance();
486
    VirtualMachine &vm = VirtualMachine::getInstance();
448
 
487
 
449
    String::AsciiValue address(args[0]);
488
    String::AsciiValue address(args[0]);
450
    int port = args[1]->Uint32Value();
489
    int port = args[1]->Uint32Value();
451
    unsigned int reconnectTimeout = args[2]->Uint32Value();
490
    unsigned int reconnectTimeout = args[2]->Uint32Value();
452
 
491
 
453
    return Integer::New(vm.startSocketThread(*address, port, reconnectTimeout));
492
    return Integer::New(vm.startSocketThread(*address, port, reconnectTimeout));
454
}
493
}
455
 
494
 
456
Handle<Value> VirtualMachine_stopSocketThread(const Arguments& args)
495
Handle<Value> VirtualMachine_stopSocketThread(const Arguments& args)
457
{
496
{
458
    VirtualMachine &vm = VirtualMachine::getInstance();
497
    VirtualMachine &vm = VirtualMachine::getInstance();
459
 
498
 
460
    unsigned int id = args[0]->Uint32Value();
499
    unsigned int id = args[0]->Uint32Value();
461
 
500
 
462
    return Boolean::New(vm.stopSocketThread(id));
501
    return Boolean::New(vm.stopSocketThread(id));
463
}
502
}
464
 
503
 
465
Handle<Value> VirtualMachine_sendToSocketThread(const Arguments& args)
504
Handle<Value> VirtualMachine_sendToSocketThread(const Arguments& args)
466
{
505
{
467
    VirtualMachine &vm = VirtualMachine::getInstance();
506
    VirtualMachine &vm = VirtualMachine::getInstance();
468
 
507
 
469
    unsigned int id = args[0]->Uint32Value();
508
    unsigned int id = args[0]->Uint32Value();
470
    String::AsciiValue data(args[1]);
509
    String::AsciiValue data(args[1]);
471
 
510
 
472
    vm.sendToSocketThread(id, *data);
511
    vm.sendToSocketThread(id, *data);
473
 
512
 
474
    return Undefined();
513
    return Undefined();
475
}
514
}
476
 
515
 
477
Handle<Value> VirtualMachine_uint2hex(const Arguments& args)
516
Handle<Value> VirtualMachine_uint2hex(const Arguments& args)
478
{
517
{
479
    VirtualMachine &vm = VirtualMachine::getInstance();
518
    VirtualMachine &vm = VirtualMachine::getInstance();
480
 
519
 
481
    unsigned int id = args[0]->Uint32Value();
520
    unsigned int id = args[0]->Uint32Value();
482
    unsigned int length = args[1]->Uint32Value();
521
    unsigned int length = args[1]->Uint32Value();
483
    string hexId = uint2hex(id, length);
522
    string hexId = uint2hex(id, length);
484
 
523
 
485
    return String::New(hexId.c_str());
524
    return String::New(hexId.c_str());
486
}
525
}
487
 
526
 
488
 
527