Subversion Repositories HomeAutomation

Rev

Go to most recent revision | Blame | Last modification | View Log | SVN | RSS feed

  1. /***************************************************************************
  2.  *   Copyright (C) December 10, 2008 by Mattias Runge                             *
  3.  *   mattias@runge.se                                                      *
  4.  *   virtualmachine.cpp                                            *
  5.  *                                                                         *
  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  *
  8.  *   the Free Software Foundation; either version 2 of the License, or     *
  9.  *   (at your option) any later version.                                   *
  10.  *                                                                         *
  11.  *   This program is distributed in the hope that it will be useful,       *
  12.  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
  13.  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
  14.  *   GNU General Public License for more details.                          *
  15.  *                                                                         *
  16.  *   You should have received a copy of the GNU General Public License     *
  17.  *   along with this program; if not, write to the                         *
  18.  *   Free Software Foundation, Inc.,                                       *
  19.  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
  20.  ***************************************************************************/
  21.  
  22. #include <map>
  23.  
  24.  
  25. #include "virtualmachine.h"
  26.  
  27. VirtualMachine* VirtualMachine::myInstance = NULL;
  28.  
  29. VirtualMachine& VirtualMachine::getInstance()
  30. {
  31.     if (myInstance == NULL)
  32.     {
  33.         myInstance = new VirtualMachine();
  34.     }
  35.  
  36.     return *myInstance;
  37. }
  38.  
  39. void VirtualMachine::deleteInstance()
  40. {
  41.     if (myInstance != NULL)
  42.     {
  43.         delete myInstance;
  44.         myInstance = NULL;
  45.     }
  46. }
  47.  
  48. VirtualMachine::VirtualMachine()
  49. {
  50.    
  51. }
  52.  
  53. VirtualMachine::~VirtualMachine()
  54. {
  55.    
  56. }
  57.  
  58. void VirtualMachine::run()
  59. {
  60.     SyslogStream &slog = SyslogStream::getInstance();
  61.  
  62.     string basePath = Settings::get("BasePath") + "/Services/System/";
  63.     string scriptName = "Base.js";
  64.     string scriptFileName = basePath + scriptName;
  65.  
  66.     if (!file_exists(scriptFileName))
  67.     {
  68.         slog << "Failed to load :" << scriptFileName << "\n";
  69.     }
  70.  
  71.     string scriptSource = file_get_contents(scriptFileName);
  72.  
  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
  75.     Handle<String> name = String::New(scriptName.c_str(), scriptName.length());
  76.  
  77.     // Create a template for the global object.
  78.     myGlobal = ObjectTemplate::New();
  79.  
  80.     //associates "print" on script to the Print function
  81.     myGlobal->Set(String::New("log"), FunctionTemplate::New(VirtualMachine_log));
  82.     myGlobal->Set(String::New("sendCanMessage"), FunctionTemplate::New(VirtualMachine_sendCanMessage));
  83.     myGlobal->Set(String::New("loadScript"), FunctionTemplate::New(VirtualMachine_loadScript));
  84.     myGlobal->Set(String::New("setTimeout"), FunctionTemplate::New(VirtualMachine_setTimeout));
  85.     myGlobal->Set(String::New("setInterval"), FunctionTemplate::New(VirtualMachine_setInterval));
  86.     myGlobal->Set(String::New("clearTimeout"), FunctionTemplate::New(VirtualMachine_clearInterval));
  87.     myGlobal->Set(String::New("clearInterval"), FunctionTemplate::New(VirtualMachine_clearInterval));
  88.  
  89.     //create context for the script
  90.     myContext = Context::New(NULL, myGlobal);
  91.  
  92.  
  93.     //access global context within this scope
  94.     Context::Scope context_scope(myContext);
  95.     //exception handler
  96.     TryCatch try_catch;
  97.     //compile script to binary code - JIT
  98.     Handle<Script> script = Script::Compile(source, name);
  99.  
  100.     //check if we got problems on compilation
  101.     if (script.IsEmpty())
  102.     {
  103.  
  104.         // Print errors that happened during compilation.
  105.         String::AsciiValue error(try_catch.Exception());
  106.         slog << "Failed to compile script: " << *error << "\n";
  107.     }
  108.     else
  109.     {
  110.         //no errors , let's continue
  111.         Handle<Value> result = script->Run();
  112.  
  113.         //check if execution ended with errors
  114.         if (result.IsEmpty())
  115.         {
  116.             // Print errors that happened during execution.
  117.             String::AsciiValue error(try_catch.Exception());
  118.             slog << "Constructor: Failed to run script: " << *error << "\n";
  119.         }
  120.         else
  121.         {
  122.             loadScript("System/Service.js");
  123.             loadScript("System/ServiceManager.js");
  124.             loadScript("System/CanMessage.js");
  125.             loadScript("System/CanManager.js");
  126.             loadScript("System/CanService.js");
  127.             loadScript("System/Startup.js");
  128.             loadScript("Autostart.js");
  129.  
  130.             myFunctionHandleHeartbeat = Handle<Function>::Cast(myContext->Global()->Get(String::New("handleHeartbeat")));
  131.             myFunctionOfflineCheck = Handle<Function>::Cast(myContext->Global()->Get(String::New("offlineCheck")));
  132.             myFunctionHandleMessage = Handle<Function>::Cast(myContext->Global()->Get(String::New("handleMessage")));
  133.             myFunctionStartup = Handle<Function>::Cast(myContext->Global()->Get(String::New("startup")));
  134.         }
  135.     }
  136.  
  137.     const int argc = 0;
  138.     Handle<Value> argv[argc] = { };
  139.  
  140.     Handle<Value> result = myFunctionStartup->Call(myFunctionStartup, argc, argv); // argc and argv are your standard arguments to a function
  141.  
  142.     mySemaphore.lock();
  143.  
  144.     while (1)
  145.     {
  146.         string expression;
  147.  
  148.         while (myExpressions.size() > 0)
  149.         {
  150.             expression = myExpressions.pop();
  151.  
  152.             runExpression(expression);
  153.         }
  154.  
  155.         CanMessage canMessage;
  156.  
  157.         while (myCanMessages.size() > 0)
  158.         {
  159.             canMessage = myCanMessages.pop();
  160.  
  161.             if (canMessage.isHeartbeat())
  162.             {
  163.                 callHandleHeartbeat(stoi(canMessage.getData()["HardwareId"].getValue()));
  164.             }
  165.             else
  166.             {
  167.                 callHandleMessage(canMessage);
  168.             }
  169.         }
  170.  
  171.         mySemaphore.wait();
  172.     }
  173.  
  174.     mySemaphore.unlock();
  175. }
  176.  
  177. void VirtualMachine::queueCanMessage(CanMessage canMessage)
  178. {
  179.     myCanMessages.push(canMessage);
  180.     mySemaphore.broadcast();
  181. }
  182.  
  183. void VirtualMachine::queueExpression(string expression)
  184. {
  185.     myExpressions.push(expression);
  186.     mySemaphore.broadcast();
  187. }
  188.  
  189. bool VirtualMachine::loadScript(string scriptName)
  190. {
  191.     SyslogStream &slog = SyslogStream::getInstance();
  192.  
  193.     string basePath = Settings::get("BasePath") + "/Services/";
  194.     string scriptFileName = basePath + scriptName;
  195.  
  196.     if (!file_exists(scriptFileName))
  197.     {
  198.         slog << "Failed to load :" << scriptFileName << "\n";
  199.         return false;
  200.     }
  201.  
  202.     string scriptSource = file_get_contents(scriptFileName);
  203.  
  204.     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.     Handle<String> name = String::New(scriptName.c_str(), scriptName.length());
  207.  
  208.     //access global context within this scope
  209.     Context::Scope context_scope(myContext);
  210.     //exception handler
  211.     TryCatch try_catch;
  212.     //compile script to binary code - JIT
  213.     Handle<Script> script = Script::Compile(source, name);
  214.  
  215.     //check if we got problems on compilation
  216.     if (script.IsEmpty())
  217.     {
  218.         // Print errors that happened during compilation.
  219.         String::AsciiValue error(try_catch.Exception());
  220.         slog << "Failed to compile script: " << *error << "\n";
  221.         return false;
  222.     }
  223.     else
  224.     {
  225.         //no errors , let's continue
  226.         Handle<Value> result = script->Run();
  227.  
  228.         //check if execution ended with errors
  229.         if (result.IsEmpty())
  230.         {
  231.             // Print errors that happened during execution.
  232.             String::AsciiValue error(try_catch.Exception());
  233.             slog << "loadScript: Failed to run script: " << *error << "\n";
  234.             return false;
  235.         }
  236.     }
  237.  
  238.     return true;
  239. }
  240.  
  241. void VirtualMachine::callHandleHeartbeat(int hardwareId)
  242. {
  243.     const int argc = 1;
  244.     Handle<Value> argv[argc] = { Integer::New(hardwareId) };
  245.  
  246.     Handle<Value> result = myFunctionHandleHeartbeat->Call(myFunctionHandleHeartbeat, argc, argv); // argc and argv are your standard arguments to a function
  247. }
  248.  
  249. void VirtualMachine::callHandleMessage(CanMessage canMessage)
  250. {
  251.     const int argc = 6;
  252.     Handle<Value> argv[argc] = {String::New(canMessage.getClassName().c_str()),
  253.                                 String::New(canMessage.getDirectionFlag().c_str()),
  254.                                 String::New(canMessage.getModuleName().c_str()),
  255.                                 Integer::New(canMessage.getModuleId()),
  256.                                 String::New(canMessage.getCommandName().c_str()),
  257.                                 String::New(canMessage.getJSONData().c_str()) };
  258.  
  259.     Handle<Value> result = myFunctionHandleMessage->Call(myFunctionHandleMessage, argc, argv); // argc and argv are your standard arguments to a function
  260. }
  261.  
  262. int VirtualMachine::setInterval(string expression, int interval, bool single)
  263. {
  264.     IntervalThread intervalThread(expression, interval, single);
  265.     intervalThread.start();
  266.  
  267.     int timeoutId = myTimers.size();
  268.     myTimers[timeoutId] = intervalThread;
  269.     myTimers[timeoutId].start();
  270.  
  271.     return timeoutId;
  272. }
  273.  
  274. bool VirtualMachine::clearInterval(int timeoutId)
  275. {
  276.     if (myTimers.find(timeoutId) != myTimers.end())
  277.     {
  278.         myTimers.erase(timeoutId);
  279.         return true;
  280.     }
  281.  
  282.     return false;
  283. }
  284.  
  285. bool VirtualMachine::runExpression(string expression)
  286. {
  287.     SyslogStream &slog = SyslogStream::getInstance();
  288.  
  289.     string scriptName = "runExpression";
  290.  
  291.     Handle<String> source =  String::New(expression.c_str(), expression.length());
  292.     //each script name must be unique , for this demo I just run one embedded script, so the name can be fixed
  293.     Handle<String> name = String::New(scriptName.c_str(), scriptName.length());
  294.  
  295.     //access global context within this scope
  296.     Context::Scope context_scope(myContext);
  297.     //exception handler
  298.     TryCatch try_catch;
  299.     //compile script to binary code - JIT
  300.     Handle<Script> script = Script::Compile(source, name);
  301.  
  302.     //check if we got problems on compilation
  303.     if (script.IsEmpty())
  304.     {
  305.         // Print errors that happened during compilation.
  306.         String::AsciiValue error(try_catch.Exception());
  307.         slog << "Failed to compile script: " << *error << "\n";
  308.        
  309.         return false;
  310.     }
  311.     else
  312.     {
  313.         //no errors , let's continue
  314.         Handle<Value> result = script->Run();
  315.  
  316.         //check if execution ended with errors
  317.         if (result.IsEmpty())
  318.         {
  319.             // Print errors that happened during execution.
  320.             String::AsciiValue error(try_catch.Exception());
  321.             slog << "runExpression: Failed to run script: " << *error << "\n";
  322.             return false;
  323.         }
  324.     }
  325.  
  326.     return true;
  327. }
  328.  
  329. Handle<Value> VirtualMachine_log(const Arguments& args)
  330. {
  331.     SyslogStream &slog = SyslogStream::getInstance();
  332.  
  333.     String::AsciiValue str(args[0]);
  334.  
  335.     slog << *str;
  336.  
  337.     return Undefined();
  338. }
  339.  
  340. Handle<Value> VirtualMachine_sendCanMessage(const Arguments& args)
  341. {
  342.     SyslogStream &slog = SyslogStream::getInstance();
  343.     CanNetManager &canMan = CanNetManager::getInstance();
  344.  
  345.     CanMessage canMessage;
  346.  
  347.     String::AsciiValue className(args[0]);
  348.     canMessage.setClassName(*className);
  349.     String::AsciiValue directionFlag(args[1]);
  350.     canMessage.setDirectionFlag(*directionFlag);
  351.     String::AsciiValue moduleName(args[2]);
  352.     canMessage.setModuleName(*moduleName);
  353.     canMessage.setModuleId(args[3]->Uint32Value());
  354.     String::AsciiValue commandName(args[4]);
  355.     canMessage.setCommandName(*commandName);
  356.  
  357.     String::AsciiValue dataString(args[5]);
  358.  
  359.     vector<string> parts = explode(",", trim(*dataString, ','));
  360.     map<string, CanVariable> data;
  361.  
  362.     for (int n = 0; n < parts.size(); n++)
  363.     {
  364.         vector<string> keyAndValue = explode(":", parts[n]);
  365.  
  366.         //string key = trim(keyAndValue[0], ' ');
  367.         //string value = trim(keyAndValue[1], ' ');
  368.         data[keyAndValue[0]] = CanVariable(keyAndValue[0], keyAndValue[1]);
  369.     }
  370.  
  371.     canMessage.setData(data);
  372.    
  373.     canMan.sendMessage(canMessage);
  374.  
  375.     return Undefined();
  376. }
  377.  
  378. Handle<Value> VirtualMachine_loadScript(const Arguments& args)
  379. {
  380.     VirtualMachine &vm = VirtualMachine::getInstance();
  381.  
  382.     String::AsciiValue str(args[0]);
  383.  
  384.     return Boolean::New(vm.loadScript(*str));
  385. }
  386.  
  387. Handle<Value> VirtualMachine_setInterval(const Arguments& args)
  388. {
  389.     VirtualMachine &vm = VirtualMachine::getInstance();
  390.  
  391.     String::AsciiValue expression(args[0]);
  392.     unsigned int interval = args[1]->Uint32Value();
  393.  
  394.     return Integer::New(vm.setInterval(*expression, interval, false));
  395. }
  396.  
  397. Handle<Value> VirtualMachine_setTimeout(const Arguments& args)
  398. {
  399.     VirtualMachine &vm = VirtualMachine::getInstance();
  400.  
  401.     String::AsciiValue expression(args[0]);
  402.     unsigned int interval = args[1]->Uint32Value();
  403.  
  404.     return Integer::New(vm.setInterval(*expression, interval, true));
  405. }
  406.  
  407. Handle<Value> VirtualMachine_clearInterval(const Arguments& args)
  408. {
  409.     VirtualMachine &vm = VirtualMachine::getInstance();
  410.  
  411.     return Boolean::New(vm.clearInterval(args[0]->Uint32Value()));
  412. }
  413.