-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrematic.js
More file actions
104 lines (91 loc) · 2.26 KB
/
Copy pathbrematic.js
File metadata and controls
104 lines (91 loc) · 2.26 KB
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
'use strict';
const DEFAULT_PORT = 49880;
const DEVICES_PATH = './devices/';
const DEVICES_DEFAULT = 'default.js';
class Brematic {
/**
* @typedef {Object} Config Device Configuration
* @property {String} host Hostname of Brematic Gateway
* @property {number} port Port of Brematic Gateway
* @property {String} deviceType Type of device
* @property {Object} deviceConfig Parameters for driver
*/
/**
* Initialize Brematic
* @param {Config} config Configuration
*/
constructor(config) {
if (config === undefined) {
throw new Error('Device Configuration required!');
} else {
// Set Host
if (config.hasOwnProperty('host')) {
this.host = config.host;
} else {
throw new Error('Host is required!');
}
// Set Port
if (config.hasOwnProperty('port')) {
this.port = config.port;
} else {
this.port = DEFAULT_PORT;
}
// Load configured driver
var driverPath = '';
if (config.hasOwnProperty('deviceType')) {
driverPath = DEVICES_PATH + config.deviceType + '.js';
} else {
driverPath = DEVICES_PATH + DEVICES_DEFAULT;
}
try {
var Device = require(driverPath);
this.device = new Device(config.deviceConfig);
} catch (err) {
console.error(err);
throw new Error('Device driver not found!');
}
}
};
/**
* Send a Message to Gateway
* @private
* @param {String} message Message to be send
*/
sendMessage(message) {
return new Promise((resolve, reject) => {
var dgram = require('dgram');
var buffer = new Buffer(message);
var client = dgram.createSocket('udp4');
client.send(
buffer,
0,
buffer.length,
this.port,
this.host,
(err, bytes) => {
// Close connection
client.close();
if (err) {
reject(err);
} else {
resolve(bytes);
}
});
});
};
/**
* @public
* @param {*} value
*/
setValue(value) {
this.device.setValue(value);
return this.sendMessage(this.device.createMessage());
}
/**
* @public
*/
getValue() {
return this.device.getValue();
}
}
module.exports = Brematic;