Subversion Repositories HomeAutomation

Rev

Rev 2205 | Rev 2218 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | SVN | RSS feed

  1.  
  2. Sensor_ModuleNames    = [ "DS18x20", "FOST02", "BusVoltage", "SimpleDTMF", "DHT11" ];
  3. SensorRf_ModuleNames    = [ "rfTransceive" ];
  4. Sensor_Intervals      = function() { return [ 1, 5, 10, 15, 20 ]; };
  5. Sensor_Aliases        = function() { return Module_GetAliasNames(Sensor_ModuleNames); };
  6. Sensor_AvailableIds   = function() { return Module_GetAvailableIds(Sensor_ModuleNames); };
  7.  
  8. function Sensor_SetReportInterval(alias_name, interval)
  9. {
  10.     if (arguments.length < 2)
  11.     {
  12.         Log("\033[31mNot enough parameters given.\033[0m\n");
  13.         return false;
  14.     }
  15.  
  16.     var aliases_data = Module_ResolveAlias(alias_name, Sensor_ModuleNames);
  17.     var found = false;
  18.  
  19.     for (var name in aliases_data)
  20.     {
  21.         var variables = {"Time"     : interval };
  22.         if (Module_SendMessage(aliases_data[name]["module_name"], aliases_data[name]["module_id"], "Report_Interval", variables))
  23.         {
  24.             Log("\033[32mCommand sent successfully to " + name + ".\033[0m\n");
  25.         }
  26.         else
  27.         {
  28.             Log("\033[31mFailed to send command to " + name + ".\033[0m\n");
  29.         }
  30.  
  31.         found = true;
  32.     }
  33.  
  34.     if (!found)
  35.     {
  36.         Log("\033[31mNo aliases by the name " + alias_name + " were applicable for this command.\033[0m\n");
  37.         return false;
  38.     }
  39.  
  40.     return true;
  41. }
  42. Console_RegisterCommand(Sensor_SetReportInterval, function(arg_index, args) { return Console_StandardAutocomplete(arg_index, args, Sensor_Aliases(), Sensor_Intervals()); });
  43.  
  44. Sensor_OnNewPhonenumberFunctions = [];
  45.  
  46. function Sensor_RegisterToNewPhonenumber(alias_name, callback)
  47. {
  48.   if (!Sensor_OnNewPhonenumberFunctions[alias_name])
  49.   {
  50.     Sensor_OnNewPhonenumberFunctions[alias_name] = [];
  51.   }
  52.  
  53.   Sensor_OnNewPhonenumberFunctions[alias_name].push(callback);
  54. }
  55.  
  56. Sensor_OnDeviceStateChangeFunctions = [];
  57.  
  58. function Sensor_RegisterToDeviceStateChange(alias_name, callback)
  59. {
  60.   if (!Sensor_OnDeviceStateChangeFunctions[alias_name])
  61.   {
  62.     Sensor_OnDeviceStateChangeFunctions[alias_name] = [];
  63.   }
  64.  
  65.   Sensor_OnDeviceStateChangeFunctions[alias_name].push(callback);
  66. }
  67.  
  68.  
  69. function Sensor_OnMessage(module_name, module_id, command, variables)
  70. {
  71.   if (in_array(Sensor_ModuleNames, module_name))
  72.   {
  73.     var aliases_data = Module_LookupAliases({
  74.       "module_name" : module_name,
  75.       "module_id"   : module_id,
  76.       "group"       : false
  77.     });
  78.  
  79.     switch (command)
  80.     {
  81.       case "Phonenumber":
  82.       {
  83.         for (var alias_name in aliases_data)
  84.         {
  85.           var number = variables["Number"];
  86.           var incommingCall = true;
  87.           var checkName = true;
  88.  
  89.           Log("received from DTMF:\"" + number + "\"");
  90.  
  91.           if (variables["Number"].length >= 6)
  92.           {
  93.             /* A seems to mean it is an incomming call! */
  94.             if (number.charAt(0) === 'A' || number.charAt(0) === 'D')
  95.             {
  96.               incommingCall = true;
  97.  
  98.               /* Remove leading A */
  99.               number = number.substring(1);
  100.             }
  101.             else /* Outgoing call */
  102.             {
  103.               incommingCall = false;
  104.             }
  105.  
  106.             /* A number can have a trailing C */
  107.             var endIndex = number.indexOf('C');
  108.  
  109.             if (endIndex !== -1)
  110.             {
  111.               /* Remove trailing C */
  112.               number = number.substring(0, endIndex);
  113.             }
  114.           }
  115.           else if (number == "B00C")
  116.           {
  117.             /* Unknown number */
  118.             number = "Unknown";
  119.             incommingCall = true;
  120.             checkName = false;
  121.           }
  122.           else if (number == "B10C")
  123.           {
  124.             /* Secret/protected number */
  125.             number = "Protected";
  126.             incommingCall = true;
  127.             checkName = false;
  128.           }
  129.           else
  130.           {
  131.             Log("DTMF decoded number is to short, number: \"" + number + "\", length: " + number.length);
  132.             return;
  133.           }
  134.          
  135.           /* Adding area code prefix if needed */
  136.           if (number.charAt(0) != '0' && checkName)
  137.           {
  138.             if (typeof sensorDefaultPhoneAreaCode === 'undefined')
  139.             {
  140.               Log("\033[31mOnlinePhonebook: please add sensorDefaultPhoneAreaCode = yourAreaCode to autostart.js, defaulting to 031\033[0m\n");
  141.               number = "031" + number;
  142.             }
  143.             else
  144.             {
  145.                 number = sensorDefaultPhoneAreaCode + number;
  146.             }
  147.           }
  148.  
  149.           /* Store number and direction in last values */
  150.           var lastValue = {};
  151.           var lastValueString = Storage_GetParameter("LastValues", alias_name);
  152.  
  153.           if (lastValueString)
  154.           {
  155.             lastValue = JSON.parse(lastValueString);
  156.           }
  157.  
  158.           var timestamp = get_time();
  159.  
  160.           lastValue["Phonenumber"] = { "value" : number, "timestamp" : timestamp };
  161.           lastValue["Direction"] = { "value" : incommingCall ? "in" : "out", "timestamp" : timestamp };
  162.  
  163.           Storage_SetParameter("LastValues", alias_name, JSON.stringify(lastValue));
  164.  
  165.  
  166.           /* Store number in phone call history */
  167.           var newValue = { "number" : number, "direction" : incommingCall ? "in" : "out", "module" : alias_name, "names" : [], "timestamp" : timestamp };
  168.  
  169.           Storage_SetParameter("PhoneCalls", timestamp, JSON.stringify(newValue));
  170.  
  171.  
  172.           /* Log the number */
  173.           Log("New number: " + number + ", direction: " + (incommingCall ? "in" : "out"));
  174.          
  175.           /* Lookup name */
  176.           if (checkName)
  177.           {
  178.             Sensor_StoreNumberInPhonebook(number, timestamp);
  179.           }
  180.  
  181.           var phonebookNumbers = Storage_GetJsonParamter("PhoneBook", number);
  182.           if (!phonebookNumbers)
  183.           {
  184.             phonebookNumbers = [];
  185.           }
  186.          
  187.           /* Call any potential subscribers */
  188.           if (Sensor_OnNewPhonenumberFunctions[alias_name])
  189.           {
  190.             for (var n in Sensor_OnNewPhonenumberFunctions[alias_name])
  191.             {
  192.               /* Call callback with arguments alias, number, direction */
  193.               Sensor_OnNewPhonenumberFunctions[alias_name][n](alias_name, number, incommingCall ? "in" : "out", phonebookNumbers);
  194.             }
  195.           }
  196.         }
  197.         break;
  198.       }
  199.       case "Voltage":
  200.       case "Temperature_Celsius":
  201.       {
  202.         if ((module_name == "DS18x20") && (variables["Value"] == 85))
  203.         {
  204.           Log("\033[31mDS18x20: Temperature conversion error: " + module_name + ":" + module_id + ", SensorId=" + variables["SensorId"] + "\033[0m");
  205.           break;
  206.         }
  207.       }
  208.       case "Humidity_Percent":
  209.       {
  210.         for (var alias_name in aliases_data)
  211.         {
  212.           if (aliases_data[alias_name]["specific"]["SensorId"] != variables["SensorId"])
  213.           {
  214.             continue;
  215.           }
  216.  
  217.           var last_value = {};
  218.           var last_value_string = Storage_GetParameter("LastValues", alias_name);
  219.  
  220.           if (last_value_string)
  221.           {
  222.             last_value = eval("(" + last_value_string + ")");
  223.           }
  224.  
  225.           last_value[command] = { "value" : variables["Value"], "timestamp" : get_time() };
  226.  
  227.           Storage_SetParameter("LastValues", alias_name, JSON.stringify(last_value));
  228.         }
  229.  
  230.         break;
  231.       }
  232.     }
  233.   }
  234. }
  235. Module_RegisterToOnMessage("all", Sensor_OnMessage);
  236.  
  237. function SensorRf_OnMessage(module_name, module_id, command, variables)
  238. {
  239.     if (in_array(SensorRf_ModuleNames, module_name))
  240.     {
  241.         var aliases_data = Module_LookupAliases({
  242.         "module_name" : module_name,
  243.         "module_id"   : module_id,
  244.         "group"       : false   });
  245.  
  246.         var VikingSuccess = "NoVikingSensor";
  247.         loopAliases:    /* Label to break nested */
  248.         for (var alias_name in aliases_data)
  249.         {
  250.             if (aliases_data[alias_name]["specific"]["Channel"] == variables["Channel"] &&
  251.                 aliases_data[alias_name]["specific"]["Proto"] == variables["Protocol"])
  252.             {
  253.                 switch (variables["Protocol"])
  254.                 {
  255.                     case "Viking":
  256.                     {   /* Add alias with these specifics: Channel=0,Proto=Viking,Address=<address of sensor> */
  257.                         VikingSuccess = "VikingNotFound";
  258.                         /*
  259.                                           ??? aaaaaaaa sttttttttttt hhhhhhhh cccccccc
  260.                         341731651126    0b100 11111001 000011001011 00101110 00110110   20.3 46%
  261.                         a = address, s = sign, t = temperature, h = humidity, c = crc
  262.                         */
  263.                         var data = variables["IRdata"];
  264.                         var crc = data&0xFF;
  265.                         var humidity = (data>>>8)&0xFF;
  266.                         var temp = (data>>>16)&0xFFF;
  267.                         var addr = rshift(data,28)&0xFF;
  268.                         var unknown = rshift(data,36)&0xF;
  269.                         var calccrc=crc8(rshift(data,8), 32);
  270.        
  271.                         if (crc != calccrc)
  272.                         {
  273.                             Log("\033[31mError: VikingSensor, incorrect CRC, data="+data+", CRC="+crc+", calcCRC="+calccrc+"\033[0m");
  274.                             break loopAliases;
  275.                         }
  276.                         if (addr == aliases_data[alias_name]["specific"]["Address"])
  277.                         {
  278.                             VikingSuccess = "VikingFound";
  279.                            
  280.                             var sign = (temp>>>11)&1;
  281.                             temp = temp&0x7FF;
  282.                             if (sign > 0)
  283.                             {
  284.                                 temp = -temp;
  285.                             }
  286.                             temp = temp/10;
  287.        
  288.                             if (unknown != 4)
  289.                             {
  290.                                 Log("\033[33mWarning: VikingSensor, unknown part="+unknown+", data="+data+"\033[0m");
  291.                             }
  292.  
  293.                             var last_value = {};
  294.                             var last_value_string = Storage_GetParameter("LastValues", alias_name);
  295.  
  296.                             if (last_value_string)
  297.                             {
  298.                                 last_value = eval("(" + last_value_string + ")");
  299.                             }
  300.  
  301.                             var timestamp = get_time();
  302.                             last_value["Temperature_Celsius"] = { "value" : temp.toString(), "timestamp" : timestamp };
  303.                             last_value["Humidity_Percent"] = { "value" : humidity.toString(), "timestamp" : timestamp };
  304.  
  305.                             Storage_SetParameter("LastValues", alias_name, JSON.stringify(last_value));
  306.                            
  307.                             break loopAliases;
  308.                         }
  309.                         break;
  310.                     }
  311.                     case "Nexa2":
  312.                     {   /* Add alias with these specifics: Channel=0,Proto=Nexa,OnData=<data for on>,OffData=<data for off> */
  313.                         var deviceStateCommand = "";
  314.                         if (variables["IRdata"] == aliases_data[alias_name]["specific"]["OnData"] && variables["Status"] == "Pressed")
  315.                         {
  316.                             deviceStateCommand = "On";
  317.                         }
  318.                         else if (variables["IRdata"] == aliases_data[alias_name]["specific"]["OffData"] && variables["Status"] == "Pressed")
  319.                         {
  320.                             deviceStateCommand = "Off";
  321.                         }
  322.                         else
  323.                         {
  324.                             break;
  325.                         }
  326.                        
  327.                         var last_value = {};
  328.                         var last_value_string = Storage_GetParameter("LastValues", alias_name);
  329.  
  330.                         if (last_value_string)
  331.                         {
  332.                             last_value = eval("(" + last_value_string + ")");
  333.                         }
  334.                        
  335.                         if (( typeof(last_value["State"]) == "undefined" ) ||
  336.                             ( deviceStateCommand == "Off" && last_value["State"]["value"] == "On" ) ||
  337.                             ( deviceStateCommand == "On" && last_value["State"]["value"] == "Off" ))
  338.                         {
  339.                             last_value["State"] = { "value" : deviceStateCommand, "timestamp" : get_time() };
  340.  
  341.                             Storage_SetParameter("LastValues", alias_name, JSON.stringify(last_value));
  342.  
  343.                             /* Call any potential subscribers */
  344.                             if (Sensor_OnDeviceStateChangeFunctions[alias_name])
  345.                             {
  346.                                 for (var n in Sensor_OnDeviceStateChangeFunctions[alias_name])
  347.                                 {
  348.                                     /* Call callback with arguments alias, state */
  349.                                     Sensor_OnDeviceStateChangeFunctions[alias_name][n](alias_name, deviceStateCommand);
  350.                                 }
  351.                             }
  352.                         }
  353.                         break;
  354.                     }
  355.                 }
  356.             }
  357.         }
  358.         if (VikingSuccess == "VikingNotFound")
  359.         {
  360.             Log("Found unknown vikingsensor address="+addr+" temperature="+temp+" humidity="+humidity+" unknown="+unknown);
  361.         }
  362.     }
  363. }
  364. Module_RegisterToOnMessage("all", SensorRf_OnMessage);
  365.  
  366. function Sensor_StoreNumberInPhonebook(number, timestamp)
  367. {
  368.   var phonebookNumbers = Storage_GetJsonParamter("PhoneBook", number);
  369.  
  370.   if (!phonebookNumbers)
  371.   {
  372.     phonebookNumbers = [];
  373.  
  374.     url = "wap.eniro.se/query?search_word=" + number + "&what=mobwp";
  375.     //Log("\033[31mURL: http://"+url+"\033[0m\n");
  376.  
  377.     Http_Request(url, function(socket_id, result, header, content_data)
  378.     {
  379.       //Log("\033[31mOnlinePhonebook-eniro: result was: " + result + "\033[0m\n");
  380.       //Log("\033[31mOnlinePhonebook-eniro: content was: " + content_data + "\033[0m\n");
  381.  
  382.       if (result.indexOf("200 OK") != -1)
  383.       {
  384.  
  385.         var lines = content_data.split("\n");
  386.  
  387.         var endString = "<anchor>Tillbaka<prev/></anchor>";
  388.         var nameStartString = "<td class=\"hTd2\">";
  389.         var nameEndString = "</table>";
  390.  
  391.         for (var n = 1; n < lines.length; n++)
  392.         {
  393.           var line = lines[n].trim("\n");
  394.  
  395.           if (line.indexOf(endString) != -1)
  396.           {
  397.             break;
  398.           }
  399.  
  400.           if (line.indexOf(nameStartString) != -1)
  401.           {
  402.             line = lines[n + 1].trim("\n");
  403.             splitted = line.split("b>");
  404.  
  405.             phonebookNumbers.push(splitted[1].substr(0, splitted[1].length - 2));
  406.             break;
  407.           }
  408.         }
  409.  
  410.         //Log("\033[31mOnlinePhonebook: Line: " + lines[1] + "\033[0m\n");
  411.         //Log("\033[31mOnlinePhonebook: Line: " + lines[2] + "\033[0m\n");
  412.         //Log("\033[31mOnlinePhonebook: Line: " + lines[3] + "\033[0m\n");
  413.         if (phonebookNumbers.length > 0)
  414.         {
  415.           Storage_SetJsonParameter("PhoneBook", number, phonebookNumbers);
  416.  
  417.           Sensor_UpdateNameInPhonecalls(timestamp, phonebookNumbers);
  418.  
  419.           Log("\033[31mOnlinePhonebook-eniro: Found: " + JSON.stringify(phonebookNumbers) + "\033[0m\n");
  420.         }
  421.       }
  422.       else
  423.       {
  424.         Log("\033[31mOnlinePhonebook-eniro: Failed to do name lookup, result was: " + result + "\033[0m\n");
  425.       }
  426.  
  427.       if (phonebookNumbers.length == 0)
  428.       {
  429.         if (typeof sensorRKSEEK_API !== 'undefined')
  430.         {
  431.           url = "rkseek.oblivioncreations.se/?client="+sensorRKSEEK_API+"&n=" + number + "&out=text";
  432.           Log("\033[31mURL: http://"+url+"\033[0m\n");
  433.  
  434.           Http_Request(url, function(socket_id, result, header, content_data)
  435.           {
  436.             phonebookNumbers = [];
  437.  
  438.             if (result.indexOf("200 OK") != -1)
  439.             {
  440.               //Log("\033[31mOnlinePhonebook: result was: " + content_data + "\033[0m\n");
  441.               var lines = content_data.split("\n");
  442.               //Log("\033[31mOnlinePhonebook: Line: " + lines[1] + "\033[0m\n");
  443.               //Log("\033[31mOnlinePhonebook: Line: " + lines[2] + "\033[0m\n");
  444.               //Log("\033[31mOnlinePhonebook: Line: " + lines[3] + "\033[0m\n");
  445.               if (lines[2].length > 0)
  446.               {
  447.                 phonebookNumbers = [ lines[2] ]; // TODO Is this really correct?!
  448.                 Storage_SetJsonParameter("PhoneBook", number, phonebookNumbers);
  449.                
  450.                 Sensor_UpdateNameInPhonecalls(timestamp, phonebookNumbers);
  451.  
  452.                 Log("\033[31mOnlinePhonebook-rseek: Found: " + JSON.stringify(phonebookNumbers) + "\033[0m\n");
  453.               }
  454.             }
  455.             else
  456.             {
  457.               Log("\033[31mOnlinePhonebook-rseek: Failed to do name lookup, result was: " + result + "\033[0m\n");
  458.             }
  459.           });
  460.         }
  461.       }
  462.     });
  463.         /*
  464.         Http_Request("wap.hitta.se/default.aspx?Who=" + number + "&Where=&PageAction=White",
  465.             function(socket_id, result, header, content_data) {
  466.                 var persons = new Array();
  467.                 if (result.indexOf("200 OK") != -1)
  468.                 {
  469.                     var endString = "<anchor>Tillbaka<prev/></anchor>";
  470.                     var nameStartString = " title=\"Link\">";
  471.                     var nameEndString = "</a>";
  472.  
  473.                     var lines = content_data.split("<br/>");
  474.  
  475.                     for (var n = 1; n < lines.length; n++)
  476.                     {
  477.                         var line = lines[n].trim(" \n");
  478.  
  479.                         if (line.indexOf(endString) != -1)
  480.                         {
  481.                             break;
  482.                         }
  483.                         var pos = line.indexOf(nameStartString + (persons.length+1) + ".");
  484.  
  485.                         if (pos != -1)
  486.                         {
  487.                             pos += nameStartString.length + 2
  488.                             persons[persons.length] = line.substr(pos, line.length-pos-nameEndString.length).html_entity_decode().replace("  ", " ");
  489.                         }
  490.                     }
  491.                     if (persons.length > 0) {
  492.                         Storage_SetJsonParameter("PhoneBook", number, persons);
  493.  
  494.                         //CAll all listeners!
  495.                         //....
  496.  
  497.                         Log("\033[31mOnlinePhonebook: Found: " + JSON.stringify(persons) + "\033[0m\n");
  498.                     }
  499.                 }
  500.                 else
  501.                 {
  502.                     Log("\033[31mOnlinePhonebook: Failed to do name lookup, result was: " + result + "\033[0m\n");
  503.                 }
  504.             }
  505.         );
  506.         */
  507.  
  508.   }
  509.   else
  510.   {
  511.     //Log("Number already stored\n");
  512.  
  513.     Sensor_UpdateNameInPhonecalls(timestamp, phonebookNumbers);
  514.   }
  515.  
  516.   return phonebookNumbers;
  517. }
  518. Console_RegisterCommand(Sensor_StoreNumberInPhonebook, function(arg_index, args) { return Console_StandardAutocomplete(arg_index, args); });
  519.  
  520. function Sensor_StoreNumberInPhonebookManual(number, name)
  521. {
  522.     if (arguments.length < 2)
  523.     {
  524.         Log("\033[31mNot enough parameters given.\033[0m\n");
  525.         return false;
  526.     }
  527.    
  528.     var completename = arguments[1];
  529.     for (var i=2; i<arguments.length; i++)
  530.     {
  531.         completename = completename+" "+arguments[i];
  532.     }
  533.    
  534.     phonebookNumbers = [];
  535.     phonebookNumbers.push(completename);
  536.     Storage_SetJsonParameter("PhoneBook", number, phonebookNumbers);
  537. }
  538. Console_RegisterCommand(Sensor_StoreNumberInPhonebookManual, function(arg_index, args) { return Console_StandardAutocomplete(arg_index, args); });
  539.  
  540. function Sensor_UpdateNameInPhonecalls(timestamp, numbers)
  541. {
  542.   if (numbers.length > 0)
  543.   {
  544.     var lastValueString = Storage_GetParameter("PhoneCalls", timestamp);
  545.  
  546.     if (lastValueString)
  547.     {
  548.       var lastValue = JSON.parse(lastValueString);
  549.  
  550.       lastValue.names = numbers;
  551.  
  552.       Storage_SetParameter("PhoneCalls", timestamp, JSON.stringify(lastValue));
  553.     }
  554.   }
  555. }
  556.  
  557.