-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
205 lines (178 loc) · 6.27 KB
/
main.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"use strict";
const axios = require('axios')
const packJson = require('./package.json');
/*
* Created with @iobroker/create-adapter v2.1.1
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require("@iobroker/adapter-core");
// Load your modules here, e.g.:
// const fs = require("fs");
class TemperaturNu extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: "temperatur-nu",
});
this.on("ready", this.onReady.bind(this));
this.on("unload", this.onUnload.bind(this));
this.unloaded = false;
}
sleep(ms) {
return new Promise(resolve => setTimeout(() => !this.unloaded && resolve(), ms));
}
async main() {
let apiParam = '';
if (
this.config.latitude !== undefined && this.config.longitude !== undefined &&
this.config.latitude !== null && this.config.longitude !== null &&
this.config.latitude !== '' && this.config.longitude !== '' &&
!isNaN(this.config.latitude) && !isNaN(this.config.longitude)
) {
apiParam += `&lat=${this.config.latitude}&lon=${this.config.longitude}`;
const url = 'https://api.temperatur.nu/tnu_1.17.php?cli=tnu' + apiParam;
this.log.info(`Get forecast from ${url}`)
let response;
try {
response = await axios.get(url, {headers: {'user-agent': `ioBroker.temperatur-nu/${packJson.version}`}});
} catch (err) {
this.log.error(`Error while requesting data: ${err.message}`);
this.log.error('Please check your settings!');
}
if (response) {
try {
await this.updateData(response.data);
} catch (err) {
this.log.error(`Error while updating data: ${err.message}`);
}
}
this.log.info('Data updated.');
} else {
this.log.error('Longitude or Latitude not set correctly.');
}
}
async updateData(data) {
this.log.info(`Raw data: ${JSON.stringify(data)}`);
const device = 'station';
const now = Date.now();
await this.setObjectNotExistsAsync(device, {
type: 'device',
common: {
name: 'station',
role: 'wheater'
},
native: {},
});
await this.setObjectNotExistsAsync(device + '.title', {
type: 'state',
common: {
name: 'station title',
role: 'text',
read: true,
write: false,
unit: '',
type: 'string'
},
native: {},
});
// Update existing
this.extendObjectAsync(device + '.title', {
common: {
type: 'string',
role: 'text'
}
});
await this.setStateAsync(device + '.title', data.stations[0].title, true);
await this.setObjectNotExistsAsync(device + '.id', {
type: 'state',
common: {
name: 'station id',
role: 'text',
read: true,
write: false,
unit: '',
type: 'string'
},
native: {},
});
// Update existing
this.extendObjectAsync(device + '.id', {
common: {
type: 'string',
role: 'text'
}
});
await this.setStateAsync(device + '.id', data.stations[0].id, true);
await this.setObjectNotExistsAsync(device + '.temperature', {
type: 'state',
common: {
name: 'current temperature',
role: 'value.temperature',
read: true,
write: false,
unit: '°C',
type: 'number'
},
native: {},
});
// Update existing
this.extendObjectAsync(device + '.temperature', {
common: {
type: 'number',
role: 'value.temperature'
}
});
await this.setStateAsync(device + '.temperature', parseFloat(data.stations[0].temp), true);
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
if ((!this.config.longitude && this.config.longitude !== 0) || isNaN(this.config.longitude) ||
(!this.config.latitude && this.config.latitude !== 0) || isNaN(this.config.latitude)
) {
this.log.info('longitude/longitude not set, get data from system');
try {
const state = await this.getForeignObjectAsync('system.config');
this.config.longitude = state.common.longitude;
this.config.latitude = state.common.latitude;
this.log.info(`system latitude: ${this.config.latitude} longitude: ${this.config.longitude}`);
} catch (err) {
this.log.error(err);
}
} else {
this.log.info(`longitude/longitude will be set by self-Config - longitude: ${this.config.longitude} latitude: ${this.config.latitude}`);
}
// now start fetching the actual data
const delay = Math.floor(Math.random() * 30000);
this.log.info(`Delay execution by ${delay}ms to better spread API calls`);
await this.sleep(delay);
// Force terminate after 5min
setTimeout(() => {
this.unloaded = true;
this.log.error('force terminate');
this.terminate ? this.terminate() : process.exit(0);
}, 300000);
await this.main();
this.log.info('Update of data done, existing ...');
this.terminate ? this.terminate() : process.exit(0);
}
onUnload(callback) {
this.unloaded = true;
callback && callback();
}
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new TemperaturNu(options);
} else {
// otherwise start the instance directly
new TemperaturNu();
}