generated from atirage/miLight-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsonoff-diy-adapter.js
214 lines (192 loc) · 5.88 KB
/
sonoff-diy-adapter.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
212
213
214
/**
* sonoff-diy-adapter.js - sonoff-diy adapter.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.*
*/
'use strict';
const {
Adapter,
Device,
Property,
Database,
} = require('gateway-addon');
var Client = require('node-rest-client').Client;
const manifest = require('./manifest.json');
function on() {
return {
name: 'on',
value: false,
metadata: {
title: 'On/Off',
type: 'boolean',
'@type': 'OnOffProperty',
},
};
}
function sleep(ms){
return new Promise(resolve => {
setTimeout(resolve,ms)
})
}
const toggleSwitch = {
'@context': 'https://iot.mozilla.org/schemas',
'@type': ['OnOffSwitch'],
name: 'On Off Switch',
properties: [
on(),
],
actions: [],
events: [],
};
class sonoffProperty extends Property {
constructor(device, name, descr, value) {
super(device, name, descr);
this.setCachedValue(value);
}
}
class sonoffDevice extends Device {
constructor(adapter, id, template, config) {
super(adapter, id);
this.RESTclient = new Client();
this.name = template.name;
this.config = config;
this['@context'] = template['@context'];
this['@type'] = template['@type'];
for (const prop of template.properties) {
this.properties.set(prop.name,
new sonoffProperty(this, prop.name, prop.metadata, prop.value));
}
}
notifyPropertyChanged(property) {
super.notifyPropertyChanged(property);
if ('on' == property.name) {
this.adapter.sendProperties(this.id, property.value);
}
}
}
class sonoffAdapter extends Adapter {
constructor(addonManager, config) {
super(addonManager, manifest.id, manifest.id);
addonManager.addAdapter(this);
for (let i = 0; i < config.switches.length; i++) {
this.addDevice('sonoff-diy-adapter-' + i.toString(), toggleSwitch, config.switches[i]);
}
}
/**
* Add a new device to the adapter.
*
* The important part is to call: `this.handleDeviceAdded(device)`
*
* @param {String} deviceId ID of the device to add.
* @param {String} deviceDescription Description of the device to add.
* @return {Promise} which resolves to the device added.
*/
addDevice(deviceId, deviceDescription, deviceConfig) {
return new Promise((resolve, reject) => {
if (deviceId in this.devices) {
reject(`Device: ${deviceId} already exists.`);
} else {
const device = new sonoffDevice(this, deviceId, deviceDescription, deviceConfig);
this.handleDeviceAdded(device);
resolve(device);
}
});
}
/**
* Remove a device from the adapter.
*
* The important part is to call: `this.handleDeviceRemoved(device)`
*
* @param {String} deviceId ID of the device to remove.
* @return {Promise} which resolves to the device removed.
*/
removeDevice(deviceId) {
return new Promise((resolve, reject) => {
const device = this.devices[deviceId];
if (device) {
this.handleDeviceRemoved(device);
resolve(device);
} else {
reject(`Device: ${deviceId} not found.`);
}
});
}
/**
* Start the pairing/discovery process.
*
* @param {Number} timeoutSeconds Number of seconds to run before timeout
*/
startPairing(_timeoutSeconds) {
console.log('sonoff-diyAdapter:', this.name,
'id', this.id, 'pairing started');
//this.addDevice('sonoff-diy-adapter', toggleSwitch);
}
/**
* Cancel the pairing/discovery process.
*/
cancelPairing() {
console.log('sonoff-diyAdapter:', this.name, 'id', this.id,
'pairing cancelled');
}
/**
* Unpair the provided the device from the adapter.
*
* @param {Object} device Device to unpair with
*/
removeThing(device) {
console.log('sonoff-diyAdapter:', this.name, 'id', this.id,
'removeThing(', device.id, ') started');
this.removeDevice(device.id).then(() => {
console.log('sonoff-diyAdapter: device:', device.id, 'was unpaired.');
}).catch((err) => {
console.error('sonoff-diyAdapter: unpairing', device.id, 'failed');
console.error(err);
});
}
/**
* Cancel unpairing process.
*
* @param {Object} device Device that is currently being paired
*/
cancelRemoveThing(device) {
console.log('sonoff-diyAdapter:', this.name, 'id', this.id,
'cancelRemoveThing(', device.id, ')');
}
sendProperties(deviceId, state) {
// set content-type header and data as json in args
const cmd = state ? "on":"off";
const args = {
data: {
"deviceid": "",
"data": {
"switch": cmd
}
},
headers: { "Content-Type": "application/json" }
};
// Skip the next update after a sendProperty
if (this.devices[deviceId]) {
this.devices[deviceId].recentlyUpdated = true;
}
this.devices[deviceId].RESTclient.post("http://" + this.devices[deviceId].config.IP + ":" + this.devices[deviceId].config.Port + "/zeroconf/switch",
args, (data, response)=> {
// parsed response body as js object
//console.log(data);
if (data.seq === undefined) {
console.log('sonoff-diyAdapter: error sending switch command');
}
});
}
}
function loadsonoffAdapter(addonManager) {
const db = new Database(manifest.id);
db.open().then(() => {
return db.loadConfig();
}).then((config) => {
console.log('sonoff-diyAdapter:', config.switches);
new sonoffAdapter(addonManager, config);
});
}
module.exports = loadsonoffAdapter;