如何在 React Native 上使用 MQTT? [英] How to use MQTT on React Native?

查看:242
本文介绍了如何在 React Native 上使用 MQTT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React Native 的新手,我想在我的应用程序中使用 MQTT.我试图按照链接中的说明进行操作 --> https://github.com/Introvertuous/react_native_mqtt

I am pretty new at React Native, and I would like to use MQTT in my app. I trying to follow the instructions in the link --> https://github.com/Introvertuous/react_native_mqtt

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

I installed MQTT throught the command --> npm install react_native_mqtt --save

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

My question is: - Where should I paste the code below? In the app.js file? Do I need to create another file? - What should I write in the app.js file to test the MQTT connection?

欢迎任何指导.

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 });

推荐答案

对于新的谷歌员工:例如,在您设法正确安装库后,这可能是您的 App.js:

For new googlers: After you managed to properly installed the library, for example, this could be your 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,
  },
});

这篇关于如何在 React Native 上使用 MQTT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆