-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDevice.js
52 lines (39 loc) · 1.3 KB
/
Device.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
const mqtt = require( 'async-mqtt' );
const fs = require( 'fs' );
const path = require( 'path' );
const message1 = require( './messages/1.json' );
class Device {
constructor( thingName, broker ){
this.thingName = thingName;
this.broker = broker;
this.client = null;
}
async connect(){
const caPath = 'credentials/AmazonRootCA1.pem.txt';
const certPath = `credentials/${this.thingName}/${this.thingName}-certificate.pem.crt`;
const keyPath = `credentials/${this.thingName}/${this.thingName}-private.pem.key`;
const options = {
clientId: this.thingName,
ca: fs.readFileSync( caPath ),
cert: fs.readFileSync( certPath),
key: fs.readFileSync( keyPath )
};
this.client = await mqtt.connectAsync( this.broker, options );
}
async publish(){
if( !this.client )
throw new Error( 'client is falsy. Connected first.' );
let message = message1.payload;
if( typeof( message ) !== 'string' )
message = JSON.stringify( message );
// Hydrate thingname in topic if needed
let topic = message1.topic;
topic = topic.replace( /__THINGNAME__/g, this.thingName );
await this.client.publish( topic, message );
}
async disconnect(){
if( this.client !== null )
await this.client.end();
}
}
module.exports = Device;