Calling the particle API in react-native

Hi there :wave:

Thank you for checking my question.
I am having problem while calling particle API in react-native

I am calling 192.168.0.1/scan-ap 192.168.0.1/public-key 192.168.0.1/configure-ap 192.168.0.1/connect-ap

And I can get the response {r:0} after call connect-ap but it’s still not connecting to device.
Should I use particle library for calling apis? I am just calling them with fetch. But I don’t know which one should I use in react-native.

Here are my codes so kindly check them. Thanks

import RSAKey from "react-native-rsa";

  const encryptPassword = (derKey, password) => {
    const keyModString = derKey.slice(28 * 2, 157 * 2);
    const keyExpString = derKey.slice(159 * 2, 162 * 2);
    let rsa = new RSAKey();
    const publicKey = {
      n: keyModString,
      e: keyExpString
    };
    publicKeyString = JSON.stringify(publicKey);
    rsa.setPublicString(publicKeyString); //expects JSON string object with modulus field (n) and exponent field (e)
    let encryptedPassword = rsa.encrypt(password);
    return encryptedPassword;
  }

  useEffect(() => {
    const encryptedPass = encryptPassword(route.params.key, route.params.password);
    const payload = {
      idx: 1,
      ssid: route.params.device.ssid,
      pwd: encryptedPass,
      sec: route.params.device.sec,
      ch: route.params.device.ch
    };
    console.log(payload)
    fetch(queryString.stringifyUrl({
      url: deviceUrl + '/configure-ap',
      query: payload,
    }), {
      method: 'POST'
    }).then((response) => {
      return response.json();
    }).then((resp) => {
      if(resp && resp.r === 0) {
        setStatus('Bringing device online.')
        onConnectAp();
      } else {
        Alert.alert('', 'There is a problem while setup wifi on device');
        navigation.goBack();
      }
    }).catch(err => {
      console.log(err)
      Alert.alert('', err.toString());
    })
  }, [])

  const onConnectAp = () => {
    fetch(queryString.stringifyUrl({
      url: deviceUrl + '/connect-ap',
      query: {idx: 1},
    }), {
      method: 'POST'
    }).then((response) => {
      return response.json();
    }).then((resp) => {
      if(resp && resp.r === 0) {
        setStatus('Adding to your device list.')
        onAddToDevice();
      } else {
        Alert.alert('', 'There is a problem while connecting to device');
        navigation.goBack();
      }
    }).catch(err => {
      console.log(err)
    })
  }

Hi,
I am not familiar with React so I cannot help you on the code level.
Every time I had to do this in the past, I would refer to this fantastic note from Rickkas7:

Can I suggest you run through it manually to better understand the process and only then you implement it in React?

Good luck!
Gustavo.

Thank you for your reply @gusgonnet
I already solved the problem and it’s working well now.
Thanks

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.