如何在React Native上使用MQTT



我在React Native上是非常新的,我想在我的应用中使用MQTT。我试图按照链接中的说明 -> https://github.com/introvertous/react_native_mqtt

我通过命令安装了mqtt-> npm install react_native_mqtt -save

我的问题是: - 我应该在哪里粘贴下面的代码?在app.js文件中?我需要创建另一个文件吗? - 我应该在app.js文件中写些什么才能测试MQTT连接?

任何指导都受到欢迎。

import init from 'react_native_mqtt';
import { AsyncStorage } from 'react-native';
init({
  size: 10000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  enableCache: true,
  reconnect: true,
  sync : {
  }
});
function onConnect() {
  console.log("onConnect");
}
function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}
function onMessageArrived(message) {
  console.log("onMessageArrived:"+message.payloadString);
}
const client = new Paho.MQTT.Client('iot.eclipse.org', 443, 'uname');
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.connect({ onSuccess:onConnect, useSSL: true });

for New Googlers:例如,在设法正确安装了库后,这可能是您的app.js:

import React, { Component } from 'react';
import init from 'react_native_mqtt';
import { AsyncStorage,
  StyleSheet,
  Text,
  View,
  TextInput,
  Button,
  Alert
 } from 'react-native';
init({
  size: 10000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  enableCache: true,
  sync: {},
});

export default class App extends Component {
  constructor(){
    super();
    this.onMessageArrived = this.onMessageArrived.bind(this)
    this.onConnectionLost = this.onConnectionLost.bind(this)

    const client = new Paho.MQTT.Client('yourURL', yourPort, 'someClientID',);
    client.onMessageArrived = this.onMessageArrived;
    client.onConnectionLost = this.onConnectionLost;
    client.connect({ 
      onSuccess: this.onConnect,
      useSSL: false ,
      userName: 'yourUser',
      password: 'yourPass',
      onFailure: (e) => {console.log("here is the error" , e); }
    });
    this.state = {
      message: [''],
      client,
      messageToSend:'',
      isConnected: false,
    };
  }

  onMessageArrived(entry) {
    console.log("onMessageArrived:"+message.payloadString);
    this.setState({message: [...this.state.message, entry.payloadString]});
  }

  onConnect = () => {
    const { client } = this.state;
    console.log("Connected!!!!");
    client.subscribe('hello/world');
    this.setState({isConnected: true, error: ''})
  };

  sendMessage(){
    message = new Paho.MQTT.Message(this.state.messageToSend);
    message.destinationName = "hello/world";
    if(this.state.isConnected){
      this.state.client.send(message);    
    }else{
      this.connect(this.state.client)
        .then(() => {
          this.state.client.send(message);
          this.setState({error: '', isConnected: true});
        })
        .catch((error)=> {
          console.log(error);
          this.setState({error: error});
        });
  }
  }

  onConnectionLost(responseObject) {
    if (responseObject.errorCode !== 0) {
      console.log("onConnectionLost:"+responseObject.errorMessage);
      this.setState({error: 'Lost Connection', isConnected: false});
    }
  }


  render() {
    return (
      <View style={styles.container}>
      <Text style={styles.welcome}>
          Welcome to React Native MQTT!
        </Text>
        <Text style={styles.instructions}>
          Message: {this.state.message.join(' --- ')}
        </Text>
        <Text style={{color: 'red'}}>
          {this.state.error}
        </Text>
        { this.state.isConnected ?
            <Text style={{color: 'green'}}>
              Connected
            </Text> : null
        }
        <TextInput
          value={this.state.messageToSend} 
          onChangeText={(value => this.setState({messageToSend: value}))} 
          placeholder="Type hereee..."
          style={styles.input} />
        <Button onPress={this.sendMessage.bind(this) } title="Send Message" />
      </View>
    );
  }

}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  button: {
    padding: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonLabel: {
    color: 'blue',
  },
  input:{
    width: 300
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

相关内容

  • 没有找到相关文章

最新更新