Subversion Repositories HomeAutomation

Rev

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

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