Giter Club home page Giter Club logo

react-native-wifi-p2p's People

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  avatar  avatar

react-native-wifi-p2p's Issues

send Message is not working

when i tried to use send message
I am gettting error "Attemp to invoke virtual method ' java.lang.String java.net.InetAdress.getHostAdress()' on anull object reference

TypeError: undefined is not an object (evaluating '_this.state.devices[0].deviceAddress') why this error

I connected two devices to my home's wifi network but one couldn't find another device through the same network, I tried ACCESS.FINE.LOCATION also as I am using android upper than Android 10. I didn't get any kind of solution. What can be the good npm package to do it well ?? Anyone ,plz help ?? I want to share data between two android devices suggest me any good npm package . Then If I try to connect to wifi direct without manually ,it is not connected . It gives error

Peer to peer audio streaming [Question]

Is it possible to stablish a connection 1/N and instead of sending a local file use an audio stream just as a2dp would do over Bluetooth?

Thank you so much!

DeviceEventEmitter.removeListener is deprecated

Hi, you're using a deprecated way of removing event listener. Currently the supported way of unsubscribing the events is to perform remove() function on subscribtion which is returned by addListener() function. Are you planning to improve this part?
image

index.js line 27

Message and file not working all time

  1. I followed the steps receive msg->send msg but getting different errror in different times though my connection is well formed between two mobile.
    I attached screenshots
    Screenshot_20200708-001816_PassOn

20200708_002409

2nd issue: file not received sometimes and damagrd file or half file received
20200707_011823
20200707_004327

TypeError: TypeError: undefined is not an object (evaluating 'WiFiP2PManager.init')

TypeError: TypeError: undefined is not an object (evaluating 'WiFiP2PManager.init')

This error is located at:
in Share (created by SceneView)
in SceneView (at StackViewLayout.js:784)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in AnimatedComponent (at StackViewCard.js:69)
in RCTView (at View.js:44)
in AnimatedComponent (at screens.native.js:59)
in Screen (at StackViewCard.js:57)
in Card (at createPointerEventsContainer.js:27)
in Container (at StackViewLayout.js:860)
in RCTView (at View.js:44)
in ScreenContainer (at StackViewLayout.js:311)
in RCTView (at View.js:44)
in AnimatedComponent (at StackViewLayout.js:307)
in Handler (at StackViewLayout.js:300)
in StackViewLayout (at withOrientation.js:30)
in withOrientation (at StackView.js:79)
in RCTView (at View.js:44)
in Transitioner (at StackView.js:22)
in StackView (created by Navigator)
in Navigator (at createKeyboardAwareNavigator.js:12)
in KeyboardAwareNavigator (at createAppContainer.js:388)
in NavigationContainer (at App.js:37)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in Root (at connectStyle.js:384)
in Styled(Root) (at App.js:33)
in Provider (at App.js:32)
in App (at withExpoRoot.js:22)
in RootErrorBoundary (at withExpoRoot.js:21)
in ExpoRootComponent (at renderApplication.js:34)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in AppContainer (at renderApplication.js:33)

This error is located at:
in NavigationContainer (at App.js:37)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in Root (at connectStyle.js:384)
in Styled(Root) (at App.js:33)
in Provider (at App.js:32)
in App (at withExpoRoot.js:22)
in RootErrorBoundary (at withExpoRoot.js:21)
in ExpoRootComponent (at renderApplication.js:34)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in AppContainer (at renderApplication.js:33)

Stack trace:
node_modules\react-native-wifi-p2p\index.js:13:40 in initialize
src\screens\Share.js:34:4 in componentDidMount
node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:12144:10 in commitLifeCycles
node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:13496:8 in commitAllLifeCycles
...

Just I am using your example code and try to run the above error occur.
I am using real device for run the code.

Fix `sendFile` promise resolving

Now promise resolves almost instantly
We should handle all process of file transfering and report correct errors if they have accurred.

And fix the documentation (with filePath example, how it should look)

Multiple file transfer at a time

Is it possible to send mutiple files to receiver using this library?
Scenario is receiver will click one time in the receive file button and sender select multiple file and send at one go..

Execution failed for task ':react-native-wifi-p2p:verifyReleaseResources'.

Hi, everytime I try to build my app it always fails:

Configure project :react-native-wifi-p2p
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
WARNING: The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (27.0.3) for Android Gradle Plugin 3.1.4.
Android SDK Build Tools 27.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.

Task :app:bundleReleaseJsAndAssets
warning: the transform cache was reset.
Loading dependency graph, done.
bundle: Writing bundle output to: C:\Users\darrell\dev\idverifier\android\app\build\generated\assets\react\release\index.android.bundle
bundle: Done writing bundle output

error: resource android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
error: resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
C:\Users\darrell.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\4128735aae96be8c7749e766b675672b\res\values-v26\values-v26.xml:9:5-12:13: AAPT: error: resource android:attr/colorError not found.

C:\Users\darrell.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\4128735aae96be8c7749e766b675672b\res\values-v26\values-v26.xml:13:5-16:13: AAPT: error: resource android:attr/colorError not found.

C:\Users\darrell.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\4128735aae96be8c7749e766b675672b\res\values-v26\values-v26.xml:17:5-93: AAPT: error: style attribute 'android:attr/keyboardNavigationCluster' not found.

C:\Users\darrell.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\4128735aae96be8c7749e766b675672b\res\values\values.xml:251:5-69: AAPT: error: resource android:attr/fontStyle not found.

C:\Users\darrell.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\4128735aae96be8c7749e766b675672b\res\values\values.xml:251:5-69: AAPT: error: resource android:attr/font not found.

C:\Users\darrell.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\4128735aae96be8c7749e766b675672b\res\values\values.xml:251:5-69: AAPT: error: resource android:attr/fontWeight not found.

error: failed linking references.

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':react-native-wifi-p2p:verifyReleaseResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 3m 0s
70 actionable tasks: 57 executed, 13 up-to-date


I'm using
"react": "16.6.0-alpha.8af6728",
"react-native": "0.57.4",
"react-native-wifi-p2p": "^0.6.3"

Please help me fix this. Thanks!

CancelConnect() not working.

After successfully executing sendMessage() I am calling cancelConnect() to cancel the connection but it is throwing error -

{"code":2,"message":"Operation failed because the framework is busy and unable to service the request"}.

Can you please help me out.

subscribeOnPeersUpdates doesn't fire at all it doesn't show me the connected devices Test on Android 10

subscribeOnPeersUpdates doesn't fire at all it doesn't show me the connected devices on Android 10

async componentDidMount() {
try {

      await initialize();
      // since it's required in Android >= 6.0
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
              'title': 'Access to wi-fi P2P mode',
              'message': 'ACCESS_COARSE_LOCATION'
          }
      )

      console.log(granted === PermissionsAndroid.RESULTS.GRANTED ? "You can use the p2p mode" : "Permission denied: p2p mode will not work");
       console.log("inside")
      subscribeOnPeersUpdates(this.handleNewPeers);
      subscribeOnConnectionInfoUpdates(this.handleNewInfo);
      subscribeOnThisDeviceChanged(this.handleThisDeviceChanged);

      const status = await startDiscoveringPeers();
      console.log('startDiscoveringPeers >>>>>>>>: ', status);
  } catch (e) {
      console.error("error >>>>",e);
  }

}

Set Group Owner operating frequency band

I am using this module to write an app that connects many devices to one (the Group Owner).

Tinkering with some test devices, I found that some create a WiFi Direct AP on the 5 GHz band, while others default to 2.4 GHz.

This may result in clients that only use the 2.4GHz band (such as low-end devices) to not find 5GHz WiFi Direct APs.

Is there any way to force a Group Owner to use the 2.4 GHz band to maintain compatibility with older devices?

Remove group but handleNewPeers method triggering after long time

scenario is: Receiver create group-> Sender immediately can see receiver but then if receiver removes the group, it is not immediately updated on sender mobile i.e. receiver is still avaialble and handleNewPeers not called immediately but after long time..
Is it normal as wifi direct taking time for this update or bug?

Also found that If I refresh app.js on sender and componentdidmount called and device information immediately updated.

and another point observed: Create group by receiver->connect by sender-> remove group by receiver -> immediately updated to sender and receiver not shown on sender mobile.

a proposal: use firebase testlab

What do you think about inserting some CI to your development?
You can first test using mocks, but then you can test using real devices with firebase testing lab.
It won't help you to connect to actual devices probably, but you can check things like initializing discover peers. This way, you'd be able to generally test on new devices and android versions you do not possess.
it would have prevented my issue for examaple:)

unsubscribeFromPeersUpdates : EventEmitter.removeListener() : Method has been deprecated

Hi, I'm using this lib (well at least trying to ^^) in a Expo project.

I was wondering if you're planning to change the removeListener() Method as adviced :

 WARN  EventEmitter.removeListener('WIFI_P2P:PEERS_UPDATED', ...): Method has been deprecated. Please instead use `remove()` on the subscription returned by `EventEmitter.addListener`.

It happends only when I try to use unsubscribeFromPeersUpdates() on unmount.

I'm using :

"react-native": "0.69.6",
"expo": "~46.0.13",
"react-native-wifi-p2p": "^3.2.2"

Although I shouldn't post this in a issue ... I was wondering if this lib suit for my case ... I'm trying to create some "LAN networking". Can I use this lib to broadcast data (I mean array / objects ) to multiple devices connected in direct wifi ?

How do peers communicate with each other?

Connecting, Disconnecting, forming a group everything is fine. But how do peers exchange information? sendMessage() api is not available as of now according to README

How do I broadcast available services of a device to its peers? Can I atleast get an IP address so that I can communicate manually with other devices?

[feature request] requestGroupInfo equivalent

Currently, there's a function called getGroupPassphraseInfo, but it'll only give you the passphrase.
I need to check who are the other peers in my group.
I need the groupOwner's and clients' macAddresses.

I believe the best way to achieve this, is to create additional method requestGroupInfo:

    @ReactMethod
    public void getGroupInfo(final Promise promise) {
        manager.requestGroupInfo(channel, new WifiP2pManager.GroupInfoListener() {
            @Override
            public void onGroupInfoAvailable(WifiP2pGroup group) {
                promise.resolve(group);
            }
        });
    }

and an appropriate js method:
const getGroupInfo = () => WiFiP2PManager.getGroupInfo();

Maybe you should also deprecate the getGroupPassphraseInfo method and remove it in the next breaking change.

Require Group Passphrase

Hi,
This is a great library. Once a group is created, we need passphrase from it.

Currently, only way to get it is manually and not programmatically from i.e Settings -> WIFI Direct -> Passphrase

Here is a snippet shared by android developer https://developer.android.com/training/connect-devices-wirelessly/wifi-direct#java

manager.requestGroupInfo(channel, new GroupInfoListener() {
  @Override
  public void onGroupInfoAvailable(WifiP2pGroup group) {
      String groupPassword = group.getPassphrase();
  }
});

App Crashing when clicking on Connect Button

Whenever i am clicking the Connect , Create Group or Send Button the App is Crashing and when i am pressing other buttons nothing is happening, can anyone please help me with this. The app is crashing again and again and to no success i was able to fix it.

Is there a way to get device Address with ipv4 format ?

Hi I am making project with android tab that will communicate via tcp-socket through wifi-internet.
So I used this module to get all devices list in same wifi-network that I can connect to.
But it returns only mac addresses. Tcp library that i am using allows only ipv4 format address.
Is there any way to get device Address with ipv4 format ?

App crashes on starting up

Hi,

I'm getting this error on successful build. Can you please help?

Attempt to invoke virtual method 'android.net.wifi.p2p.WifiP2pManager$Channel android.net.wifi.p2p.WifiP2pManager.initialize(android.content.Context, android.os.Looper, android.net.wifi.p2p.WifiP2pManager$ChannelListener)' on a null object reference
init
WiFiP2PManagerModule.java:81
invoke
Method.java
invoke
JavaMethodWrapper.java:372
invoke
JavaModuleWrapper.java:160
run
NativeRunnable.java
handleCallback
Handler.java:790
dispatchMessage
Handler.java:99
dispatchMessage
MessageQueueThreadHandler.java:29
loop
Looper.java:164
run
MessageQueueThreadImpl.java:192
run
Thread.java:764

Group creation is not defined on real-time

Device A:

  • Device: Android
  • OS: API 29 (Q)

Device B:

  • Device: Android
  • OS: API 28 (P)

Using the master version of react-native-wifi-p2p or the project itself for demonstration of the library API, I'm not able to represent a group creation in real-time on the opposite device under these two devices, by getting the available devices, even though it is available on connection info. Is this a known issue for the newer Android devices or so? Without this, I can't either connect.

To Reproduce
Steps to reproduce the behavior:

  1. Open the example app
  2. Create Group
  3. On the guest (client that will connect to the group owner), press Get Available Devices button, and you'll get "isGroupOwner": false.

Example in documentation is incorrect

It refers to react-native-android-p2p-wifi, when the package is actually named react-native-wifi-p2p.

When I try running the example, it doesn't work, and I don't know if this is because the example is incorrect or if there is something wrong with my test setup - the example needs to be reviewed and updated to ensure it is correct.

Devices is not showing in android 9

The nearby devices list is showing in android 7 and the lower version phone, but not showing in android 9 . Can you please help me on that

App crashes during Get Connection Info

Looks like there is an issue in WiFiP2PManagerModule. Also, the getAvaibleDevices method returns an empty array. I with Mi A1 and Xiomi Poco F1.

FATAL EXCEPTION: main
Process: com.examples, PID: 11146
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.net.InetAddress.getHostAddress()' on a null object reference
at io.wifi.p2p.WiFiP2PManagerModule$1.onConnectionInfoAvailable(WiFiP2PManagerModule.java:63)
at android.net.wifi.p2p.WifiP2pManager$Channel$P2pHandler.handleMessage(WifiP2pManager.java:822)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:172)
at android.app.ActivityThread.main(ActivityThread.java:6590)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

getAvailablePeers always returns empty array

1st: thanks for that awesome repo.

I tested it on my galaxy S6 (android 7.0) and also on S9 (android 8.0).
I'am running the same code on both phones.
Everything works fine on S6, it detects my wifi-printer, but on S9 getAvailablePeers always returns an empty array.

Any idea why ?

I need mesh topology

I need a p2p connection between android devices, 3 different devices should be able to exchange data with each other, but without a server. Only clients should be able to communicate with each other. However, when I look at the document, we can only use the star topology. The mesh topology I need. How can I get this topology with this library?

File path and file name on receiver end

  1. Can you please let me know where can I change the receive file name and path as I see there is hardcoded path and extension is always jpg where the file is getting saved.

  2. And also why jpg file not reflected in gallery on receiver phone after succesfull receive.

disconnect implementation doesn't match the name 'disconnect'

currently the implementation is:

@ReactMethod
    public void disconnect(final Callback callback) {
        manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                callback.invoke();
            }

            @Override
            public void onFailure(int reasonCode) {
                callback.invoke(Integer.valueOf(reasonCode));
            }
        });
    }

However, according to its docs cancelConnect - 'Cancel any ongoing p2p group negotiation'.

disconnect should be like in this stackoverflow answer:

public static void disconnect() {
    if (mManager != null && mChannel != null) {
        mManager.requestGroupInfo(mChannel, new GroupInfoListener() {
            @Override
            public void onGroupInfoAvailable(WifiP2pGroup group) {
                if (group != null && mManager != null && mChannel != null) {
                    mManager.removeGroup(mChannel, new ActionListener() {

                        @Override
                        public void onSuccess() {
                            Log.d(TAG, "removeGroup onSuccess -");
                        }

                        @Override
                        public void onFailure(int reason) {
                            Log.d(TAG, "removeGroup onFailure -" + reason);
                        }
                    });
                }
            }
        });
    }
}

failed to connect to /192.168.49.1 (port 8988) from /192.168.49.1 (port 47274) after 5000ms: isConnected failed: ECONNREFUSED (Connection refused)

I am getting this error while sending the file or message. I have followed exactly the same steps for sending a file as mentioned but still, I am not able to send it. Can you please help me out?

My code is as below. I was able to connect the two devices successfully but while sending file I am getting the above error.

 sendMessage() {
    getConnectionInfo().then((info) => {
      console.log('Connection Info Send', info);
      if (info.groupOwnerAddress !== null) {
        ImagePicker.openPicker({
          cropping: false,
          includeBase64: true,
          mediaType: 'photo',
        })
          .then((image) => {
            console.log('Image', image);
            sendFile(image.path);
          })
          .catch((e) => {
            console.log('Photo picker error', e);
          });
      }
    });
  }
onStartInvestigate = () => {
    PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
      {
        title: 'Access to wi-fi P2P mode',
        message: 'ACCESS_COARSE_LOCATION',
      },
    )
      .then((granted) => {
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('You can use the p2p mode');
        } else {
          console.log('Permission denied: p2p mode will not work');
        }
      })
      .then(() => {
        startDiscoveringPeers()
          .then((val) => {})
          .catch((e) => {
            console.log('ERROR DISCOVERING PEERS', e);
          });
      })
      .then(() => {
        console.log(`Peers searching started`);
        subscribeOnPeersUpdates(({devices}) => {
          console.log(`New devices available: ${JSON.stringify(devices)}`);
          if (devices.length > 0) {
            connect(devices[0].deviceAddress)
              .then(() => {
                console.log('Successfully connected');
                getConnectionInfo().then((info) => {
                  console.log('Connection Info', info);
                  receiveFile().then((path) =>
                    console.log(`Path to file: ${path}`),
                  );
                });
              })
              .catch((e) => {
                console.log('Error connecting', e);
              });
          }
        });
        // getAvailablePeers().then((peers) => {
        //   console.log(peers);
        //   if (peers.devices.length > 0) {

        //   }
        // });
      })
      .catch((err) =>
        console.error(
          `Something is gone wrong. Maybe your WiFi is disabled? Error details: ${err}`,
        ),
      );
  };

Data flow clarifications

Based on the documentation, I need to clarify some workflow concerns.

  • It seems like data flow, that is sending messages or files, is only available in the form of the client sending data to the server. Can the server use the same methods and send messages/files back to the client?
  • If no, then what would be the ideal design for 2-way communication between devices? As I understand that a device can be both a client and a server but not simultaneously.

I tried to search for specific protocols regarding WiFi Direct but I can't seem to find anything that states how data is being transferred from one device to another.

Thanks.

Example code is not working

I used Example code but Its not working its not able to show devices and not able to connect with devices
Please help to run this Example I want to send string or file to other device.

Using Example of Usage

import React, { PureComponent } from 'react';
import {
  StyleSheet,
  View,
  Button
} from 'react-native';
import {
  initialize,
  startDiscoveringPeers,
  stopDiscoveringPeers,
  unsubscribeFromPeersUpdates,
  unsubscribeFromThisDeviceChanged,
  unsubscribeFromConnectionInfoUpdates,
  subscribeOnConnectionInfoUpdates,
  subscribeOnThisDeviceChanged,
  subscribeOnPeersUpdates,
  connect,
  cancelConnect,
  createGroup,
  removeGroup,
  getAvailablePeers,
  sendFile,
  receiveFile,
  getConnectionInfo,
  getGroupInfo,
  receiveMessage,
  sendMessage,
} from 'react-native-wifi-p2p';
import { PermissionsAndroid } from 'react-native';

type Props = {};
export default class App extends PureComponent<Props> {
  state = {
    devices: []
  };

  async componentDidMount() {
      try {
          await initialize();
          // since it's required in Android >= 6.0
          const granted = await PermissionsAndroid.request(
              PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
              {
                  'title': 'Access to wi-fi P2P mode',
                  'message': 'ACCESS_COARSE_LOCATION'
              }
          );

          console.log(granted === PermissionsAndroid.RESULTS.GRANTED ? "You can use the p2p mode" : "Permission denied: p2p mode will not work");

          subscribeOnPeersUpdates(this.handleNewPeers);
          subscribeOnConnectionInfoUpdates(this.handleNewInfo);
          subscribeOnThisDeviceChanged(this.handleThisDeviceChanged);

          const status = await startDiscoveringPeers();
          console.log('startDiscoveringPeers status: ', status);
      } catch (e) {
          console.error(e);
      }
  }

  componentWillUnmount() {
    unsubscribeFromConnectionInfoUpdates(this.handleNewInfo);
    unsubscribeFromPeersUpdates(this.handleNewPeers);
    unsubscribeFromThisDeviceChanged(this.handleThisDeviceChanged)
  }

  handleNewInfo = (info) => {
    console.log('OnConnectionInfoUpdated', info);
  };

  handleNewPeers = ({ devices }) => {
    console.log('OnPeersUpdated', devices);
    this.setState({ devices: devices });
  };

  handleThisDeviceChanged = (groupInfo) => {
      console.log('THIS_DEVICE_CHANGED_ACTION', groupInfo);
  };

  connectToFirstDevice = () => {
      console.log('Connect to: ', this.state.devices[0]);
      connect(this.state.devices[0].deviceAddress)
          .then(() => console.log('Successfully connected'))
          .catch(err => console.error('Something gone wrong. Details: ', err));
  };

  onCancelConnect = () => {
      cancelConnect()
          .then(() => console.log('cancelConnect', 'Connection successfully canceled'))
          .catch(err => console.error('cancelConnect', 'Something gone wrong. Details: ', err));
  };

  onCreateGroup = () => {
      createGroup()
          .then(() => console.log('Group created successfully!'))
          .catch(err => console.error('Something gone wrong. Details: ', err));
  };

  onRemoveGroup = () => {
      removeGroup()
          .then(() => console.log('Currently you don\'t belong to group!'))
          .catch(err => console.error('Something gone wrong. Details: ', err));
  };

  onStopInvestigation = () => {
      stopDiscoveringPeers()
          .then(() => console.log('Stopping of discovering was successful'))
          .catch(err => console.error(`Something is gone wrong. Maybe your WiFi is disabled? Error details`, err));
  };

  onStartInvestigate = () => {
      startDiscoveringPeers()
          .then(status => console.log('startDiscoveringPeers', `Status of discovering peers: ${status}`))
          .catch(err => console.error(`Something is gone wrong. Maybe your WiFi is disabled? Error details: ${err}`));
  };

  onGetAvailableDevices = () => {
      getAvailablePeers()
          .then(peers => console.log(peers));
  };

  onSendFile = () => {
      //const url = '/storage/sdcard0/Music/Rammstein:Amerika.mp3';
      const url = '/storage/emulated/0/Music/Bullet For My Valentine:Letting You Go.mp3';
      PermissionsAndroid.request(
                  PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                  {
                      'title': 'Access to read',
                      'message': 'READ_EXTERNAL_STORAGE'
                  }
              )
          .then(granted => {
              if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                  console.log("You can use the storage")
              } else {
                  console.log("Storage permission denied")
              }
          })
          .then(() => {
              return PermissionsAndroid.request(
                  PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                  {
                      'title': 'Access to write',
                      'message': 'WRITE_EXTERNAL_STORAGE'
                  }
              )
          })
          .then(() => {
              return sendFile(url)
                  .then((metaInfo) => console.log('File sent successfully', metaInfo))
                  .catch(err => console.log('Error while file sending', err));
          })
          .catch(err => console.log(err));
  };

  onReceiveFile = () => {
      PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
          {
              'title': 'Access to read',
              'message': 'READ_EXTERNAL_STORAGE'
          }
      )
          .then(granted => {
              if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                  console.log("You can use the storage")
              } else {
                  console.log("Storage permission denied")
              }
          })
          .then(() => {
              return PermissionsAndroid.request(
                  PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                  {
                      'title': 'Access to write',
                      'message': 'WRITE_EXTERNAL_STORAGE'
                  }
              )
          })
          .then(() => {
              return receiveFile('/storage/emulated/0/Music/', 'BFMV:Letting You Go.mp3')
                  .then(() => console.log('File received successfully'))
                  .catch(err => console.log('Error while file receiving', err))
          })
          .catch(err => console.log(err));
  };

  onSendMessage = () => {
      sendMessage("Hello world!")
        .then((metaInfo) => console.log('Message sent successfully', metaInfo))
        .catch(err => console.log('Error while message sending', err));
  };

  onReceiveMessage = () => {
      receiveMessage()
          .then((msg) => console.log('Message received successfully', msg))
          .catch(err => console.log('Error while message receiving', err))
  };

  onGetConnectionInfo = () => {
    getConnectionInfo()
        .then(info => console.log('getConnectionInfo', info));
  };

  onGetGroupInfo = () => {
      getGroupInfo()
        .then(info => console.log('getGroupInfo', info));
  };

  render() {
    return (
      <View style={styles.container}>
        <Button
          title="Connect"
          onPress={this.connectToFirstDevice}
        />
        <Button
          title="Cancel connect"
          onPress={this.onCancelConnect}
        />
        <Button
          title="Create group"
          onPress={this.onCreateGroup}
        />
        <Button
          title="Remove group"
          onPress={this.onRemoveGroup}
        />
        <Button
          title="Investigate"
          onPress={this.onStartInvestigate}
        />
        <Button
          title="Prevent Investigation"
          onPress={this.onStopInvestigation}
        />
        <Button
          title="Get Available Devices"
          onPress={this.onGetAvailableDevices}
        />
        <Button
          title="Get connection Info"
          onPress={this.onGetConnectionInfo}
        />
        <Button
          title="Get group info"
          onPress={this.onGetGroupInfo}
        />
        <Button
          title="Send file"
          onPress={this.onSendFile}
        />
        <Button
          title="Receive file"
          onPress={this.onReceiveFile}
        />
        <Button
          title="Send message"
          onPress={this.onSendMessage}
        />
        <Button
          title="Receive message"
          onPress={this.onReceiveMessage}
        />
      </View>
    );
  }
}

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

transmit an image from a camera

I'm starting a project in which I need to get the images from a camera via wifi, is it possible to do this through this lib, if so, how?

Thank you for your attention, hug.

Unable to connect [Error: failed to connect to /192.168.49.1 (port 8988) from /192.168.49.1 (port 37003) after 5000ms: isConnected failed: ECONNREFUSED (Connection refused)]

Repeatedly getting this while using sendMessage() and sendFile().
My code is as follows -

import * as WiFiP2P from 'react-native-wifi-p2p';

export const sendFilesToServer = (macAddr, files) => {
    console.log(files, macAddr);
    files.forEach(file => {
        WiFiP2P.connect(macAddr)
            // Resolve connection details using getConnectionInfo
            // .then(() => WiFiP2P.createGroup())
            .then(() => WiFiP2P.getConnectionInfo())
            .then(() => WiFiP2P.getAvailablePeers())
            // Send file metadata using sendMessage()
            .then(() => console.log(file.name))
            .then(() => {
                console.log('SENDING message');
                return WiFiP2P.sendMessage(file.name);
            })
            // Send file
            .then(() => {
                console.log('SENDING file');
                return WiFiP2P.sendFile(file.uri);
            })
            .catch(err => console.log('Unable to connect', err));
    });
}

export const receiveFromClient = () => {
    console.log('Can receive now');
    // Receive file metadata using receiveMessage()
    WiFiP2P.createGroup()
        .then(() => WiFiP2P.receiveMessage())
        // .then(() => {
        //     return PermissionsAndroid.request(
        //         PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        //         {
        //             'title': 'Access to write',
        //             'message': 'WRITE_EXTERNAL_STORAGE'
        //         }
        //     )
        // })

        // Receive file and store it based on the metadata
        .then(message => {
            console.log('Received message ', message);
            return WiFiP2P.receiveFile('/storage/emulated/0/Music/', message);
        })
        .catch(err => console.log(err));
}

EDIT : In addition, whenever the server tries to run createGroup(), it always returns with the error as follows
{ "code" : 2, "message": "Operation failed because the framework is busy and unable to service the request" }

I had same problem also

when I searched available device from galaxy s7 (android version 8.0). It returned empty array. but when I searched available device from galaxy note4 (andorid version 6.0.1). It returned available device. I should make it work on android 8.0. Do you know why It is not work on specific version and can you fix it?

Thank you.

handleThisDeviceChanged method not working

After entering to the application or changing the WIFI enable or disable this method doesn't trigger as need to get the own device information like name , address etc.

Cannot connect devices, plus getting an error in Android O

Cannot connect to groups.

In Android O, I'm getting an error "Operation failed due to an internal error"; after the location permission is provided.

The sample app was created from the example of usage from README.md. I've just added a view to output the contents of console.log.

Screenshot of the Error
Error Pic

Note:

  1. My repo containing the code can be found here
  2. The apk for the sample app can be downloaded from here

How do I connect two devices running this app? I'm not able to join any groups.

Task :react-native-wifi-p2p:compileDebugJavaWithJavac FAILED

Getting this error:-
I rechecked linking everything is same as defined in documentation.

Note:-
I have changed the library's gradle version to 3.3.1. and sdks to 28

> Task :react-native-wifi-p2p:compileDebugJavaWithJavac FAILED
Gradle may disable incremental compilation as the following annotation processors are not incremental: databinding-compiler-3.3.1.jar (androidx.databinding:databinding-compiler:3.3.1).
Consider setting the experimental feature flag android.enableSeparateAnnotationProcessing=true in the gradle.properties file to run annotation processing in a separate task and make compilation incremental.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-wifi-p2p:compileDebugJavaWithJavac'.
> javax/xml/bind/JAXBException

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s

i tried adding android.enableSeparateAnnotationProcessing=true but it generates another error

React-Native Versions:

  "dependencies": {
    "react": "16.8.3",
    "react-native": "0.59.8",
    "react-native-wifi-p2p": "^0.6.5"
  }

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.