-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
96 lines (82 loc) · 3.42 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"use strict";
var Service, Characteristic;
var temperatureService;
var request = require("request");
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-yr", "Yr", WeatherAccessory);
}
function WeatherAccessory(log, config) {
this.log = log;
this.name = config["name"];
this.location = config["location"];
this.lastupdate = 0;
this.temperature = 0;
}
WeatherAccessory.prototype =
{
getState: function (callback) {
// Only fetch new data once per hour
if (this.lastupdate + (60 * 60) < (Date.now() / 1000 | 0)) {
var url = "http://www.yr.no/sted/" + this.location + "/varsel.xml";
this.httpRequest(url, function (error, response, responseBody) {
if (error) {
this.log("HTTP get weather function failed: %s", error.message);
callback(error);
} else {
this.log("HTTP Response", responseBody);
var weatherJson = require('xml2json').toJson(responseBody);
var weatherObj = JSON.parse(weatherJson);
var temperature = parseFloat(weatherObj.weatherdata.forecast.tabular.time[0].temperature.value);
this.log("temperature: ", temperature);
this.temperature = temperature;
this.lastupdate = (Date.now() / 1000);
callback(null, this.temperature);
}
}.bind(this));
} else {
this.log("Returning cached data", this.temperature);
temperatureService.setCharacteristic(Characteristic.CurrentTemperature, this.temperature);
callback(null, this.temperature);
}
},
identify: function (callback) {
this.log("Identify requested!");
callback(); // success
},
getServices: function () {
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, "Yr.no")
.setCharacteristic(Characteristic.Model, "Location")
.setCharacteristic(Characteristic.SerialNumber, "");
temperatureService = new Service.TemperatureSensor(this.name);
temperatureService
.getCharacteristic(Characteristic.CurrentTemperature)
.on("get", this.getState.bind(this));
temperatureService
.getCharacteristic(Characteristic.CurrentTemperature)
.setProps({minValue: -30});
temperatureService
.getCharacteristic(Characteristic.CurrentTemperature)
.setProps({maxValue: 120});
return [informationService, temperatureService];
},
httpRequest: function (url, callback) {
request({
url: url,
body: "",
method: "GET",
rejectUnauthorized: false
},
function (error, response, body) {
callback(error, response, body)
})
}
};
if (!Date.now) {
Date.now = function () {
return new Date().getTime();
}
}