Created
May 31, 2019 22:43
-
-
Save furuya02/d723fa4127785ad93272d42494a81993 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Mqtt { | |
constructor() { | |
this.device = undefined; | |
} | |
async _getCredentials() { | |
AWS.config.region = this.region; | |
var cognitoidentity = new AWS.CognitoIdentity(); | |
var params = { | |
IdentityPoolId: this.poolId | |
}; | |
const identityId = await cognitoidentity.getId(params).promise(); | |
const data = await cognitoidentity.getCredentialsForIdentity(identityId).promise(); | |
var credentials = { | |
accessKey: data.Credentials.AccessKeyId, | |
secretKey: data.Credentials.SecretKey, | |
sessionToken: data.Credentials.SessionToken | |
}; | |
return credentials; | |
} | |
async init(poolId, region, endpoint, topic, clientId) { | |
this.poolId = poolId; | |
this.region = region; | |
this.endpoint = endpoint; | |
this.topic = topic; | |
this.clientId = clientId; | |
let self = this; | |
const credentials = await this._getCredentials(); // Credentialsの取得 | |
const awsIot = require('aws-iot-device-sdk'); | |
this.device = awsIot.device({ | |
region: this.region, | |
clientId: this.clientId, | |
accessKeyId: credentials.accessKey, | |
secretKey: credentials.secretKey, | |
sessionToken : credentials.sessionToken, | |
protocol: 'wss', | |
port: 443, | |
host: this.endpoint | |
}); | |
this.device.on('message', function(_topic, payload) { | |
self.onRecive(payload.toString("utf-8")); | |
}); | |
this.device.subscribe(topic, undefined, (err, granted) => { | |
if( err ) { | |
console.log('subscribe error: ' + err); | |
} | |
}); | |
} | |
async Send(param) { | |
await this.device.publish(this.topic, JSON.stringify(param), err => { | |
if( err ){ | |
console.log('publish error: ' + err); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment