Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help required #100

Open
anuragkaushik10 opened this issue Jun 26, 2024 · 8 comments
Open

Help required #100

anuragkaushik10 opened this issue Jun 26, 2024 · 8 comments

Comments

@anuragkaushik10
Copy link

anuragkaushik10 commented Jun 26, 2024

Hey @kirillzyusko and team,

I am building an application where one user is the receiver and the other is the sender, even when there is no internet connection.

I have achieved this feature using react-native-tcp, but it requires too much manual intervention. To make it more automatic, I discovered this library.

However, I am now unsure if this library supports large base64 strings.

Currently, I can call the connect() function successfully, as it doesn't throw an error, indicating the devices are connected.

My next step is to send the actual base64 string to the receiver.

Here is my actual code:

import React, { useEffect, useState } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Button,
  PermissionsAndroid,
  TouchableOpacity,
  Alert,
} from 'react-native';
import WifiP2P, {
  connect,
  initialize,
  receiveMessage,
  sendMessage,
  startDiscoveringPeers,
  stopDiscoveringPeers,
  subscribeOnPeersUpdates,
} from 'react-native-wifi-p2p';
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';

const P2P = () => {
  const [peers, setPeers] = useState(null);
  const [data, setData] = useState('');
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    checkPermission();
  }, []);

  const checkPermission = async () => {
    try {
      const locationPermission = await check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
      if (locationPermission === RESULTS.GRANTED) {
        initializeWiFiDirect();
      } else {
        requestPermission();
      }
    } catch (error) {
      console.error('Error checking permission:', error);
    }
  };

  const requestPermission = async () => {
    try {
      const result = await request(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
      if (result === RESULTS.GRANTED) {
        initializeWiFiDirect();
      } else {
        console.log('Location permission denied');
      }
    } catch (error) {
      console.error('Error requesting permission:', error);
    }
  };

  const initializeWiFiDirect = async () => {
    try {
      console.log('WiFi Direct initialized');
      subscribeToPeersChanges();
    } catch (error) {
      console.error('Failed to initialize WiFi Direct:', error);
    }
  };

  const subscribeToPeersChanges = () => {
    const discoverPeersSubscription = subscribeOnPeersUpdates((deviceList) => {
      setPeers(deviceList);
    });
    return () => {
      discoverPeersSubscription.remove();
    };
  };

  const discoverPeers = async () => {
    try {
      setPeers(null);
      await startDiscoveringPeers();
    } catch (error) {
      console.error('Error discovering peers:', error);
    }
  };

  const connectToPeer = async (deviceAddress) => {
    try {
      console.log(deviceAddress);
      await connect(deviceAddress);
      Alert.alert('Connected');
      setConnected(true);
      sendData(deviceAddress);
      await stopDiscoveringPeers();
    } catch (err) {
      console.log(err);
    }
  };

  const sendData = async (deviceAddress) => {
    try {
      await sendMessage(deviceAddress, 'anurag');
      Alert.alert('Data Sent');
    } catch (e) {
      console.log(e);
    }
  };

  const receiveData = async () => {
    try {
      console.log('receiveData');
      receiveMessage()
        .then((msg) => console.log('Message received successfully', msg))
        .catch((err) => console.log('Error while receiving message', err));

      Alert.alert('Data Received');
    } catch (e) {
      console.log(e);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>WiFi Direct Example</Text>
      <Button title="Discover Peers" onPress={discoverPeers} />
      <Text style={styles.subtitle}>Available Peers:</Text>
      {peers?.devices.length > 0 &&
        peers?.devices.map((peer) => (
          <TouchableOpacity
            style={{ backgroundColor: 'red', padding: 20 }}
            key={peer.deviceAddress}
            onPress={() => connectToPeer(peer.deviceAddress)}>
            <Text style={{ color: 'white' }}>{peer.deviceName}</Text>
          </TouchableOpacity>
        ))}
      <Button title="Receive Data" onPress={receiveData} />
      {data && <Text>{data}</Text>}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
 }
})

Please take a look and let me know if any further adjustments are required.

@kirillzyusko
Copy link
Owner

What is the size of the string? Does it exceed 16Mb?

@anuragkaushik10
Copy link
Author

Thankyou for your prompt response.

String size will not exceed 16mb

@kirillzyusko
Copy link
Owner

Okay, why can't you use sendFile? I guess it's more suitable?

But overall sending base64 also should work - does it throw any particular error?

@anuragkaushik10
Copy link
Author

Here you go getting same error when using sendFile() and sendMessage()

image

@kirillzyusko
Copy link
Owner

@anuragkaushik10
Copy link
Author

Okay I will do but before that.

The steps ->

  1. Search for devices using startDiscoveringPeers();
  2. After this by passing the device address I will connect the device using connect(deviceAddress)
  3. Start to using sendMessage or sendFile functions on sender side and simultaneously call receiveMessage and receiveFile functions on receiver side.

@anuragkaushik10
Copy link
Author

anuragkaushik10 commented Jun 27, 2024

Hey when following the steps mentioned in README for sending message.

Calling createGroup() gives the following error

image

++++

Also calling getConnectionInfo() after calling createGroup() gives the following message

{"groupFormed": true, "groupOwnerAddress": {"hostAddress": "host:name", "isLoopbackAddress": false}, "isGroupOwner": false}

@kirillzyusko
Copy link
Owner

Calling createGroup() gives the following error

@anuragkaushik10 Can you share adb logs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants