Giter VIP home page Giter VIP logo

react-native-mqtt's People

Contributors

alikh31 avatar introvertuous avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-native-mqtt's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

use client certificate for ssl

how can we use the ssl certificate client to authorize connection between server and client?
I just seeing the parameter useSSL: true/false
but the client need a certificate ? like browser generate signed certificate in web site

TypeScript

ts] 'MQTT' is declared but its value is never read.
[ts]
Could not find a declaration file for module 'react_native_mqtt'. '/home/i_m_brk/wtf/node_modules/react_native_mqtt/index.js' implicitly has an 'any' type.
Try npm install @types/react_native_mqtt if it exists or add a new declaration (.d.ts) file containing declare module 'react-native-mqtt';
module "/home/i_m_brk/wtf/node_modules/react-native-mqtt/index"

AMQJS0016E Invalid MQTT message type 0.

I am using your module in my react native projects. In one app, everything is ok on the emulator. But in another app, I always get the error "AMQJS0016E Invalid MQTT message type 0." on the emulator.

Object {invocationContext: undefined, errorCode: 16, errorMessage: "AMQJS0016E Invalid MQTT message type 0."}

I can say the Mqtt codes are very similar if not same between 2 apps.

So how can I debug the issue, please help.
P/S: not sure if it comes from AsyncStorage ?, your module will use different key for different apps in AsyncStorage ?, or how you build it currently ?

Not working on Android

The package works perfectly on iOS. However, when I run on Android, with the exact same parameters and code, I get this (AMQJS0007E Socket error:undefined). Any solutions?

Example please

I have tried including this in my project in expo but I just can't get it to work, I have tried it with cloudmqtt, hive and eclipse online free brokers but its not working. Can someone link a project they have made in react native using this library for MQTT. That will give me much more clarity thanks.

[QUESTION] - Store Paho.MQTT.Client in REDUX store

Hi there,

I have successfully implemented the package and love it. Great work.

Right now I have stored the client object in the local store as shown in the example but when I try to store the object in the REDUX store I get only an empty object.

Here a simple example

constructor(props) {
        super(props)

        const client = new Paho.MQTT.Client(<IP>, <PORT>, <CLIENT ID>)
        client.onConnectionLost = this._onConnectionLost
        client.onMessageArrived = this._onMessageArrived
        client.connect({
            onSuccess: this._onConnect,
            useSSL: true
        })
        this.props.setMQTTClient(client)

Where setMQTTClient() is the action that invokes the reducer to write it to the client to the store.

Since I'm getting an empty object I'm wondering whether the client creation is Promised based. If yes, how can I hook on the callback so that I can save the entire object once it has been created.

MQTT connection lost when app is in background for above 1 or 2 minutes (Android)

I've been trying to use react_native_mqtt to handle a feature that required mqtt connection still alive when app in background mode. But after 1 or 2 minute in background, mqtt connection lost and console: {errorCode: 7, errorMessage: 'AMQJS0007E Socket error:undefined.', reconnect: false, uri: 'ws://...:**/mqtt'}. Is this a bug of library or related to Android OS? And if anyone faced this problem before, please explain it. Thanks a lot!
My library information i'm using:
+ "react_native_mqtt": "^1.3.1",
+ "react-native": "^0.63.4",
+ "react": "^16.13.1",

Need to connect to mqtt server over tls

I've set the useSSL flag and the calls are going through wss:// but still the client credentials are being exposed in web socket.

How can I use secure mqtt or SSL pinning with client.connect()

I really need to find a way out of this.

Thanks

android mqtts connection failed

I have configure my broker with SSL like this in mosquitto.conf

listener 8883
protocol mqtt
cafile /usr/local/etc/mosquitto/certs2/ca.crt
keyfile /usr/local/etc/mosquitto/certs2/server.key
certfile /usr/local/etc/mosquitto/certs2/server.crt

listener 443
protocol websockets
cafile /usr/local/etc/mosquitto/certs/ca.crt
keyfile /usr/local/etc/mosquitto/certs/server.key
certfile /usr/local/etc/mosquitto/certs/server.crt

when I try to connect using react_native_mqtt with useSSL true and my IP host I can't

{ invocationContext: undefined,
errorCode: 7,
errorMessage: 'AMQJS0007E Socket error:undefined.' }

How to use SSL with react_native_mqtt ?

Red box error: Object is not a constructor (evaluating 'new Storage(options)')

I'm getting a show-stopping error in XCode and Android Studio after upgrading from 1.1.4 to 1.1.5. The red box error reads:

Object is not a constructor (evaluating 'new Storage(options)')

The version of react-native-storage included as a dependency is the same across versions, and the version of react-native we're using is also the same, so it doesn't appear that the problem comes from react-native's AsyncStorage. We're initializing react_native_mqtt exactly as shown in the README example. Error disappears after locking the version to 1.1.4, blowing away the node_modules directory and running npm install.

onMessageArrived not triggered

I'm having problem receiving the messages which are published to my broker.

I'm connecting to a MQTT service locally over webSockets, running on node using Mosca.

When publishing messages to the service through the test site (http://www.hivemq.com/demos/websocket-client/) I can see all the messages arriving to the broker just fine.

As far as I can tell I'm also able to connect to the service in my React Native app using recat_native_mqtt, i.e. the onConnect event is trigger when I start the app.

Everything up to this point seams to be working as expected, my problem is that the onMessageArrival handler isn't triggered, even though the messages are clearly reaching the MQTT broker.
Just i case I should also mention that I've set the useSSL-flag to false since my localhost is not on SSL.

no concurrent publisher support

Hello , i am facing an issue for concurrent user. I am not able to send data to broker if one publisher is already connected.

here is my configuration

import init from 'react_native_mqtt';
import AsyncStorage from '@react-native-async-storage/async-storage';
import DeviceInfo from 'react-native-device-info';

init({
size: 10000,
storageBackend: AsyncStorage,
defaultExpires: 1000 * 3600 * 24,
enableCache: true,
sync: {},
});

const defaultConnectOptions = {
reconnect: false,
cleanSession: true,
mqttVersion: 3,
keepAliveInterval: 60,
timeout: 60
}

class MQTTConnection {
constructor(host, port, clientID) {
this.mqtt = new Paho.MQTT.Client(host, port, clientID);
this.QOS = 1;
this.RETAIN = true;
this.channel = 'test';
this.clientID = "device";
//this.clientID = 'new_mqtt_test'
}

connect(host, port, options = null) {
    this.clientID = DeviceInfo.getBrand();

    if (options) {
        this.QOS = options.qos;
        this.RETAIN = options.retain;
    }

    let currentTime = new Date();
    // let clientID = currentTime + uuid.v1();
    // clientID = clientID.slice(0, 23);
    // console.log('clientID: ', clientID)

 
    this.mqtt.onConnectionLost = (res) => {
        this.onMQTTLost;
        console.log("this.mqtt.onConnectionLost"+res)
    };
    this.mqtt.onMessageArrived = (message) => {
        this.onMQTTMessageArrived(message);
    };
    this.mqtt.onMessageDelivered = (message) => {
        this.onMQTTMessageDelivered(message);
    };

    const connectOptions = options ? options : defaultConnectOptions;

    console.log("calling connect")


    this.mqtt.connect({
        onSuccess: ()=>{
            console.log('debug inside connect success .......')
        },
        onFailure: ()=>{
            console.log('debug inside connect failure.....')
        },
        ...connectOptions
    });
}

onMQTTSuccess = () => {
    this.onMQTTConnect()
}

onMQTTFailure = () => {
    this.onMQTTLost()
}

subscribeChannel(channel) {
    console.log('MQTTConnection subscribeChannel: ', channel)
    if (!this.mqtt || !this.mqtt.isConnected()) {
        return;
    }
    this.mqtt.subscribe(channel, this.QOS);
}

unsubscribeChannel(channel) {
    console.log('MQTTConnection unsubscribeChannel: ', channel)
    if (!this.mqtt || !this.mqtt.isConnected()) {
        return;
    }
    this.mqtt.unsubscribe(channel);
}

send(payload) {
    console.log('MQTTConnection send: ')
    if (!this.mqtt || !this.mqtt.isConnected()) {
        return;
    }


    if (!this.channel || !payload) {
        return false;
    }
    
    let now = new Date()
    let options = { timeZone: 'Asia/Kolkata' };
    let currentTimeIST = now.toLocaleString('en-US', options);

    //let utcString = now.toUtring();
    payload = `[${this.clientID}][${currentTimeIST}] : ${payload} `

    console.log(payload)
    
    //console.log(`MQTTConnection send publish channel: ${channel}, payload: ${payload} qos: ${this.QOS} retained: ${this.RETAIN}`)
    this.mqtt.publish(this.channel, payload, this.QOS, this.RETAIN);
}

close() {
    this.mqtt && this.mqtt.disconnect();
    this.mqtt = null;
}

set userID (newID) {
    this.clientID = newID;
}

}

// let client = null

// if (!client){
// client = new MQTTConnection('13.233.185.239', 8083,'ClientId');
// // client = new MQTTConnection('13.233.185.239', 8083,'ClientId');
// client.connect()
// }
//const client= new MQTTConnection('13.233.185.239', 8083,'ClientId');

export default MQTTConnection;

MQTTConnection.prototype.onMQTTConnect = ()=>{console.log('debug connect....')}
MQTTConnection.prototype.onMQTTLost = ()=>{console.log('debug lost...')}
MQTTConnection.prototype.onMQTTMessageArrived = ()=>{console.log('debug arrived...')}
MQTTConnection.prototype.onMQTTMessageDelivered = ()=>{console.log('debug delivered...')}

无法连接,出现AMQJS0007E

代码:
import { AsyncStorage }from'react-native';
import init from 'react_native_mqtt';
init({
size: 10000,
storageBackend: AsyncStorage,
defaultExpires: 1000 * 3600 * 24,
enableCache: true,
reconnect: true,
sync: {}
});
//第一步:创建
// 地址,端口,路径(这么写就行了),connectId(随便写) :地址和端口,都是后台给,或者你自己弄个mqtt的服务
//完整路径为:mqtt://192.168.22.149:1883
let client = new Paho.MQTT.Client('192.168.22.149',1883,'/mqtt','aaa')

    //第二步:连接,暂时有一个参数,2个方法:成功,失败
    client.connect({
        useSSL: false,
        onSuccess: onConnect,
        onFailure:(e)=>{ console.log('失败'); console.log(e); }
    });
    // 成功后需要发送主题 ,就是一个接口的路径类似
    function onConnect(){
        console.log('成功');
        client.subscribe('/fangtao');
    }
    //第三步:断掉
    // client.onConnectionLost = onConnectionLost;

    // function onConnectionLost (responseObject) {
    //     if (responseObject.errorCode !== 0) {
    //     console.log('onConnectionLost:' + responseObject.errorMessage);
    //     }
    // }

    // 第四步:接收消息
    client.onMessageArrived = onMessageArrived;

    function onMessageArrived (message) {
        console.log('消息:' + message.payloadString);
    }

版本:
"react": "16.9.0",
"react-native": "0.61.1",
"react_native_mqtt": "^1.3.1"

报错信息:
失败
{"errorCode":7,"errorMessage":"AMQJS0007E Socket error:undefined.","invocationContext":undefined}

android mqtts connect failed

I use mqtts to connect broker, and set 'useSSL: true'; it works well with ios platform, but it not working with android.
throw exception:
'{invocationContext: undefined, errorCode: 7, errorMessage: "AMQJS0007E Socket error:undefined."}'

AMQJSC0001E Connect timed out

All connection timeout:
const client = new Paho.MQTT.Client('iot.eclipse.org',80, 'aaa');
//const client = new Paho.MQTT.Client('mqtt.swifitch.cz',1883, 'aaa');
client.onConnectionLost = this.onConnectionLost;
client.onMessageArrived = this.onMessageArrived;
client.connect({ onSuccess: this.onConnect,onFailure:this.onFailure });

"react": "16.0.0",
"react-native": "0.51.0",
"react_native_mqtt": "^1.1.9"

Someone help?

mqtt

Why is there no way to set up emqx's will message

INVALID_STATE_ERR is causing the device to CRASH

I am using this library for connecting to the MQTT sever. I am getting the INVALID_STATE_ERR. I am not able to replicate the error. How to handle this type of error?

I am pasting my error stack here

com.facebook.react.common.JavascriptException: INVALID_STATE_ERR, stack:
value@79:1340
_socket_send@557:21101
_on_socket_open@557:16408
<unknown>@557:628
value@63:1501
<unknown>@79:4566
value@32:1363
value@18:3559
<unknown>@18:1044
value@18:2986
value@18:1016

I am using socket only for receiving the message. Can any one help regarding this?. I am attaching my Code Snippet

// These are my Utility function.

_createClient (options) {
      const location = this._getLocation()
      const clientId = this.generateClientId()
      const port = this._getPort()
      const path = this._getPath()
      const client = new Paho.MQTT.Client(location, port, path, clientId)
      console.log('Connecting to client', location, port, path, clientId)
      this.client = client
      this.client.onMessageArrived = this._notifyListeners // in case of new Message Arrival
      this.client.onConnectionLost = this.retry
      return this.client
    }

initialize (cb) {
      return new Promise((resolve, reject) => {
        try {
          this._createClient()
          this.observers = []
          if (!this.connected) {
            return this.connect()
              .then(resolve)
              .catch(err => {
                reject(new SocketError(err))
              })
          } else {
            console.log('Already Connected')
            return Promise.resolve()
          }
        } catch (ex) {
          return reject(new SocketError(ex))
        }
      })
    }


subscribe (subscribeTopic) {
      return new Promise((resolve, reject) => {
        try {
          if (this.connected) {
            console.log('Subscribing for Topic', subscribeTopic)
            this.client.subscribe(subscribeTopic, {
              onSuccess: () => {
                return resolve()
              },
              onFailure: err => reject(new SocketError(err)),
              qos: 2
            })
          } else {
            return reject(
              new SocketError(
                'Unable To Connect to socket. Exponential BackOff Started'
              )
            )
          }
        } catch (ex) {
          return reject(new SocketError(ex))
        }
      })
    }

For connecting I am using -

MQTTSocket.initialize() .then(() => MQTTSocket.subscribe(_userId))

_userId is the userId.

How can i replicate the issue?.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.