forked from ChristopherNeuwirth/homebridge-rc433-etekcity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (85 loc) · 2.52 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
97
98
99
const rpi433 = require('rpi-433');
const rfEmitter = rpi433.emitter({pin: 0, pulseLength: 179});
let Service;
let Characteristic;
// command queue
let todoList = [];
let timer = null;
let timeout = 200; // timeout between sending rc commands (in ms)
module.exports = (homebridge) => {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-rc433-etekcity', 'RC433EtekcitySwitch', RC433EtekcitySwitch);
};
class RC433EtekcitySwitch {
constructor(log, config) {
// config
this.name = config['name'];
this.id = config['id'];
this.pulse = config['pulse'];
this.signalOn = config['on'];
this.signalOff = config['off'];
// setup
this.log = log;
this.service = new Service.Switch(this.name);
this.setupRcSwitchService(this.service);
// information service
this.informationService = new Service.AccessoryInformation();
this.informationService
.setCharacteristic(Characteristic.Name, 'RC433EtekcitySwitch')
.setCharacteristic(Characteristic.Manufacturer, 'CN')
.setCharacteristic(Characteristic.Model, 'Etekcity ' + this.name)
.setCharacteristic(Characteristic.SerialNumber, '1337-' + this.id);
}
getServices() {
return [this.informationService, this.service];
}
setupRcSwitchService(service) {
let state = false;
service
.getCharacteristic(Characteristic.On)
.on('set', (value, callback) => {
state = value;
let signal;
if(state) {
signal = this.signalOn;
} else {
signal = this.signalOff;
}
todoList.push({
'signal': signal,
'callback': callback
});
if (timer === null) {
timer = setTimeout(this.toggleNext, timeout, this);
}
});
service
.getCharacteristic(Characteristic.On)
.on('get', (callback) => {
callback(null, state);
});
}
toggleNext(switchObject) {
// get next todo item
let todoItem = todoList.shift();
let signal = todoItem['signal'];
let callback = todoItem['callback'];
// send signal
rfEmitter.sendCode(signal, function(error, stdout) {
if(error) {
console.log('error ' + error);
} else {
console.log('success ' + stdout);
};
});
// set timer for next todo
if (todoList.length > 0) {
timer = setTimeout(switchObject.toggleNext, timeout, switchObject);
} else {
timer = null;
}
// call callback
callback();
}
}