· 6 years ago · Apr 19, 2019, 12:40 AM
1<template>
2 <div></div>
3</template>
4
5<script>
6export default {
7 name: 'IoT',
8 created () {
9 const AWS = require('aws-sdk')
10 const AWSIoTData = require('aws-iot-device-sdk')
11 console.log('IoT component created')
12 let that = this
13
14 // LOOK! YOU WILL NEED TO UPDATE THESE VALUES!
15 const currentlySubscribedTopic = 'askJames'
16 const AWSConfiguration = {
17 poolId: 'us-east-1:d12345-1234-1234-1234', // 'YourCognitoIdentityPoolId'
18 host: 'abc123123123-ats.iot.us-east-1.amazonaws.com', // 'YourAwsIoTEndpoint', e.g. 'prefix.iot.us-east-1.amazonaws.com'
19 region: 'us-east-1' // 'YourAwsRegion', e.g. 'us-east-1'
20 }
21
22 const clientId = 'askJames-' + (Math.floor((Math.random() * 100000000) + 1))
23 AWS.config.region = AWSConfiguration.region
24
25 AWS.config.credentials = new AWS.CognitoIdentityCredentials({
26 IdentityPoolId: AWSConfiguration.poolId
27 })
28
29 const mqttClient = AWSIoTData.device({
30 region: AWS.config.region,
31 host: AWSConfiguration.host,
32 clientId: clientId,
33 protocol: 'wss',
34 maximumReconnectTimeMs: 8000,
35 debug: false,
36 accessKeyId: '',
37 secretKey: '',
38 sessionToken: ''
39 })
40
41 const cognitoIdentity = new AWS.CognitoIdentity()
42 const getCreds = () => {
43 AWS.config.credentials.get((err, data) => {
44 if (!err) {
45 console.log('retrieved identity: ' + AWS.config.credentials.identityId)
46 const params = {
47 IdentityId: AWS.config.credentials.identityId
48 }
49 cognitoIdentity.getCredentialsForIdentity(params, (err, data) => {
50 console.log('CREDS:', data)
51 if (!err) {
52 mqttClient.updateWebSocketCredentials(data.Credentials.AccessKeyId,
53 data.Credentials.SecretKey,
54 data.Credentials.SessionToken)
55 } else {
56 console.log('error retrieving credentials: ' + err)
57 }
58 })
59 } else {
60 console.log('error retrieving identity:' + err)
61 }
62 })
63 }
64
65 mqttClient.on('connect', () => {
66 console.log('mqttClient connected')
67 mqttClient.subscribe(currentlySubscribedTopic)
68 })
69
70 mqttClient.on('error', (err) => {
71 console.log('mqttClient error:', err)
72 getCreds()
73 })
74
75 mqttClient.on('message', (topic, payload) => {
76 const msg = JSON.parse(payload.toString())
77 console.log('mqttClient message: ', msg)
78 // Send the message back to parent component
79 that.$root.$emit('send', msg)
80 })
81 }
82}
83</script>