Subversion Repositories HomeAutomation

Rev

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

Rev Author Line No. Line
1648 runge 1
 
2232 linlun 2
Sensor_ModuleNames    = [ "DS18x20", "FOST02", "BusVoltage", "SimpleDTMF", "DHT11", "VoltageCurrent", "ultrasonic" ];
2205 arune 3
SensorRf_ModuleNames    = [ "rfTransceive" ];
1648 runge 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
    {
1649 runge 12
        Log("\033[31mNot enough parameters given.\033[0m\n");
1648 runge 13
        return false;
14
    }
2091 runge 15
 
1648 runge 16
    var aliases_data = Module_ResolveAlias(alias_name, Sensor_ModuleNames);
17
    var found = false;
2091 runge 18
 
1648 runge 19
    for (var name in aliases_data)
20
    {
1765 linlun 21
        var variables = {"Time"     : interval };
1649 runge 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
        }
2091 runge 30
 
1649 runge 31
        found = true;
32
    }
2091 runge 33
 
1649 runge 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
    }
2091 runge 39
 
1649 runge 40
    return true;
41
}
42
Console_RegisterCommand(Sensor_SetReportInterval, function(arg_index, args) { return Console_StandardAutocomplete(arg_index, args, Sensor_Aliases(), Sensor_Intervals()); });
43
 
2091 runge 44
Sensor_OnNewPhonenumberFunctions = [];
2050 arune 45
 
46
function Sensor_RegisterToNewPhonenumber(alias_name, callback)
47
{
2091 runge 48
  if (!Sensor_OnNewPhonenumberFunctions[alias_name])
49
  {
50
    Sensor_OnNewPhonenumberFunctions[alias_name] = [];
51
  }
52
 
53
  Sensor_OnNewPhonenumberFunctions[alias_name].push(callback);
2050 arune 54
}
55
 
2207 arune 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
 
1649 runge 69
function Sensor_OnMessage(module_name, module_id, command, variables)
70
{
2091 runge 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
    });
1807 linlun 78
 
2091 runge 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;
2098 runge 87
          var checkName = true;
1649 runge 88
 
2098 runge 89
          Log("received from DTMF:\"" + number + "\"");
90
 
2122 runge 91
          if (variables["Number"].length >= 6)
2091 runge 92
          {
2092 runge 93
            /* A seems to mean it is an incomming call! */
94
            if (number.charAt(0) === 'A' || number.charAt(0) === 'D')
2091 runge 95
            {
2092 runge 96
              incommingCall = true;
2091 runge 97
 
98
              /* Remove leading A */
99
              number = number.substring(1);
100
            }
2092 runge 101
            else /* Outgoing call */
2091 runge 102
            {
2092 runge 103
              incommingCall = false;
2091 runge 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;
2098 runge 120
            checkName = false;
2091 runge 121
          }
122
          else if (number == "B10C")
123
          {
124
            /* Secret/protected number */
125
            number = "Protected";
126
            incommingCall = true;
2098 runge 127
            checkName = false;
2091 runge 128
          }
129
          else
130
          {
131
            Log("DTMF decoded number is to short, number: \"" + number + "\", length: " + number.length);
132
            return;
133
          }
2181 arune 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
          }
2091 runge 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"));
2152 arune 174
 
2091 runge 175
          /* Lookup name */
2098 runge 176
          if (checkName)
177
          {
2181 arune 178
            Sensor_StoreNumberInPhonebook(number, timestamp);
2098 runge 179
          }
2091 runge 180
 
2181 arune 181
          var phonebookNumbers = Storage_GetJsonParamter("PhoneBook", number);
2152 arune 182
          if (!phonebookNumbers)
183
          {
184
            phonebookNumbers = [];
185
          }
186
 
2091 runge 187
          /* Call any potential subscribers */
188
          if (Sensor_OnNewPhonenumberFunctions[alias_name])
189
          {
190
            for (var n in Sensor_OnNewPhonenumberFunctions[alias_name])
191
            {
2152 arune 192
              /* Call callback with arguments alias, number, direction */
193
              Sensor_OnNewPhonenumberFunctions[alias_name][n](alias_name, number, incommingCall ? "in" : "out", phonebookNumbers);
2091 runge 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":
2232 linlun 209
      case "Percent":
210
      case "Distance":
2091 runge 211
      {
212
        for (var alias_name in aliases_data)
213
        {
214
          if (aliases_data[alias_name]["specific"]["SensorId"] != variables["SensorId"])
215
          {
216
            continue;
217
          }
218
 
219
          var last_value = {};
220
          var last_value_string = Storage_GetParameter("LastValues", alias_name);
221
 
222
          if (last_value_string)
223
          {
224
            last_value = eval("(" + last_value_string + ")");
225
          }
226
 
227
          last_value[command] = { "value" : variables["Value"], "timestamp" : get_time() };
228
 
229
          Storage_SetParameter("LastValues", alias_name, JSON.stringify(last_value));
230
        }
231
 
232
        break;
233
      }
234
    }
235
  }
1649 runge 236
}
237
Module_RegisterToOnMessage("all", Sensor_OnMessage);
1899 linlun 238
 
2205 arune 239
function SensorRf_OnMessage(module_name, module_id, command, variables)
240
{
241
    if (in_array(SensorRf_ModuleNames, module_name))
242
    {
243
        var aliases_data = Module_LookupAliases({
244
        "module_name" : module_name,
245
        "module_id"   : module_id,
246
        "group"       : false   });
247
 
2211 arune 248
        /* Must check sensor here in case no alias is stored the adress needs to be printed */
2205 arune 249
        var VikingSuccess = "NoVikingSensor";
2211 arune 250
        if (variables["Protocol"] == "Viking")
251
        {
252
            /*
253
                              ??? aaaaaaaa sttttttttttt hhhhhhhh cccccccc
254
            341731651126    0b100 11111001 000011001011 00101110 00110110   20.3 46%
255
            a = address, s = sign, t = temperature, h = humidity, c = crc
256
            */
257
            var data = variables["IRdata"];
258
            var crc = data&0xFF;
259
            var humidity = (data>>>8)&0xFF;
260
            var temp = (data>>>16)&0xFFF;
261
            var addr = rshift(data,28)&0xFF;
262
            var unknown = rshift(data,36)&0xF;
263
            var calccrc=crc8(rshift(data,8), 32);
264
 
265
            var sign = (temp>>>11)&1;
266
            temp = temp&0x7FF;
267
            if (sign > 0)
268
            {
269
                temp = -temp;
270
            }
271
            temp = temp/10;
272
 
273
            VikingSuccess = "VikingNotFound";
274
 
275
            if (unknown != 4)
276
            {
277
                Log("\033[33mWarning: VikingSensor, unknown part="+unknown+", data="+data+"\033[0m");
278
            }
279
        }
280
 
2205 arune 281
        loopAliases:    /* Label to break nested */
282
        for (var alias_name in aliases_data)
283
        {
284
            if (aliases_data[alias_name]["specific"]["Channel"] == variables["Channel"] &&
285
                aliases_data[alias_name]["specific"]["Proto"] == variables["Protocol"])
286
            {
287
                switch (variables["Protocol"])
288
                {
289
                    case "Viking":
2207 arune 290
                    {   /* Add alias with these specifics: Channel=0,Proto=Viking,Address=<address of sensor> */
2205 arune 291
                        if (crc != calccrc)
292
                        {
293
                            Log("\033[31mError: VikingSensor, incorrect CRC, data="+data+", CRC="+crc+", calcCRC="+calccrc+"\033[0m");
294
                            break loopAliases;
295
                        }
296
                        if (addr == aliases_data[alias_name]["specific"]["Address"])
297
                        {
298
                            VikingSuccess = "VikingFound";
299
 
300
                            var last_value = {};
301
                            var last_value_string = Storage_GetParameter("LastValues", alias_name);
302
 
303
                            if (last_value_string)
304
                            {
305
                                last_value = eval("(" + last_value_string + ")");
306
                            }
307
 
308
                            var timestamp = get_time();
309
                            last_value["Temperature_Celsius"] = { "value" : temp.toString(), "timestamp" : timestamp };
2218 arune 310
                            if (humidity<101)
311
                            {
312
                                last_value["Humidity_Percent"] = { "value" : humidity.toString(), "timestamp" : timestamp };
313
                            }
2205 arune 314
 
315
                            Storage_SetParameter("LastValues", alias_name, JSON.stringify(last_value));
316
 
317
                            break loopAliases;
318
                        }
319
                        break;
320
                    }
2207 arune 321
                    case "Nexa2":
2211 arune 322
                    {   /* Add alias with these specifics: Channel=0,Proto=Nexa2,OnData=<data for on>,OffData=<data for off> */
2207 arune 323
                        var deviceStateCommand = "";
324
                        if (variables["IRdata"] == aliases_data[alias_name]["specific"]["OnData"] && variables["Status"] == "Pressed")
325
                        {
326
                            deviceStateCommand = "On";
327
                        }
328
                        else if (variables["IRdata"] == aliases_data[alias_name]["specific"]["OffData"] && variables["Status"] == "Pressed")
329
                        {
330
                            deviceStateCommand = "Off";
331
                        }
332
                        else
333
                        {
334
                            break;
335
                        }
336
 
337
                        var last_value = {};
338
                        var last_value_string = Storage_GetParameter("LastValues", alias_name);
339
 
340
                        if (last_value_string)
341
                        {
342
                            last_value = eval("(" + last_value_string + ")");
343
                        }
344
 
345
                        if (( typeof(last_value["State"]) == "undefined" ) ||
346
                            ( deviceStateCommand == "Off" && last_value["State"]["value"] == "On" ) ||
347
                            ( deviceStateCommand == "On" && last_value["State"]["value"] == "Off" ))
348
                        {
349
                            last_value["State"] = { "value" : deviceStateCommand, "timestamp" : get_time() };
350
 
351
                            Storage_SetParameter("LastValues", alias_name, JSON.stringify(last_value));
352
 
353
                            /* Call any potential subscribers */
354
                            if (Sensor_OnDeviceStateChangeFunctions[alias_name])
355
                            {
356
                                for (var n in Sensor_OnDeviceStateChangeFunctions[alias_name])
357
                                {
358
                                    /* Call callback with arguments alias, state */
359
                                    Sensor_OnDeviceStateChangeFunctions[alias_name][n](alias_name, deviceStateCommand);
360
                                }
361
                            }
362
                        }
363
                        break;
364
                    }
2205 arune 365
                }
366
            }
367
        }
368
        if (VikingSuccess == "VikingNotFound")
369
        {
370
            Log("Found unknown vikingsensor address="+addr+" temperature="+temp+" humidity="+humidity+" unknown="+unknown);
371
        }
372
    }
373
}
374
Module_RegisterToOnMessage("all", SensorRf_OnMessage);
375
 
2091 runge 376
function Sensor_StoreNumberInPhonebook(number, timestamp)
1899 linlun 377
{
2152 arune 378
  var phonebookNumbers = Storage_GetJsonParamter("PhoneBook", number);
2091 runge 379
 
380
  if (!phonebookNumbers)
381
  {
382
    phonebookNumbers = [];
383
 
384
    url = "wap.eniro.se/query?search_word=" + number + "&what=mobwp";
385
    //Log("\033[31mURL: http://"+url+"\033[0m\n");
386
 
387
    Http_Request(url, function(socket_id, result, header, content_data)
388
    {
389
      //Log("\033[31mOnlinePhonebook-eniro: result was: " + result + "\033[0m\n");
390
      //Log("\033[31mOnlinePhonebook-eniro: content was: " + content_data + "\033[0m\n");
391
 
392
      if (result.indexOf("200 OK") != -1)
393
      {
394
 
395
        var lines = content_data.split("\n");
396
 
397
        var endString = "<anchor>Tillbaka<prev/></anchor>";
398
        var nameStartString = "<td class=\"hTd2\">";
399
        var nameEndString = "</table>";
400
 
401
        for (var n = 1; n < lines.length; n++)
402
        {
403
          var line = lines[n].trim("\n");
404
 
405
          if (line.indexOf(endString) != -1)
406
          {
407
            break;
408
          }
409
 
410
          if (line.indexOf(nameStartString) != -1)
411
          {
412
            line = lines[n + 1].trim("\n");
413
            splitted = line.split("b>");
414
 
415
            phonebookNumbers.push(splitted[1].substr(0, splitted[1].length - 2));
416
            break;
417
          }
418
        }
419
 
420
        //Log("\033[31mOnlinePhonebook: Line: " + lines[1] + "\033[0m\n");
421
        //Log("\033[31mOnlinePhonebook: Line: " + lines[2] + "\033[0m\n");
422
        //Log("\033[31mOnlinePhonebook: Line: " + lines[3] + "\033[0m\n");
423
        if (phonebookNumbers.length > 0)
424
        {
425
          Storage_SetJsonParameter("PhoneBook", number, phonebookNumbers);
426
 
427
          Sensor_UpdateNameInPhonecalls(timestamp, phonebookNumbers);
428
 
429
          Log("\033[31mOnlinePhonebook-eniro: Found: " + JSON.stringify(phonebookNumbers) + "\033[0m\n");
430
        }
431
      }
432
      else
433
      {
434
        Log("\033[31mOnlinePhonebook-eniro: Failed to do name lookup, result was: " + result + "\033[0m\n");
435
      }
436
 
2094 runge 437
      if (phonebookNumbers.length == 0)
2091 runge 438
      {
2094 runge 439
        if (typeof sensorRKSEEK_API !== 'undefined')
2091 runge 440
        {
2094 runge 441
          url = "rkseek.oblivioncreations.se/?client="+sensorRKSEEK_API+"&n=" + number + "&out=text";
442
          Log("\033[31mURL: http://"+url+"\033[0m\n");
2091 runge 443
 
2094 runge 444
          Http_Request(url, function(socket_id, result, header, content_data)
2091 runge 445
          {
2094 runge 446
            phonebookNumbers = [];
447
 
448
            if (result.indexOf("200 OK") != -1)
2091 runge 449
            {
2094 runge 450
              //Log("\033[31mOnlinePhonebook: result was: " + content_data + "\033[0m\n");
451
              var lines = content_data.split("\n");
452
              //Log("\033[31mOnlinePhonebook: Line: " + lines[1] + "\033[0m\n");
453
              //Log("\033[31mOnlinePhonebook: Line: " + lines[2] + "\033[0m\n");
454
              //Log("\033[31mOnlinePhonebook: Line: " + lines[3] + "\033[0m\n");
455
              if (lines[2].length > 0)
456
              {
457
                phonebookNumbers = [ lines[2] ]; // TODO Is this really correct?!
458
                Storage_SetJsonParameter("PhoneBook", number, phonebookNumbers);
459
 
460
                Sensor_UpdateNameInPhonecalls(timestamp, phonebookNumbers);
2152 arune 461
 
2094 runge 462
                Log("\033[31mOnlinePhonebook-rseek: Found: " + JSON.stringify(phonebookNumbers) + "\033[0m\n");
463
              }
2091 runge 464
            }
2094 runge 465
            else
466
            {
467
              Log("\033[31mOnlinePhonebook-rseek: Failed to do name lookup, result was: " + result + "\033[0m\n");
468
            }
469
          });
470
        }
2091 runge 471
      }
2094 runge 472
    });
2014 linlun 473
        /*
2091 runge 474
        Http_Request("wap.hitta.se/default.aspx?Who=" + number + "&Where=&PageAction=White",
1899 linlun 475
            function(socket_id, result, header, content_data) {
476
                var persons = new Array();
477
                if (result.indexOf("200 OK") != -1)
478
                {
479
                    var endString = "<anchor>Tillbaka<prev/></anchor>";
480
                    var nameStartString = " title=\"Link\">";
481
                    var nameEndString = "</a>";
2091 runge 482
 
1899 linlun 483
                    var lines = content_data.split("<br/>");
2091 runge 484
 
1899 linlun 485
                    for (var n = 1; n < lines.length; n++)
486
                    {
487
                        var line = lines[n].trim(" \n");
2091 runge 488
 
1899 linlun 489
                        if (line.indexOf(endString) != -1)
490
                        {
491
                            break;
492
                        }
493
                        var pos = line.indexOf(nameStartString + (persons.length+1) + ".");
2091 runge 494
 
1899 linlun 495
                        if (pos != -1)
496
                        {
497
                            pos += nameStartString.length + 2
498
                            persons[persons.length] = line.substr(pos, line.length-pos-nameEndString.length).html_entity_decode().replace("  ", " ");
499
                        }
500
                    }
501
                    if (persons.length > 0) {
502
                        Storage_SetJsonParameter("PhoneBook", number, persons);
2091 runge 503
 
1899 linlun 504
                        //CAll all listeners!
505
                        //....
2091 runge 506
 
1899 linlun 507
                        Log("\033[31mOnlinePhonebook: Found: " + JSON.stringify(persons) + "\033[0m\n");
508
                    }
509
                }
510
                else
511
                {
512
                    Log("\033[31mOnlinePhonebook: Failed to do name lookup, result was: " + result + "\033[0m\n");
2091 runge 513
                }
1899 linlun 514
            }
515
        );
2014 linlun 516
        */
2091 runge 517
 
518
  }
519
  else
520
  {
521
    //Log("Number already stored\n");
522
 
523
    Sensor_UpdateNameInPhonecalls(timestamp, phonebookNumbers);
524
  }
2152 arune 525
 
526
  return phonebookNumbers;
1899 linlun 527
}
528
Console_RegisterCommand(Sensor_StoreNumberInPhonebook, function(arg_index, args) { return Console_StandardAutocomplete(arg_index, args); });
529
 
2182 arune 530
function Sensor_StoreNumberInPhonebookManual(number, name)
531
{
532
    if (arguments.length < 2)
533
    {
534
        Log("\033[31mNot enough parameters given.\033[0m\n");
535
        return false;
536
    }
537
 
538
    var completename = arguments[1];
539
    for (var i=2; i<arguments.length; i++)
540
    {
541
        completename = completename+" "+arguments[i];
542
    }
543
 
544
    phonebookNumbers = [];
545
    phonebookNumbers.push(completename);
546
    Storage_SetJsonParameter("PhoneBook", number, phonebookNumbers);
547
}
548
Console_RegisterCommand(Sensor_StoreNumberInPhonebookManual, function(arg_index, args) { return Console_StandardAutocomplete(arg_index, args); });
549
 
2091 runge 550
function Sensor_UpdateNameInPhonecalls(timestamp, numbers)
551
{
552
  if (numbers.length > 0)
553
  {
554
    var lastValueString = Storage_GetParameter("PhoneCalls", timestamp);
1899 linlun 555
 
2091 runge 556
    if (lastValueString)
557
    {
558
      var lastValue = JSON.parse(lastValueString);
1899 linlun 559
 
2091 runge 560
      lastValue.names = numbers;
561
 
562
      Storage_SetParameter("PhoneCalls", timestamp, JSON.stringify(lastValue));
563
    }
564
  }
565
}
566
 
2232 linlun 567
function Sensor_SetUltrasonicMode(alias_name, BottomLimit, TopLimit, mode)
568
{
569
    if (arguments.length < 4)
570
    {
571
        Log("\033[31mNot enough parameters given.\033[0m\n");
572
        return false;
573
    }
574
 
575
    var aliases_data = Module_ResolveAlias(alias_name, Sensor_ModuleNames);
576
    var found = false;
577
 
578
    for (var name in aliases_data)
579
    {
580
        var variables = {   "0Percent"     : BottomLimit,
581
                    "100Percent"   : TopLimit,
582
                    "SensorMode"   : mode,
583
                    "SensorId"  : aliases_data[name]["specific"]["Channel"],
584
        };
585
        if (Module_SendMessage(aliases_data[name]["module_name"], aliases_data[name]["module_id"], "UltrasonicConfig", variables))
586
        {
587
            Log("\033[32mCommand sent successfully to " + name + ".\033[0m\n");
588
        }
589
        else
590
        {
591
            Log("\033[31mFailed to send command to " + name + ".\033[0m\n");
592
        }
593
 
594
        found = true;
595
    }
596
 
597
    if (!found)
598
    {
599
        Log("\033[31mNo aliases by the name " + alias_name + " were applicable for this command.\033[0m\n");
600
        return false;
601
    }
602
 
603
    return true;
604
}
605
Console_RegisterCommand(Sensor_SetUltrasonicMode, function(arg_index, args) { return Console_StandardAutocomplete(arg_index, args, Sensor_Aliases()); });