/
main.js
211 lines (176 loc) · 6.08 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
206
207
208
209
210
211
/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
'use strict';
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
// @ts-ignore
const adapterName = require('./package.json').name.split('.').pop();
/**
* The adapter instance
* @type {ioBroker.Adapter}
*/
let adapter;
let timer;
const devices = {};
function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: adapterName,
objectChange: (id, obj) => {
if (devices[id]) {
if (obj) {
devices[id] = obj;
delete devices[id].native;
} else {
delete devices[id];
}
}
},
unload: callback => {
// stop running timer
timer && clearTimeout(timer);
timer = null;
callback();
},
ready: () => main()
});
adapter = new utils.Adapter(options);
return adapter;
}
function checkObject(obj, type) {
if (type === 'percent') {
return obj.common.unit === '%' || ('min' in obj.common && 'max' in obj.common);
} else if (type === 'temperature') {
return obj.common.type === 'number';
} else if (type === 'onoff') {
return obj.common.type === 'boolean';
}
return false;
}
function convertValue(obj, type, value) {
if (type === 'percent') {
if ('min' in obj.common && 'max' in obj.common) {
const delta = obj.common.max - obj.common.min;
return obj.common.min + Math.round(delta * value / 100);
} else {
return value;
}
} else if (type === 'temperature') {
return value;
} else if (type === 'onoff') {
return !!value;
}
return false;
}
const updateStates = async () => {
const profiles = adapter.config.profiles;
const now = new Date();
const active = {};
for (const k in profiles) {
const profile = profiles[k];
let profileState = profile.type === 'profile' && profile.data.state && (await adapter.getForeignStateAsync(profile.data.state));
if (profileState && typeof profileState === 'object') {
profileState = profileState.val;
}
if (profile.type === 'profile'
&& profile.data.dow.includes(now.getDay())
&& profileState
) {
const index = Math.floor((now.getHours() + now.getMinutes() / 60) / profile.data.intervalDuration);
const value = profile.data.intervals[index];
profile.data.members.forEach(id => {
if (!devices[id]) {
adapter.log.warn(`Device ${id} used in schedule "${profile.title}", but object does not exist.`);
// this object was deleted after adapter start
return;
}
if (!active[id] || active[id].priority < profile.data.prio) {
active[id] = {
id: profile.id,
title: profile.title,
priority: profile.data.prio,
type: profile.data.type,
value,
};
} else if (active[id] && active[id].priority === profile.data.prio) {
adapter.log.error(`"${id}" is in two or more profiles: "${profile.title}" and "${active[id].title}"(<-used for control)`);
}
});
}
}
for (const id in active) {
const profile = active[id];
if (!checkObject(devices[id], profile.type)) {
adapter.log.error(`${device} in ${profile.title} is not type ${profile.type}`);
continue;
}
const value = convertValue(devices[id], profile.type, profile.value);
await adapter.setForeignStateChangedAsync(id, value);
adapter.log.info(`${id} in ${profile.title} set to ${value}`);
}
}
function startNextInterval() {
const time = new Date();
if (time.getMinutes() < 30) {
time.setMinutes(30);
} else {
time.setHours(time.getHours() + 1);
time.setMinutes(0);
}
time.setSeconds(0);
time.setMilliseconds(0);
timer = setTimeout(() => {
timer = null;
updateStates();
startNextInterval();
}, time.getTime() - Date.now());
}
const FORBIDDEN_CHARS = /[^._\-/ :!#$%&()+=@^{}|~\p{Ll}\p{Lu}\p{Nd}]+/gu;
function getStateId(profile, profiles, _list) {
_list = _list || [];
_list.unshift(profile.title.replace(FORBIDDEN_CHARS, '_').replace(/\./g, '_'));
if (profile.parent) {
// find parent profile
const parentProfile = profiles.find(item => item.id === profile.parent);
if (parentProfile) {
return getStateId(parentProfile, profiles, _list);
}
// eslint-disable-next-line
console.error('Cannot find parent ' + profile.parent);
return null;
}
return `${adapter.namespace}.${_list.join('.')}`;
}
async function main() {
const profiles = adapter.config.profiles;
// collect all devices
for (let k = 0; k < profiles.length; k++) {
const profile = profiles[k];
if (profile && profile.type === 'profile') {
if (profile.data.state === true) {
profile.data.state = getStateId(profile, profiles);
}
for (const m in profile.data.members) {
if (!devices[profile.data.members[m]]) {
const obj = await adapter.getForeignObjectAsync(profile.data.members[m]);
if (obj && obj.common) {
devices[obj._id] = obj;
delete obj.native;
}
}
}
}
}
// subscribe on all used IDs
adapter.subscribeForeignObjects(Object.keys(devices));
updateStates();
startNextInterval();
}
// If started as allInOne mode => return function to create instance
// @ts-ignore
if (module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}