Subversion Repositories HomeAutomation

Rev

Rev 2207 | 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.         /* Must check sensor here in case no alias is stored the adress needs to be printed */
  247.         var VikingSuccess = "NoVikingSensor";
  248.         if (variables["Protocol"] == "Viking")
  249.         {
  250.             /*
  251.                               ??? aaaaaaaa sttttttttttt hhhhhhhh cccccccc
  252.             341731651126    0b100 11111001 000011001011 00101110 00110110   20.3 46%
  253.             a = address, s = sign, t = temperature, h = humidity, c = crc
  254.             */
  255.             var data = variables["IRdata"];
  256.             var crc = data&0xFF;
  257.             var humidity = (data>>>8)&0xFF;
  258.             var temp = (data>>>16)&0xFFF;
  259.             var addr = rshift(data,28)&0xFF;
  260.             var unknown = rshift(data,36)&0xF;
  261.             var calccrc=crc8(rshift(data,8), 32);
  262.  
  263.             var sign = (temp>>>11)&1;
  264.             temp = temp&0x7FF;
  265.             if (sign > 0)
  266.             {
  267.                 temp = -temp;
  268.             }
  269.             temp = temp/10;
  270.  
  271.             VikingSuccess = "VikingNotFound";
  272.            
  273.             if (unknown != 4)
  274.             {
  275.                 Log("\033[33mWarning: VikingSensor, unknown part="+unknown+", data="+data+"\033[0m");
  276.             }
  277.         }
  278.                
  279.         loopAliases:    /* Label to break nested */
  280.         for (var alias_name in aliases_data)
  281.         {
  282.             if (aliases_data[alias_name]["specific"]["Channel"] == variables["Channel"] &&
  283.                 aliases_data[alias_name]["specific"]["Proto"] == variables["Protocol"])
  284.             {
  285.                 switch (variables["Protocol"])
  286.                 {
  287.                     case "Viking":
  288.                     {   /* Add alias with these specifics: Channel=0,Proto=Viking,Address=<address of sensor> */
  289.                         if (crc != calccrc)
  290.                         {
  291.                             Log("\033[31mError: VikingSensor, incorrect CRC, data="+data+", CRC="+crc+", calcCRC="+calccrc+"\033[0m");
  292.                             break loopAliases;
  293.                         }
  294.                         if (addr == aliases_data[alias_name]["specific"]["Address"])
  295.                         {
  296.                             VikingSuccess = "VikingFound";
  297.  
  298.                             var last_value = {};
  299.                             var last_value_string = Storage_GetParameter("LastValues", alias_name);
  300.  
  301.                             if (last_value_string)
  302.                             {
  303.                                 last_value = eval("(" + last_value_string + ")");
  304.                             }
  305.  
  306.                             var timestamp = get_time();
  307.                             last_value["Temperature_Celsius"] = { "value" : temp.toString(), "timestamp" : timestamp };
  308.                             last_value["Humidity_Percent"] = { "value" : humidity.toString(), "timestamp" : timestamp };
  309.  
  310.                             Storage_SetParameter("LastValues", alias_name, JSON.stringify(last_value));
  311.                            
  312.                             break loopAliases;
  313.                         }
  314.                         break;
  315.                     }
  316.                     case "Nexa2":
  317.                     {   /* Add alias with these specifics: Channel=0,Proto=Nexa2,OnData=<data for on>,OffData=<data for off> */
  318.                         var deviceStateCommand = "";
  319.                         if (variables["IRdata"] == aliases_data[alias_name]["specific"]["OnData"] && variables["Status"] == "Pressed")
  320.                         {
  321.                             deviceStateCommand = "On";
  322.                         }
  323.                         else if (variables["IRdata"] == aliases_data[alias_name]["specific"]["OffData"] && variables["Status"] == "Pressed")
  324.                         {
  325.                             deviceStateCommand = "Off";
  326.                         }
  327.                         else
  328.                         {
  329.                             break;
  330.                         }
  331.                        
  332.                         var last_value = {};
  333.                         var last_value_string = Storage_GetParameter("LastValues", alias_name);
  334.  
  335.                         if (last_value_string)
  336.                         {
  337.                             last_value = eval("(" + last_value_string + ")");
  338.                         }
  339.                        
  340.                         if (( typeof(last_value["State"]) == "undefined" ) ||
  341.                             ( deviceStateCommand == "Off" && last_value["State"]["value"] == "On" ) ||
  342.                             ( deviceStateCommand == "On" && last_value["State"]["value"] == "Off" ))
  343.                         {
  344.                             last_value["State"] = { "value" : deviceStateCommand, "timestamp" : get_time() };
  345.  
  346.                             Storage_SetParameter("LastValues", alias_name, JSON.stringify(last_value));
  347.  
  348.                             /* Call any potential subscribers */
  349.                             if (Sensor_OnDeviceStateChangeFunctions[alias_name])
  350.                             {
  351.                                 for (var n in Sensor_OnDeviceStateChangeFunctions[alias_name])
  352.                                 {
  353.                                     /* Call callback with arguments alias, state */
  354.                                     Sensor_OnDeviceStateChangeFunctions[alias_name][n](alias_name, deviceStateCommand);
  355.                                 }
  356.                             }
  357.                         }
  358.                         break;
  359.                     }
  360.                 }
  361.             }
  362.         }
  363.         if (VikingSuccess == "VikingNotFound")
  364.         {
  365.             Log("Found unknown vikingsensor address="+addr+" temperature="+temp+" humidity="+humidity+" unknown="+unknown);
  366.         }
  367.     }
  368. }
  369. Module_RegisterToOnMessage("all", SensorRf_OnMessage);
  370.  
  371. function Sensor_StoreNumberInPhonebook(number, timestamp)
  372. {
  373.   var phonebookNumbers = Storage_GetJsonParamter("PhoneBook", number);
  374.  
  375.   if (!phonebookNumbers)
  376.   {
  377.     phonebookNumbers = [];
  378.  
  379.     url = "wap.eniro.se/query?search_word=" + number + "&what=mobwp";
  380.     //Log("\033[31mURL: http://"+url+"\033[0m\n");
  381.  
  382.     Http_Request(url, function(socket_id, result, header, content_data)
  383.     {
  384.       //Log("\033[31mOnlinePhonebook-eniro: result was: " + result + "\033[0m\n");
  385.       //Log("\033[31mOnlinePhonebook-eniro: content was: " + content_data + "\033[0m\n");
  386.  
  387.       if (result.indexOf("200 OK") != -1)
  388.       {
  389.  
  390.         var lines = content_data.split("\n");
  391.  
  392.         var endString = "<anchor>Tillbaka<prev/></anchor>";
  393.         var nameStartString = "<td class=\"hTd2\">";
  394.         var nameEndString = "</table>";
  395.  
  396.         for (var n = 1; n < lines.length; n++)
  397.         {
  398.           var line = lines[n].trim("\n");
  399.  
  400.           if (line.indexOf(endString) != -1)
  401.           {
  402.             break;
  403.           }
  404.  
  405.           if (line.indexOf(nameStartString) != -1)
  406.           {
  407.             line = lines[n + 1].trim("\n");
  408.             splitted = line.split("b>");
  409.  
  410.             phonebookNumbers.push(splitted[1].substr(0, splitted[1].length - 2));
  411.             break;
  412.           }
  413.         }
  414.  
  415.         //Log("\033[31mOnlinePhonebook: Line: " + lines[1] + "\033[0m\n");
  416.         //Log("\033[31mOnlinePhonebook: Line: " + lines[2] + "\033[0m\n");
  417.         //Log("\033[31mOnlinePhonebook: Line: " + lines[3] + "\033[0m\n");
  418.         if (phonebookNumbers.length > 0)
  419.         {
  420.           Storage_SetJsonParameter("PhoneBook", number, phonebookNumbers);
  421.  
  422.           Sensor_UpdateNameInPhonecalls(timestamp, phonebookNumbers);
  423.  
  424.           Log("\033[31mOnlinePhonebook-eniro: Found: " + JSON.stringify(phonebookNumbers) + "\033[0m\n");
  425.         }
  426.       }
  427.       else
  428.       {
  429.         Log("\033[31mOnlinePhonebook-eniro: Failed to do name lookup, result was: " + result + "\033[0m\n");
  430.       }
  431.  
  432.       if (phonebookNumbers.length == 0)
  433.       {
  434.         if (typeof sensorRKSEEK_API !== 'undefined')
  435.         {
  436.           url = "rkseek.oblivioncreations.se/?client="+sensorRKSEEK_API+"&n=" + number + "&out=text";
  437.           Log("\033[31mURL: http://"+url+"\033[0m\n");
  438.  
  439.           Http_Request(url, function(socket_id, result, header, content_data)
  440.           {
  441.             phonebookNumbers = [];
  442.  
  443.             if (result.indexOf("200 OK") != -1)
  444.             {
  445.               //Log("\033[31mOnlinePhonebook: result was: " + content_data + "\033[0m\n");
  446.               var lines = content_data.split("\n");
  447.               //Log("\033[31mOnlinePhonebook: Line: " + lines[1] + "\033[0m\n");
  448.               //Log("\033[31mOnlinePhonebook: Line: " + lines[2] + "\033[0m\n");
  449.               //Log("\033[31mOnlinePhonebook: Line: " + lines[3] + "\033[0m\n");
  450.               if (lines[2].length > 0)
  451.               {
  452.                 phonebookNumbers = [ lines[2] ]; // TODO Is this really correct?!
  453.                 Storage_SetJsonParameter("PhoneBook", number, phonebookNumbers);
  454.                
  455.                 Sensor_UpdateNameInPhonecalls(timestamp, phonebookNumbers);
  456.  
  457.                 Log("\033[31mOnlinePhonebook-rseek: Found: " + JSON.stringify(phonebookNumbers) + "\033[0m\n");
  458.               }
  459.             }
  460.             else
  461.             {
  462.               Log("\033[31mOnlinePhonebook-rseek: Failed to do name lookup, result was: " + result + "\033[0m\n");
  463.             }
  464.           });
  465.         }
  466.       }
  467.     });
  468.         /*
  469.         Http_Request("wap.hitta.se/default.aspx?Who=" + number + "&Where=&PageAction=White",
  470.             function(socket_id, result, header, content_data) {
  471.                 var persons = new Array();
  472.                 if (result.indexOf("200 OK") != -1)
  473.                 {
  474.                     var endString = "<anchor>Tillbaka<prev/></anchor>";
  475.                     var nameStartString = " title=\"Link\">";
  476.                     var nameEndString = "</a>";
  477.  
  478.                     var lines = content_data.split("<br/>");
  479.  
  480.                     for (var n = 1; n < lines.length; n++)
  481.                     {
  482.                         var line = lines[n].trim(" \n");
  483.  
  484.                         if (line.indexOf(endString) != -1)
  485.                         {
  486.                             break;
  487.                         }
  488.                         var pos = line.indexOf(nameStartString + (persons.length+1) + ".");
  489.  
  490.                         if (pos != -1)
  491.                         {
  492.                             pos += nameStartString.length + 2
  493.                             persons[persons.length] = line.substr(pos, line.length-pos-nameEndString.length).html_entity_decode().replace("  ", " ");
  494.                         }
  495.                     }
  496.                     if (persons.length > 0) {
  497.                         Storage_SetJsonParameter("PhoneBook", number, persons);
  498.  
  499.                         //CAll all listeners!
  500.                         //....
  501.  
  502.                         Log("\033[31mOnlinePhonebook: Found: " + JSON.stringify(persons) + "\033[0m\n");
  503.                     }
  504.                 }
  505.                 else
  506.                 {
  507.                     Log("\033[31mOnlinePhonebook: Failed to do name lookup, result was: " + result + "\033[0m\n");
  508.                 }
  509.             }
  510.         );
  511.         */
  512.  
  513.   }
  514.   else
  515.   {
  516.     //Log("Number already stored\n");
  517.  
  518.     Sensor_UpdateNameInPhonecalls(timestamp, phonebookNumbers);
  519.   }
  520.  
  521.   return phonebookNumbers;
  522. }
  523. Console_RegisterCommand(Sensor_StoreNumberInPhonebook, function(arg_index, args) { return Console_StandardAutocomplete(arg_index, args); });
  524.  
  525. function Sensor_StoreNumberInPhonebookManual(number, name)
  526. {
  527.     if (arguments.length < 2)
  528.     {
  529.         Log("\033[31mNot enough parameters given.\033[0m\n");
  530.         return false;
  531.     }
  532.    
  533.     var completename = arguments[1];
  534.     for (var i=2; i<arguments.length; i++)
  535.     {
  536.         completename = completename+" "+arguments[i];
  537.     }
  538.    
  539.     phonebookNumbers = [];
  540.     phonebookNumbers.push(completename);
  541.     Storage_SetJsonParameter("PhoneBook", number, phonebookNumbers);
  542. }
  543. Console_RegisterCommand(Sensor_StoreNumberInPhonebookManual, function(arg_index, args) { return Console_StandardAutocomplete(arg_index, args); });
  544.  
  545. function Sensor_UpdateNameInPhonecalls(timestamp, numbers)
  546. {
  547.   if (numbers.length > 0)
  548.   {
  549.     var lastValueString = Storage_GetParameter("PhoneCalls", timestamp);
  550.  
  551.     if (lastValueString)
  552.     {
  553.       var lastValue = JSON.parse(lastValueString);
  554.  
  555.       lastValue.names = numbers;
  556.  
  557.       Storage_SetParameter("PhoneCalls", timestamp, JSON.stringify(lastValue));
  558.     }
  559.   }
  560. }
  561.  
  562.