Skip to content

Instantly share code, notes, and snippets.

@johntvogt
Created October 20, 2020 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johntvogt/ecdc695362e36057ae98c5c6aa4024f4 to your computer and use it in GitHub Desktop.
Save johntvogt/ecdc695362e36057ae98c5c6aa4024f4 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from 'react'
import { View, StyleSheet, Text, TouchableOpacity, NativeModules, Button, NativeEventEmitter, ActivityIndicator, Alert, RefreshControl } from 'react-native'
import { connect } from 'react-redux'
import SafeArea from '../components/SafeArea'
import PillButton from '../components/PillButton'
import store, { AppState } from '../store'
import { mergeAuthFlow } from '../store/auth-flow/actions'
import { mergeProgress } from '../store/progress/actions'
import { mergeAppliance } from '../store/appliance/actions'
import { colors, fonts, window } from '../utils/shared-styles'
import { ScreenRootProps } from '../utils/types'
import { ApplianceState } from '../store/appliance/types'
import { ScrollView } from 'react-native-gesture-handler'
import WifiProvisioningNative from '../native/WifiProvisioningNative'
import * as BluetoothService from '../services/bluetooth'
interface PickerCellProps {
label: string
value: string
onPress: () => void
}
interface ConnectToWifiScreenProps extends ScreenRootProps {
appliance: ApplianceState
}
const ConnectToWifiScreen: React.FunctionComponent<ConnectToWifiScreenProps> = ({ navigation, appliance }) => {
const eventEmitter = new NativeEventEmitter(NativeModules.WifiProvisioningNativeNotifications)
let applicationFoundSubscription
let deletedSubscription
let connectedSubscription
let failedToConnectSubscription
let savedNetworksFoundSubscription
let networksFoundSubscription
let deviceReconnectRequiredSubscription
let deleteFailedSubscription
const [selectedSSID, setSelectedSSID] = useState("")
const [availableNetworks, setAvailableNetworks] = useState([] as string[])
const [savedNetworks, setSavedNetworks] = useState([] as string[])
const { id: selectedUUID } = appliance
const [shouldScanForNetworks, setShouldScanForNetworks] = useState(false)
const [loading, setLoading] = useState(false)
const [errorMessage, setErrorMessage] = useState("")
function onButtonPress(index, isSaved) {
const selectedSSID = isSaved ? savedNetworks[index] : availableNetworks[index]
WifiProvisioningNative.didSelectNetwork(selectedUUID, index, isSaved, selectedSSID)
navigation!.navigate("ProvideWifiPassword", { selectedSSID, selectedUUID })
}
async function handleActive() {
await WifiProvisioningNative.disconnectFromAppliances()
await WifiProvisioningNative.removeWifiNotifications()
await WifiProvisioningNative.setUpWifiNotifications()
await BluetoothService.disconnectConnectedDevices()
if (selectedUUID == undefined) {
navigation!.navigate("PairScreen")
return
}
setLoading(true)
console.log('Searcing for Devices')
WifiProvisioningNative.searchForDevices(selectedUUID)
}
function connectAndSearch() {
WifiProvisioningNative.connectToAppliance(selectedUUID)
}
function scanForNetworks() {
setLoading(true);
WifiProvisioningNative.searchForNetworks(selectedUUID)
}
function deleteNetwork(index, ssid) {
setAvailableNetworks([])
setSavedNetworks([])
WifiProvisioningNative.deleteNetwork(index, selectedUUID, ssid)
store.dispatch(mergeAppliance({ connected: false, wifiConnected: false, isProvisioned: false }))
}
useEffect(() => {
setUpEventListeners()
handleActive()
navigation?.setParams({refresh: scanForNetworks})
console.log(navigation?.state?.params);
return () => {
WifiProvisioningNative.disconnectFromAppliances()
console.log('UNMOUNTING')
eventEmitter.removeAllListeners
eventEmitter.removeSubscription
applicationFoundSubscription.remove()
deletedSubscription.remove()
connectedSubscription.remove()
failedToConnectSubscription.remove()
savedNetworksFoundSubscription.remove()
networksFoundSubscription.remove()
deviceReconnectRequiredSubscription.remove()
deleteFailedSubscription.remove()
}
}, [])
const networkDeletionConfirmation = (ssid, index) => {
Alert.alert(
'Remove Saved Network \n ' + ssid + "?",
'',
[
{
text: 'Yes',
style: 'destructive',
onPress: () => deleteNetwork(index, ssid)
},
{
text: 'Cancel'
}
],
{ cancelable: false }
)
}
const setUpEventListeners = () => {
applicationFoundSubscription = eventEmitter.addListener('appliancesFound', (data) => {
console.warn('datasss for appliance found', data)
console.warn('selectedUUID', selectedUUID)
connectAndSearch()
})
console.log('SEARCHING FOR DEVICES', selectedUUID);
deletedSubscription = eventEmitter.addListener('deleted', (data) => scanForNetworks())
connectedSubscription = eventEmitter.addListener('connected', (data) => {
// setShouldScanForNetworks(true)
console.warn('connected to device')
setTimeout(scanForNetworks, 5000)
})
failedToConnectSubscription = eventEmitter.addListener('failedToConnect', (data) => {
setLoading(false)
console.warn("failed to pair")
setErrorMessage("Could not connect to Drinkmaker, please make sure Drinkmaker is in range and bluetooth is on for your device")
})
savedNetworksFoundSubscription = eventEmitter.addListener('savedNetworksFound', (data) => {
setSavedNetworks(data)
setLoading(false)
})
networksFoundSubscription = eventEmitter.addListener('networksFound', (data) => {
setAvailableNetworks(data)
setLoading(false)
})
deviceReconnectRequiredSubscription = eventEmitter.addListener('deviceReconnectRequired', (data) => {
setLoading(false)
console.warn("failed to pair")
setErrorMessage("Could not connect to Drinkmaker, please make sure Drinkmaker is in range and bluetooth is on for your device")
})
deleteFailedSubscription = eventEmitter.addListener('deleteFailed', (data) => {
Alert.alert(
'Error',
'Deleting Network failed, please try again.',
[
{
text: 'OK',
style: 'destructive'
}
],
{ cancelable: false }
)
})
}
return (
<SafeArea>
<ScrollView contentContainerStyle={{alignItems:'center'}}
showsVerticalScrollIndicator={false}
>
<Text style={styles.title}>Nearby Wi-Fi Networks</Text>
<Text style={[styles.subTitle]}>
Once connected you can make a drink with your Drinkmaker
</Text>
{loading ? (
<View style={styles.activityIndicator}>
<ActivityIndicator size="large" />
</View>
) : (
<View>
{(availableNetworks.length > 0 || savedNetworks.length > 0) ? (
<View style={{
flex: 1,
marginTop: 20,
}}>
<View>
{ savedNetworks.length > 0
&&
<Text>Saved Networks</Text>
}
{
savedNetworks.map((item, index) => (
<View style={{flexDirection: 'row'}}>
<TouchableOpacity
style={styles.savedContainer}
onPress={() => onButtonPress(index, true)}>
<Text style={styles.notSelectedText}>
{item}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.removeContainer}
onPress={() => networkDeletionConfirmation(item, index)}>
<Text style={styles.selectedText}>
Remove
</Text>
</TouchableOpacity>
</View>
))
}
</View>
<View style ={{marginTop:20}}>
<Text>Available Networks</Text>
{
availableNetworks.map((item, index) => (
<TouchableOpacity
style={styles.container}
onPress={() => onButtonPress(index, false)}>
<Text style={styles.notSelectedText}>
{item}
</Text>
</TouchableOpacity>
))
}
</View>
{/* <TouchableOpacity
style={styles.container}
onPress={() => console.log('other')}>
<Text style={styles.notSelectedText}>
Other...
</Text>
</TouchableOpacity> */}
</View>
) : (
<View style={styles.noNetworksFound}>
<Text style={[styles.subTitle]}>{errorMessage ? errorMessage : "No Networks found or Drinkmaker out of range. Please rescan to find networks."}</Text>
<PillButton
style={{marginBottom: 50}}
buttons={[
{
text: 'ReScan',
onPress: () => handleActive(),
backgroundColor: colors.actionButtonTextBlue,
textColor: colors.actionButtonBackgroundGray
}
]}
/>
</View>
)}
</View>
)}
</ScrollView>
</SafeArea>
)
}
ConnectToWifiScreen['navigationOptions'] = ({navigation}) => ({
headerLeft: () => <TouchableOpacity style={{marginLeft:20}} onPress={() => navigation.navigate(navigation.getParam("navigateTo") ? navigation.getParam("navigateTo") : 'ApplianceConfiguration')}><Text style={{color:colors.black, fontSize: 18}}>Cancel</Text></TouchableOpacity>,
headerRight: () => <TouchableOpacity style={{marginRight:20}} onPress={navigation.getParam("refresh")}><Text style={{color:colors.actionButtonBackgroundBlue, fontSize: 18}}>Refresh</Text></TouchableOpacity>
})
const mapStateToProps = (state: AppState) => ({
appliance: state.appliance,
})
export default connect(mapStateToProps, { mergeAuthFlow, mergeProgress })(ConnectToWifiScreen)
const { width, height } = window
const styles = StyleSheet.create({
title: {
fontFamily: fonts.ApercuBold,
fontSize: 23,
color: colors.titleGray,
textAlign: 'center',
marginTop: 0
},
subTitle: {
fontFamily: fonts.SentinelMedium,
fontSize: 16,
width: width * 0.7,
lineHeight: 16 + 7,
color: colors.black,
textAlign: 'center',
marginTop: 12
},
adjustButton: {
marginBottom: 50
},
text: {
fontFamily: fonts.ApercuBold,
fontSize: 14,
color: colors.actionButtonTextBlue,
textTransform: 'uppercase'
},
container: {
padding: 15,
marginTop: 10,
height: 50,
width: width * 0.95,
backgroundColor: 'transparent',
borderBottomColor: '#C7C7C7',
borderBottomWidth: 1,
alignItems: 'flex-start',
},
savedContainer: {
padding: 15,
marginTop: 10,
height: 50,
width: width * 0.62,
backgroundColor: 'transparent',
borderBottomColor: '#C7C7C7',
borderBottomWidth: 1,
alignItems: 'flex-start',
},
removeContainer: {
padding: 15,
paddingRight: 0,
marginTop: 10,
height: 50,
width: width * 0.32,
backgroundColor: 'transparent',
borderBottomColor: '#C7C7C7',
borderBottomWidth: 1,
alignItems: 'flex-end',
},
activityIndicator: {
marginTop: '50%',
alignItems: 'center',
alignSelf: 'center'
},
noNetworksFound: {
position: 'absolute',
top: '50%',
alignSelf: 'center',
marginTop: 20,
},
notSelectedText: {
color: '#000000',
fontSize: 18,
fontFamily: fonts.ApercuMedium
},
selectedText: {
paddingRight: 20,
color: colors.actionButtonTextBlue,
fontSize: 18,
fontFamily: fonts.ApercuMedium
}
})
package com.bedfordsystems.drinkworks;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.content.pm.PackageManager.NameNotFoundException;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.ScanResult;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.PopupMenu;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.bluetooth.le.ScanFilter;
import android.os.ParcelUuid;
import org.json.JSONObject;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants;
import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSDevice;
import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSManager;
import software.amazon.freertos.amazonfreertossdk.BleConnectionStatusCallback;
import software.amazon.freertos.amazonfreertossdk.BleScanResultCallback;
import software.amazon.freertos.amazonfreertossdk.NetworkConfigCallback;
import software.amazon.freertos.amazonfreertossdk.networkconfig.*;
import java.util.HashMap;
public class WifiProvisioningNative extends ReactContextBaseJavaModule {
private static final String TAG = "DeviceScanFragment";
private boolean mqttOn = true;
private BleDeviceAdapter mBleDeviceAdapter;
List<BleDevice> mBleDevices = new ArrayList<>();
List<WifiInfo> mWifiInfoList = new ArrayList<>();
private static final int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_FINE_LOCATION = 1;
private String mDeviceMacAddr;
private AmazonFreeRTOSDevice mDevice;
private AmazonFreeRTOSManager mAmazonFreeRTOSManager;
public WifiProvisioningNative(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "WifiProvisioningNative";
}
@ReactMethod
public void searchForDevices (String uuid) {
Log.d(TAG, "Ian Dorosh");
mAmazonFreeRTOSManager = AmazonFreeRTOSAgent.getAmazonFreeRTOSManager(getReactApplicationContext());
List<ScanFilter> filters_v2 = new ArrayList<>();
ScanFilter scanFilter = new ScanFilter.Builder()
.setServiceUuid(ParcelUuid.fromString("0d8fd548-266b-48ee-8b16-ef4c87e24953"))
.build();
filters_v2.add(scanFilter);
mAmazonFreeRTOSManager.setScanFilters(filters_v2);
//Enabling Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
getCurrentActivity().startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
// requesting user to grant permission.
try {
getCurrentActivity().requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_FINE_LOCATION);
} catch (Exception e) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("failedToConnect", null);
}
// WritableArray devices = new WritableNativeArray();
mAmazonFreeRTOSManager.startScanDevices(new BleScanResultCallback() {
@Override
public void onBleScanResult(ScanResult result) {
BleDevice thisDevice = new BleDevice(result.getDevice().getName(), result.getDevice().getAddress(), result.getDevice());
WritableMap params = Arguments.createMap(); // add here the data you want to send
WritableArray d = new WritableNativeArray();
params.putString("name", result.getDevice().getName());
params.putString("uuid",result.getDevice().getAddress());
d.pushMap(params);
if (!mBleDevices.contains(thisDevice) && uuid.equals(result.getDevice().getAddress())) {
mBleDevices.add(thisDevice);
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("appliancesFound", d);
}
Log.d(TAG, "new ble device found. Mac: " + thisDevice.getName());
if (!mBleDevices.contains(thisDevice)) {
Log.d(TAG, "new ble device found. Mac: " + thisDevice.getMacAddr());
// mBleDevices.add(thisDevice);
// devices.pushMap(params);
}
}
});
// WritableArray devices = new WritableNativeArray();
// for (BleDevice bd : mBleDevices) {
// WritableMap params = Arguments.createMap(); // add here the data you want to send
// params.putString("name", result.getDevice().getName());
// params.putString("uuid",result.getDevice().getAddress());
// devices.pushMap(params);
// }
// getReactApplicationContext()
// .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
// .emit("appliancesFound", devices);
}
@ReactMethod
public void searchForNetworks (String uuid) {
Log.d(TAG, "NNET Searching for networks. UUID: " + uuid);
mDevice = mAmazonFreeRTOSManager.getConnectedDevice(uuid);
if (mDevice != null) {
mWifiInfoList.clear();
ListNetworkReq listNetworkReq = new ListNetworkReq();
listNetworkReq.maxNetworks = 10;
listNetworkReq.timeout = 5;
try {
mDevice.listNetworks(listNetworkReq, mNetworkConfigCallback);
} catch (Exception e) {
Log.d(TAG, "NNET Something went wrong fetching networks: " + e.getMessage());
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("deviceReconnectRequired", null);
}
Log.d(TAG, "NNET GOT NETWORKS");
// try
// {
// Thread.sleep(2000);
// }
// catch(InterruptedException e)
// {
// // this part is executed when an exception (in this example InterruptedException) occurs
// }
// WritableArray a = new WritableNativeArray();
// for (WifiInfo wifiInfo : mWifiInfoList) {
// Log.d(TAG, "NNET GOT NETWORKS: " + wifiInfo.getSsid());
// a.pushString(wifiInfo.getSsid());
// }
// getReactApplicationContext()
// .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
// .emit("networksFound", a);
} else {
Log.d(TAG, "NNET NO NETWORKS FOUND");
// WritableArray a = new WritableNativeArray();
// a.pushString("Stay Away Guest");
// a.pushString("Spectrum 8893");
// a.pushString("WIFI 4564");
// a.pushString("FBI Gonna get you");
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("deviceReconnectRequired", null);
}
}
@ReactMethod
public void connectToAppliance (String uuid) {
Log.d(TAG, "CAPP Connecting to appliance. UUID: " + uuid);
BleDevice aDevice = null;
for (BleDevice bd : mBleDevices) {
if (uuid.equals(bd.getMacAddr())) {
Log.d(TAG, "CAPP Setting Connected Appliance. MAC: " + bd.getMacAddr());
aDevice = bd;
}
}
if (aDevice != null) {
AWSCredentialsProvider credentialsProvider = null;
mAmazonFreeRTOSManager.connectToDevice(aDevice.getBluetoothDevice(), new BleConnectionStatusCallback() {
@Override
public void onBleConnectionStatusChanged(AmazonFreeRTOSConstants.BleConnectionState connectionStatus) {
Log.i(TAG, "CAPP BLE connection status changed to: " + connectionStatus);
if (connectionStatus == AmazonFreeRTOSConstants.BleConnectionState.BLE_INITIALIZED) {
mDevice = mAmazonFreeRTOSManager.getConnectedDevice(uuid);
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("connected", null);
} else if (connectionStatus == AmazonFreeRTOSConstants.BleConnectionState.BLE_DISCONNECTED) {
// figure out how to not have this emit so many times as it is causing a loop of hell when this goes back to RN
// getReactApplicationContext()
// .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
// .emit("failedToConnect", null);
}
}
}, credentialsProvider, true);
}
}
@ReactMethod
public void disconnectFromAppliances () {
if (mDevice != null) {
Log.e(TAG, "NNET Device STIL EXISTS --- DISCONNECTING. ");
mAmazonFreeRTOSManager.disconnectFromDevice(mDevice);
}
}
@ReactMethod
public void connectToNetwork (String ssid, String password, String uuid) {
BleDevice aDevice = null;
if (mDevice != null) {
Log.e(TAG, "NNET Device STIL EXISTS. ");
} else {
Log.e(TAG, "NNET Device NOT FOUND. ");
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("networkSaveFailed", null);
}
// for (BleDevice bd : mBleDevices) {
// if (uuid.equals(bd.getMacAddr())) {
// Log.d(TAG, "CAPP Setting Connected Appliance. MAC: " + bd.getMacAddr());
// aDevice = bd;
// }
// }
for (WifiInfo wifiInfo : mWifiInfoList) {
if (wifiInfo.getSsid().equals(ssid)) {
SaveNetworkReq saveNetworkReq = new SaveNetworkReq();
saveNetworkReq.ssid = wifiInfo.getSsid();
saveNetworkReq.bssid = wifiInfo.getBssid();
saveNetworkReq.psk = password;
saveNetworkReq.security = wifiInfo.getNetworkType();
saveNetworkReq.index = wifiInfo.getIndex();
if (mDevice != null) {
try {
mDevice.saveNetwork(saveNetworkReq, mNetworkConfigCallback);
} catch (Exception e) {
Log.d(TAG, "NNET Something went wrong fetching networks: " + e.getMessage());
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("networkSaveFailed", null);
}
} else {
Log.e(TAG, "Device is not found. " + mDeviceMacAddr);
}
break;
}
}
}
@ReactMethod
public void deleteNetwork(int index, String uuid, String ssid) {
for (WifiInfo wifiInfo : mWifiInfoList) {
if (wifiInfo.getSsid().equals(ssid)) {
DeleteNetworkReq deleteNetworkReq = new DeleteNetworkReq();
deleteNetworkReq.index = wifiInfo.getIndex();
if (mDevice != null) {
try {
mDevice.deleteNetwork(deleteNetworkReq, mNetworkConfigCallback);
} catch (Exception e) {
Log.d(TAG, "NNET Something went wrong deleting network: " + e.getMessage());
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("deleteFailed", null);
}
} else {
Log.e(TAG, "Device is not found. " + mDeviceMacAddr);
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("deleteFailed", null);
}
}
}
}
@ReactMethod
public void didSelectNetwork (String uuid, Integer selectedNetworkIndex, Boolean isSaved, String selectedSSID) {
}
private class BleDeviceAdapter {
private List<BleDevice> mDeviceList;
public BleDeviceAdapter(List<BleDevice> devices) {
mDeviceList = devices;
}
public int getItemCount() {
return mDeviceList.size();
}
}
@ReactMethod
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == getCurrentActivity().RESULT_OK) {
Log.i(TAG, "Successfully enabled bluetooth");
} else {
Log.w(TAG, "Failed to enable bluetooth");
}
}
}
@ReactMethod
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_FINE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "ACCESS_FINE_LOCATION granted.");
} else {
Log.w(TAG, "ACCESS_FINE_LOCATION denied");
}
}
}
}
private NetworkConfigCallback mNetworkConfigCallback = new NetworkConfigCallback() {
@Override
public void onListNetworkResponse(final ListNetworkResp response) {
WifiInfo wifiInfo = new WifiInfo(
response.getSsid(),
response.getBssid(),
response.getRssi(),
response.getSecurity(),
response.getIndex(),
response.getConnected()
);
if (!mWifiInfoList.contains(wifiInfo)) {
mWifiInfoList.add(wifiInfo);
// mBssid2WifiInfoMap.put(bssidToString(wifiInfo.getBssid()), wifiInfo);
// mWifiInfoAdapter.notifyDataSetChanged();
}
WritableArray connected = new WritableNativeArray();
WritableArray available = new WritableNativeArray();
for (WifiInfo wi : mWifiInfoList) {
Log.d(TAG, "NNET Network SSID: " + wi.getSsid());
// Log.d(TAG, "NNET Network Connected: " + wi.getConnected());
if (wi.getConnected()) {
connected.pushString(wi.getSsid());
} else {
available.pushString(wi.getSsid());
}
}
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("networksFound", available);
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("savedNetworksFound", connected);
// mHandler.post(new Runnable() {
// @Override
// public void run() {
// WifiInfo wifiInfo = new WifiInfo(response.getSsid(), response.getBssid(),
// response.getRssi(), response.getSecurity(), response.getIndex(),
// response.getConnected());
// if (!mWifiInfoList.contains(wifiInfo)) {
// mWifiInfoList.add(wifiInfo);
// mBssid2WifiInfoMap.put(bssidToString(wifiInfo.getBssid()), wifiInfo);
// // mWifiInfoAdapter.notifyDataSetChanged();
// }
// }
// });
}
@Override
public void onSaveNetworkResponse(final SaveNetworkResp response) {
String respString = response.toString();
Character status = respString.charAt(respString.length() - 1);
if (status.equals('0')) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("didSave", null);
} else {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("networkSaveFailed", null);
}
}
@Override
public void onDeleteNetworkResponse(final DeleteNetworkResp response) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("deleted", null);
}
@Override
public void onEditNetworkResponse(EditNetworkResp response) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("networkEdited", null);
}
};
@ReactMethod
public void setUpWifiNotifications () {
}
@ReactMethod
public void removeWifiNotifications () {
}
}v
import { NativeModules } from 'react-native'
interface WifiProvisioningNative {
searchForDevices: (string) => void
setUpWifiNotifications: () => void
removeWifiNotifications: () => void
disconnectFromAppliances: () => void
searchForNetworks: (string) => void
connectToAppliance: (string) => void
connectToNetwork: (ssid, password, uuid) => void
didSelectNetwork: (uuid, selectedNetworkIndex, isSaved, selectedSSID) => void
deleteNetwork: (index, uuid, ssid) => void
}
export default NativeModules.WifiProvisioningNative as WifiProvisioningNative
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment