Git Product home page Git Product logo

react-native-paho-mqtt's Introduction

Eclipse Paho JavaScript client forked for React Native

npm version Build Status

A fork of paho-client, this project exists to provide an ES6-ready, Promise-based, react-native compatible version of the Eclipse Paho client

Compatibility note

Due to a React Native binary websocket bug, this library will not work with React Native 0.46.0 on Android, but should be ok on other platforms. RN 0.47 and RN<=0.45 are fine on all platforms as far as I know.

Documentation

Reference documentation (for the base Paho client) is online at: http://www.eclipse.org/paho/files/jsdoc/index.html

Getting Started

The included code below is a very basic sample that connects to a server using WebSockets and subscribes to the topic World, once subscribed, it then publishes the message Hello to that topic. Any messages that come into the subscribed topic will be printed to the Javascript console.

This requires the use of a broker that supports WebSockets natively, or the use of a gateway that can forward between WebSockets and TCP.

import { Client, Message } from 'react-native-paho-mqtt';

//Set up an in-memory alternative to global localStorage
const myStorage = {
  setItem: (key, item) => {
    myStorage[key] = item;
  },
  getItem: (key) => myStorage[key],
  removeItem: (key) => {
    delete myStorage[key];
  },
};

// Create a client instance
const client = new Client({ uri: 'ws://iot.eclipse.org:80/ws', clientId: 'clientId', storage: myStorage });

// set event handlers
client.on('connectionLost', (responseObject) => {
  if (responseObject.errorCode !== 0) {
    console.log(responseObject.errorMessage);
  }
});
client.on('messageReceived', (message) => {
  console.log(message.payloadString);
});

// connect the client
client.connect()
  .then(() => {
    // Once a connection has been made, make a subscription and send a message.
    console.log('onConnect');
    return client.subscribe('World');
  })
  .then(() => {
    const message = new Message('Hello');
    message.destinationName = 'World';
    client.send(message);
  })
  .catch((responseObject) => {
    if (responseObject.errorCode !== 0) {
      console.log('onConnectionLost:' + responseObject.errorMessage);
    }
  })
;

react-native-paho-mqtt's People

Contributors

andypiper avatar franleplant avatar gyurobenjamin avatar jpwsutton avatar knolleary avatar miketran78727 avatar rh389 avatar robhogan 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

Watchers

 avatar  avatar  avatar

react-native-paho-mqtt's Issues

Error in ReactJS

I am getting following error when I try to use react-native-paho-mqtt in ReactJS app.

./node_modules/react-native-paho-mqtt/src/Client.js
Module parse failed: Unexpected token (27:5)
You may need an appropriate loader to handle this file type.
| // ------------------------------------------------------------------------
| 
| type ConstructorOptions = {
|   uri: string,
|   clientId: string,

Can it be used in ReactJS app?

Cannot connect to broker

Hi, apparently it seems I cannot connect to any broker from my android emulator, every time I try to connect I get this error:

07-20 11:58:24.197  7089  7121 I ReactNativeJS: [Error: AMQJS0016E Invalid MQTT message type 0.]
07-20 11:58:24.197  7089  7121 I ReactNativeJS: onConnectionLost:undefined

I don't really get what's wrong, I just tried the given example with both the eclipse broker and my own broker but the result is the same. Any help would be very very appreciated

Reconnect

Is there a possibility to simply enable a reconnect-functionality (with same subscriptions)? U fortunately, after a certain time, the websocket-connection will be disconnected. Thank you!

Connection lost but client returns that it is still connected

After putting my application in the background for a minute (on android) and resuming i notice that the Client.isConnected() call returns true, even when the trace ping logs are not showing responses. (and my other clients do not receive anything sent from the disconnected client)

This problem seems to be tied to this: 8185b64

  1. _socketSend (the only place our pinger seems to be reset) is never called (as far as i can see)
  2. our pinger will never "fail" which i think breaks the "keep alive" function of mqtt outlined here: https://www.hivemq.com/blog/mqtt-essentials-part-10-alive-client-take-over
  3. if i set the keep alive time to a shorter time (default for this library is 60 seconds - amazon iot says the shortest they allow is 5 seconds) then this client will be disconnected after that time without properly reporting that it is disconnected.

ConnectOptions undefined

Basically i have to use .connect then i get this error. ConnectOptions undefined on "./src/ClientImplementation.js"

Typescript

How to solve solve type script errors
I don't know how to solve, ๐Ÿ˜…

typescript definitions

Would be nice if there was a comprehensive typescript definition file.

Current work around is to just declare the module in a separate file so Typescript will continue to compile

react-native-paho-mqtt.d.ts

declare module 'react-native-paho-mqtt';

counts of messageReceive will more and more since disconnect

my settings:
connect=> cleanSession: false
subscribe=> qos:2

issue:
when I just send a message once from server, but the counts of messageReceivered will grow up cause the disconnected

happened:
connect => subscribe => disconnect => connect again.. then have an issue
counts of messageReceive will more and more since disconnect

How to connect to RabbitMQ cluster?

Hi,

I was trying to connect to the rabbitMQ cluster.

I provided uris in ConnectOptions but it is of no use.

I saw the code in Client.js, uris is defined in ConnectOptions but not used.
So is it possible to connect to RabbitMQ cluster? If so, please let me know

unsubscribe

Hello,

So I'm trying to handle reconnects using Appstate because the reconnect flag isn't supported in connection options and I'm getting some weirdness with the unsubscribe.

I unsubscribe from all the topics before I do a disconnect but when I bring the app back to active I get errors on Unsubscribe timed out and then Subscribe timed out.

In addition I'm getting errors on the connection saying it's still connected even though I did a disconnect.

Anyone seeing this? Maybe if someone had a code example of working disconnect and unsubscribe that might help, it's not in the readme.

Thank!

Tony

Always failed to connect to MQTT after changing to new URL

@rh389 Thanks for great work. I can connect to AWS IoT MQTT by this library. But it always failed to connect to MQTT after changing the URL. If the user sign out and sign in to another account the URL will be changed. I call the disconnect and connect to new URL again it will give me an Error: AMQJS0011E Invalid state already connected.

Sending empty MQTT message

Hi, I am trying to send an empty MQTT message on a specified topic. This is a common pattern with MQTT to 'query' the status of an MQTT connected device.

I am using the project in a React Native app and can connect, subscribe and send (non-empty) messages fine. I am not sure how to send and empty message though.

The below code works fine and sends the payload 0 on the topic specified in device.command:

     const _message = new Message('0');
      _message.destinationName = device.command;
      this.onMessageSendHandler(_message);

In order to try and send empty messages I tried to create the new message object in the following two ways both of which returned errors:

  1. to test not passing and parameter to the object creation
     const _message = new Message();
  • Error received: TypeError: undefined is not and object (evaluating 'newPayload.toString')
  1. to test an empty string:
     const _message = new Message('');
  • Error received: Error: AMQJS0011E Invalid state not connected.
  1. to test an empty array:
     const _message = new Message([]);
  • Error received: AMQJS0013E Invalid argument for newPayload.
  1. to test an empty JavaScript object as a string:
     const _message = new Message('{}');
  • Error received: Error: AMQJS0011E Invalid state not connected.
  1. to test an empty JavaScript object:
     const _message = new Message({});
  • Error received: AMQJS0013E Invalid argument for newPayload.

So I am not sure how to send and empty message with this client library. Did I miss something obvious or not so obvious?

AMQJS0004E Ping timed out.

After running app in android device or simulator, it send the first ping req and the ping resp does not arrives to the app. the app sends another ping req and the mosquitto sends the ping resp but it does not arrives and the alert AMQJS0004E Ping timed out is shown.
Using mosquitto, with authentication, linux ubuntu 16, react native through websockets on port 8083

I tried to use the same mosquitto instance directly from browser, using hivemq mqtt web client and everything works, even from the linux command line...

It is clear on mosquitto log that it answers with PING RESP but this never rechas the react native app end point.

Any help?

Thanks

Imo

active?

Is this project active anymore?

keep connection on background

I have a problem with maintaining the mqtt connection. When I turn off the screen on the ios or the application works on the background for about 30 seconds, the connection is immediately closed. I want to stay connected even when working in the background. Is there a way to do this? It is very important to me that if I do not maintain the connection, when turning off the screen I have to re-make the connection, it causes discomfort to the user. Thank you very much for the library. Looking forward to your response

My mqtt is not working when i am using the release version but it is working when i am using it in build format

export const Click = (user) => {
// debugger;
// console.log(user, "coming hear");
return (dispatch) => {
// const { authtoken, field2 } = user;
// console.log(authtoken,"ekvhjwejh");

const client = new Client({ uri: 'ws://192.168.10.111:9001/ws', clientId: 'JOULS ECOTECH243546578989', storage: myStorage });
// set event handlers
client.on('connectionLost', (responseObject) => {
  if (responseObject.errorCode !== 0) {
    console.log(responseObject.errorMessage);
  }
});
const onConnect = () => {

  client.on('messageReceived', (message) => {
    console.log(message?.payloadString);
    dispatch(setAuthtoken(message?.payloadString));
  });
}

client.connect()
  .then(() => {
    // Once a connection has been made, make a subscription and send a message.
    console.log('onConnect');
    return client.subscribe('Jouls_Ecotech_User_Notifications');
  })
  .then(() => {
    const sampleee ={
      "Charging Mode": "Balanced_Mode"
    }
    const message = new Message(JSON.stringify(user));
    message.destinationName = 'Jouls_Ecotech_User_ID';
    // const sample = new Message(JSON.stringify(sampleee));
    // sample.destinationName = 'Jouls_Ecotech_User_Charging Modes';
    client.send(message);
    // client.send(sample);
  }).then(() => {
    onConnect()
  })
  .catch((responseObject) => {
    if (responseObject.errorCode !== 0) {
      console.log('onConnectionLost:' + responseObject.errorMessage);
    }
  })


//   client.onConnectionLost = onConnectionLost;
//   client.onMessageArrived = onMessageArrived;

}
}
my code in this the connection is happning when my app is in build form but when i release it to play store or use its release format it is giving connection error .

Not working on Android

The package doesn't seem to work on Android. It says onConnectionLost:Error: AMQJS0007E Socket error: Unknown socket error. (for the exact same parameters)

Works fine on iOS

Remove Cyclic Dependency

React native recently updated to warn these imports.
One good example copied from react-native console is:

Require cycle: node_modules/react-native-paho-mqtt/src/util.js -> node_modules/react-native-paho-mqtt/src/WireMessage.js -> node_modules/react-native-paho-mqtt/src/util.js

How to disable console logs / trace?

I get a console log for ever message and action the MQTT client takes, is there a way to disable them? I tried using the traceFunction option and the trace option in the client constructor, but that didn't seem to do anything. I'd expect something like "debug: false"

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.

How to use with SSL/TLS + certificate authority file?

I searched around the googles for a while, but wasn't able to come up with anything. How does one use this client with SSL and a certificate authority file? The MQTT.js library has a way to handle it, and the original paho suggests that it's something handled by the browser (eclipse#97), but as we don't have a browser in the RN version, what needs to happen for it to work? We should be able to test it on wss://test.mosquitto.org:1883/

Error code not coming while trying connection with wrong credentials

The errorCode which should have been there when we try to connect to rabbitmq using wrong credentials is not coming and also after checking the code I found out that in the constant file error code 6 should have come in the error response whereas it is giving code 4 in catch message.

Connect to unencrypted Broker in Android 13 SDKVersion 33

We're using a Broker without TLS encryption for our IoT device. After upgrading to Android 13 with SDK Version 33 the connection can't be established anymore. Is there a way to get the connection working without a certificate or do we now need to encrypt?

Thanks for any hints on this!

Try connect to broken when connectionLost

Thank for the library awesome. Please let me ask when the connection is disconnected, it will automatically reconnect ? Since I connect lost get an error message and can not send message to the broken . I do not experience such a phenomenon on my web-based platform.
Looking forward to your response

Unable to connect, connection time out

-"Client.connect"{"willMessage":null,"timeout":30000,"keepAliveInterval":60,"cleanSession":true,"mqttVersion":4}false

-"Pinger.doPing""send PINGREQ"
-"Client._disconnected"1"AMQJSC0001E Connect timed out."
-responseObject: Error: AMQJSC0001E Connect timed out.
at ClientImplementation._disconnected (E:\Apps\hospital_app_react\node_modules\react-native-paho-mqtt\src\ClientImplementation.js:726)
at E:\Apps\hospital_app_react\node_modules\react-native-paho-mqtt\src\ClientImplementation.js:173
at E:\Apps\hospital_app_react\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:256
at _callTimer (E:\Apps\hospital_app_react\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:152)
at Object.callTimers (E:\Apps\hospital_app_react\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:405)
at MessageQueue.__callFunction (E:\Apps\hospital_app_react\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:351)
at E:\Apps\hospital_app_react\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:116
at MessageQueue.__guardSafe (E:\Apps\hospital_app_react\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:314)
at MessageQueue.callFunctionReturnFlushedQueue (E:\Apps\hospital_app_react\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:115)
at t (RNDebuggerWorker.js:1)
-onConnectionLost:undefined

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.