kirillzyusko / react-native-wifi-p2p

Library that provide access for working with wi-fi direct (p2p) module in android.
175 stars 33 forks source link

Example code is not working #53

Open ReactCoder12 opened 2 years ago

ReactCoder12 commented 2 years ago

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,
  },
});
kirillzyusko commented 2 years ago

Hi @ReactCoder12 The issue has a lack of information. First of all could you please give more info about devices you are using (its OS versions etc.)? And second - did you read https://github.com/kirillzyusko/react-native-wifi-p2p#caveats ?

ReactCoder12 commented 2 years ago

Yes I read this but their little different permission for different android versions Can you Please explain How this App run on All Versions of Android I just need to Communicate android devices

ReactCoder12 commented 2 years ago

Iam Using Android 12.0 Version

kirillzyusko commented 2 years ago

Iam Using Android 12.0 Version

You need to enable GPS and ask additional permission for FINE_LOCATION. I think it should be enough. Also if something doesn't work you can check logcat output to understand a reason :)

ReactCoder12 commented 2 years ago

Thank you Now App is running Can you Please explain Little about How to use App means What we need press first create group and then what need to do and also will it need hotspot to make one device as server

ReactCoder12 commented 2 years ago

My Wifi is On But after creating Group in devices Available it gives me Empty array

kirillzyusko commented 2 years ago

Thank you Now App is running Can you Please explain Little about How to use App means What we need press first create group and then what need to do and also will it need hotspot to make one device as server

For communication you can using steps described here: https://github.com/kirillzyusko/react-native-wifi-p2p#sendmessagemessage

and also will it need hotspot to make one device as server My Wifi is On But after creating Group in devices Available it gives me Empty array

As far as I remember you don't need to configure wifi in any special way. Maybe you will need to connect them first time manually (using wifi direct feature in settings, though honestly I don't remember it, and I bet that it should work using only API from this library without any manual configuration).

ReactCoder12 commented 2 years ago

kirillzyusko I connect two devices with wifi direct then open App its crashing On connect button, send Message Button Why this is Crashing even if make or not make create group request

ReactCoder12 commented 2 years ago

I am using Your this Example code https://github.com/kirillzyusko/react-native-wifi-p2p-example/blob/master/App.js on Press Connect gives device cannot be empty. onPress Send file or send Message it gives Attempt to read from field 'java.net.inetAddress android.net.wifi.p2p.Wifi.p2p.WifiP2info.groupOwnerAdress' on a null object reference

Please help me to solve this thats why I am not able to send message to other device

kirillzyusko commented 2 years ago

Hi @ReactCoder12

Sorry, but I don't understand your problem. You describe it in a very generic way... What I can understand is that something doesn't work as you expect. But such info doesn't contain any information about steps you were trying to perform and logs from logcat. Let's go step by step:

  1. Have you tried to connect two devices manually using wifi direct and transfer any information? If yes, then we can confirm, that both devices have a working wifi.
  2. When you open example app - can two devices discover each other?
  3. What happens if you press "connect" button? Please attach a small logcat output (logs should contain info only from the start of example app - please, don't send all logs from your device)

P.S. regarding this:

it gives Attempt to read from field 'java.net.inetAddress android.net.wifi.p2p.Wifi.p2p.WifiP2info.groupOwnerAdress' on a null object reference

Seems like you are trying to read info about groupOwner, but you are not a group owner 🤷‍♂️

kirillzyusko commented 2 years ago

Also you may read old/closed issues. Maybe we already solved this or a similar problem :)

ReactCoder12 commented 2 years ago

Hi kirillzyusko Thank you So mush you help me alot I have last Question and Please explain me in Step which step needs to do first I create wifi direct between two devices Connection Established with wifi Direct. But On App How to use Your App? which steps need to do first.

kirillzyusko commented 2 years ago

It's written in README:

image

Is there anything that confuses you?

ReactCoder12 commented 2 years ago

Here you mean Server side a one Mobile which create group right?

kirillzyusko commented 2 years ago

Here you mean Server side a one Mobile which create group right?

Yes, you are right

Ankush523 commented 5 months ago

@kirillzyusko Does the wifi direct connection between devices only work when the app is present in both the devices? Or is it like any one of the devices can have the app and connect to another device even if doesn't have the app

kirillzyusko commented 5 months ago

@Ankush523 honestly I don't remember - better to check it yourself 👀

Ankush523 commented 5 months ago

I tried out the repo, the connection between the devices is working fine but the send message is not working. The app is getting closed when send message is being clicked.

kirillzyusko commented 5 months ago

@Ankush523 that means that the app has crashed. Without adb logs I'll not be able to help 🤷‍♂️

Ankush523 commented 5 months ago

@kirillzyusko can u tell me how to get the adb log while running the app in a physical device because the app doesnt worj in android studio as u mentioned

kirillzyusko commented 5 months ago

@Ankush523 just run adb logcat