代码之家  ›  专栏  ›  技术社区  ›  Yash Vaghela

无法使用react native连接到aws iot设备

  •  1
  • Yash Vaghela  · 技术社区  · 6 年前

    我正在用react native构建物联网应用程序。 用过这个包

    https://github.com/aws/aws-iot-device-sdk-js

    但在运行应用程序时出错

    enter image description here

    import React, {Component} from 'react';
    import {Platform, 
      StyleSheet, 
      Text, 
      View,
      TextInput,
      TouchableOpacity,
      StatusBar,
    } from 'react-native';
    import AwsIot from 'aws-iot-device-sdk'
    export default class App extends Component {
      constructor(props){
        super(props)
        this.connectToIoT()
      }
      connectToIoT(){
        var device = AwsIot.device({
           keyPath:'1d8bea736f-private.pem.key',
           certPath: '1d8bea736f-certificate.pem.crt',
           caPath:   'AmazonRootCA1.pem',
           clientId: 'IoTcloud',
           host: 'a3ckca0x6pesml.iot.ap-northeast-2.amazonaws.com'
       });
       console.log(device)
       device
        .on('connect', function() {
          console.log('connect');
        });
        device
        .on('message', function(topic, payload) {
          console.log('message', topic, payload.toString());
        });
        }
    }

    keyPath、certPath、caPath文件存储在项目的根目录中

    已经从堆栈中跟踪此解决方案 How to implement AWS IoT(device) in React-Native?

    但仍然坚持这个错误

    1 回复  |  直到 6 年前
        1
  •  4
  •   Narendra Chouhan    6 年前
    import Aws from 'aws-sdk/dist/aws-sdk-react-native'
    import AwsIot from 'aws-iot-device-sdk'
    
    AWS_REGION = 'us-east-1' // Change if needed.
    AWS_COGNITO_IDENTITY_POOL = 'us-east-1:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' 
    // Fill in.
    AWS_IOT_ENDPOINT = 'XXXXXXXXXXXXX.iot.us-east-1.amazonaws.com' // Fill in.
    
    Aws.config.region = AWS_REGION
    Aws.config.credentials = new Aws.CognitoIdentityCredentials({
    IdentityPoolId: AWS_COGNITO_IDENTITY_POOL
    })
    
    Aws.config.credentials.get(() => {
    const config = {}
    let client
    
    config.host = AWS_IOT_ENDPOINT
    config.protocol = 'wss'
    config.clientId = `client-${Math.floor((Math.random() * 100000) + 1)}`
    config.accessKeyId = Aws.config.credentials.accessKeyId
    config.secretKey = Aws.config.credentials.secretAccessKey
    config.sessionToken = Aws.config.credentials.sessionToken
    
    client = AwsIot.device(config)
    
    client.on('connect', () => {
        client.subscribe('some_topic')
    })
    
    client.on('message', (topic, message) => {
        console.log(topic, message)
    })
    
    client.on('error', error => {
        console.log(error)
    })
    })
    

    https://github.com/aws/aws-iot-device-sdk-js/issues/86#issuecomment-371159865

        2
  •  0
  •   s b    6 年前

    推荐文章