-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (64 loc) · 2.35 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
var rpio = require('rpio');
var Service, Characteristic;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-gpio', 'GDOOR', GardenDoorAccessory);
}
function GardenDoorAccessory(log, config) {
this.log = log;
this.name = config['name'];
this.pin = config['pin'];
this.duration = config['duration'];
this.service = new Service.LockMechanism(this.name);
if (!this.pin) throw new Error('You must provide a config value for pin.');
this.service
.getCharacteristic(Characteristic.LockCurrentState)
.on('get', this.getState.bind(this));
this.service
.getCharacteristic(Characteristic.LockTargetState)
.on('get', this.getState.bind(this))
.on('set', this.setState.bind(this));
}
GardenDoorAccessory.prototype.getServices = function() {
return [this.service];
}
GardenDoorAccessory.prototype.getState = function(callback) {
this.log("Getting current state...");
rpio.open(this.pin, rpio.OUTPUT);
var on = rpio.read(this.pin)
callback(null, on);
console.log('Pin ' + this.pin + ' is currently set ' + (rpio.read(this.pin) ? 'high' : 'low'));
}
GardenDoorAccessory.prototype.setState = function(state, callback) {
var lockitronState = (state == Characteristic.LockTargetState.SECURED) ? "lock" : "unlock";
this.log("Set state to %s", lockitronState);
if (state == Characteristic.LockTargetState.UNSECURED) {
this.pinAction(0);
if (is_defined(this.duration) && is_int(this.duration)) {
this.pinTimer()
}
callback(null);
} else {
this.pinAction(1);
callback(null);
}
}
GardenDoorAccessory.prototype.pinAction = function(action) {
this.log('Turning ' + (action == 0 ? 'on' : 'off') + ' pin #' + this.pin);
var self = this;
rpio.open(this.pin, rpio.OUTPUT);
rpio.write(this.pin, action == 0 ? rpio.LOW : rpio.HIGH);
}
GardenDoorAccessory.prototype.pinTimer = function() {
var self = this;
setTimeout(function() {
self.pinAction(1);
}, this.duration);
}
var is_int = function(n) {
return n % 1 === 0;
}
var is_defined = function(v) {
return typeof v !== 'undefined';
}