forked from ankurp/homebridge-pir-motion-sensor
/
index.js
66 lines (54 loc) · 1.77 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
const gpio = require('rpi-gpio');
gpio.setMode(gpio.MODE_BCM);
let Service, Characteristic;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-gpio-pir-motion-sensor', 'Motion Sensor', MotionSensor);
};
class MotionSensor {
constructor(log, config) {
this.log = log;
this.name = config.name;
this.pirPin = config.pirPin;
this.motionDetected = false;
}
identify(callback) {
this.log('Identify requested!');
callback(null);
}
getServices() {
const informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, 'Alex Muller')
.setCharacteristic(Characteristic.Model, 'Pi Motion Sensor')
.setCharacteristic(Characteristic.SerialNumber, 'Raspberry Pi');
this.service = new Service.MotionSensor(this.name);
this.service
.getCharacteristic(Characteristic.MotionDetected)
.on('get', (callback) => {
callback(null, this.motionDetected);
});
gpio.on('change', (channel, value) => {
if (channel === this.pirPin) {
this.motionDetected = value;
this.service.setCharacteristic(Characteristic.MotionDetected, this.motionDetected);
}
});
gpio.setup(this.pirPin, gpio.DIR_IN, gpio.EDGE_BOTH, () => {
gpio.read(this.pirPin, (err, value) => {
if (err) {
console.error(err); // eslint-disable-line no-console
return;
}
this.motionDetected = value;
});
});
this.service
.getCharacteristic(Characteristic.Name)
.on('get', callback => {
callback(null, this.name);
});
return [informationService, this.service];
}
}