forked from homebridge/homebridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenericRS232Device.js
58 lines (50 loc) · 1.89 KB
/
GenericRS232Device.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
var Service = require("hap-nodejs").Service;
var Characteristic = require("hap-nodejs").Characteristic;
var SerialPort = require("serialport").SerialPort;
module.exports = {
accessory: GenericRS232DeviceAccessory
}
function GenericRS232DeviceAccessory(log, config) {
this.log = log;
this.id = config["id"];
this.name = config["name"];
this.model_name = config["model_name"];
this.manufacturer = config["manufacturer"];
this.on_command = config["on_command"];
this.off_command = config["off_command"];
this.device = config["device"];
this.baudrate = config["baudrate"];
}
GenericRS232DeviceAccessory.prototype = {
setPowerState: function(powerOn, callback) {
var that = this;
var command = powerOn ? that.on_command : that.off_command;
var serialPort = new SerialPort(that.device, { baudrate: that.baudrate }, false);
serialPort.open(function (error) {
if (error) {
callback(new Error('Can not communicate with ' + that.name + " (" + error + ")"))
} else {
serialPort.write(command, function(err, results) {
if (error) {
callback(new Error('Can not send power command to ' + that.name + " (" + err + ")"))
} else {
callback()
}
});
}
});
},
getServices: function() {
var switchService = new Service.Switch(this.name);
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, this.manufacturer)
.setCharacteristic(Characteristic.Model, this.model_name)
.setCharacteristic(Characteristic.SerialNumber, this.id);
switchService
.getCharacteristic(Characteristic.On)
.on('set', this.setPowerState.bind(this));
return [informationService, switchService];
}
}
module.exports.accessory = GenericRS232DeviceAccessory;