Commit 7e2d882d by HaOuiha

keeping userData in firestore & try to count valid breaker for create

parent edfa5612
......@@ -49,7 +49,7 @@ export const getAllMainDeviceInfo = () => async (dispatch, getState) => {
.doc(deviceId)
.get();
let ownerDeviceInfoData = await ownerDeviceInfo.data();
let ownerDeviceInfoData = ownerDeviceInfo.data();
const breakerStatus = await getBreakerStatus(deviceId);
allMainDeviceInfoData.push(
......@@ -65,7 +65,7 @@ export const getAllMainDeviceInfo = () => async (dispatch, getState) => {
.doc(deviceId)
.get();
let sharingDeviceInfoData = await sharingDeviceInfo.data();
let sharingDeviceInfoData = sharingDeviceInfo.data();
const breakerStatus = await getBreakerStatus(deviceId);
allMainDeviceInfoData.push(
......
import app from '../../firebase';
import app, { fireStore } from '../../firebase';
import AsyncStorage from '@react-native-community/async-storage';
export const GET_CURRENT_USER = 'GET_CURRENT_USER';
......@@ -13,9 +14,21 @@ export const getCurrentUserAction = (displayName, email, emailVerified, phoneNum
});
export const getCurrentUser = user => async dispatch => {
const { displayName, email, emailVerified, uid, phoneNumber, photoURL } = user;
try {
const appUser = await fireStore
.collection('user')
.doc(user.uid)
.get();
const appUserData = appUser.data();
const { displayName, email, emailVerified, phoneNumber, photoURL, token } = appUserData;
// console.log('appUserData', appUserData);
dispatch(getCurrentUserAction(displayName, email, emailVerified, phoneNumber, uid, photoURL));
await AsyncStorage.setItem('token', token);
return dispatch(getCurrentUserAction(displayName, email, emailVerified, phoneNumber, user.uid, photoURL));
} catch (e) {
alert('getCurrentUser error', e);
}
};
export const updateUser = userData => async (dispatch, getState) => {
......@@ -26,10 +39,11 @@ export const updateUser = userData => async (dispatch, getState) => {
const newDisplayName = `${userData.firstName} ${userData.lastName}`;
const newPhoneNumber = userData.phoneNumber;
const user = app.auth().currentUser;
await user.updateProfile({
const userRef = fireStore.collection('user').doc(uid);
await userRef.update({
displayName: newDisplayName,
phoneNumber: newPhoneNumber,
photoURL,
});
dispatch(getCurrentUserAction(newDisplayName, email, emailVerified, newPhoneNumber, uid, photoURL));
......@@ -37,3 +51,24 @@ export const updateUser = userData => async (dispatch, getState) => {
console.log('Update user failed!', error);
}
};
export const createNewUser = (userData, newUser) => async dispatch => {
try {
const { photoURL, emailVerified, uid } = newUser;
const { email, firstName, lastName, phoneno } = userData;
const displayName = `${firstName} ${lastName}`;
const userRef = fireStore.collection('user').doc(uid);
await userRef.set({
displayName,
email,
emailVerified,
phoneNumber: phoneno,
photoURL,
});
dispatch(getCurrentUserAction(displayName, email, emailVerified, phoneno, uid, photoURL));
} catch (error) {
console.log('Create user failed!', error);
}
};
......@@ -228,7 +228,7 @@ export const setSubBreakerStatus = (settingValue, MainIndex, SubIndex) => async
clearInterval(queryShadowInterval);
countTimes = 0;
}
}, 3000);
}, 4000);
} catch (error) {
console.log(error);
}
......
......@@ -10,6 +10,8 @@ import { withNavigationFocus } from 'react-navigation';
import Permissions from 'react-native-permissions';
import { TouchableNativeFeedback, TouchableOpacity } from 'react-native-gesture-handler';
import QRCodeScanner from 'react-native-qrcode-scanner';
import { apolloQuery, READ_SHADOW } from '../../utils/apollo/apollo';
import _ from 'lodash';
class CameraScreen extends Component {
static navigationOptions = ({ navigation }) => {
......@@ -38,11 +40,13 @@ class CameraScreen extends Component {
setTimeout(() => {
this.setState({ isWaiting: true });
}, 250);
this.createNewDevice('7cb6e9aa-0a44-47d6-bca8-4d724b0fcd43');
};
handleBarCodeScanned = ({ type, data }) => {
this.setState({ scanned: true });
alert(`Bar code with type ${type} and data ${data} has been scanned!`);
// createNewDevice
};
requestPermission = async () => {
......@@ -50,6 +54,44 @@ class CameraScreen extends Component {
this.setState({ cameraPermission: response });
};
createNewDevice = async deviceId => {
const {
data: {
shadow: { value },
},
} = await apolloQuery(READ_SHADOW, { deviceid: deviceId });
const breakersStatus = _.pick(value, ['MD_STA', 'ML1', 'ML2', 'ML3', 'ML4']);
console.log('breakersStatus', breakersStatus);
const checkingExistedBreaker = () => {
let existedMainBreaker = [];
let existedSubBreaker = [];
for (let i = 1; i <= 4; i++) {
if (breakersStatus.MD_STA[`ML${i}`] !== 3) {
existedMainBreaker.push(`ML${i}`);
}
}
console.log(existedMainBreaker);
existedMainBreaker.map((mainBreaker, id) => {
for (let i = 1; i <= 8; i++) {
if (breakersStatus[mainBreaker][`L${id + 1}B${i}`] !== 3) {
}
}
});
};
checkingExistedBreaker();
// const userRef = fireStore.collection('user').doc(deviceId);
// await userRef.set({
// displayName,
// email,
// emailVerified,
// phoneNumber: phoneno,
// photoURL,
// });
};
renderCamera = () =>
Platform.OS === 'android' ? (
<RNCamera
......
......@@ -50,6 +50,7 @@ class SmartMeterScreen extends PureComponent {
data: this.props.allMainDeviceInfo,
});
}
console.log(this._isMounted);
};
renderItem = ({ item, index }) => {
......@@ -62,7 +63,6 @@ class SmartMeterScreen extends PureComponent {
};
getData = async () => {
this._isMounted = false;
await this.props.getAllMainDeviceInfo();
};
......@@ -74,16 +74,15 @@ class SmartMeterScreen extends PureComponent {
return itemData.indexOf(textData) > -1;
});
this.setState({
data: newData,
});
this.setState({ data: newData });
};
render() {
const { isLoading, error } = this.props;
const { data } = this.state;
return !error ? (
// !error ? (
return (
<View style={[theme.container, theme.containerWithPadding]}>
<Text style={[theme.smallTitle, theme.textDark, { marginBottom: 10 }]}>Smart Device</Text>
......@@ -114,7 +113,7 @@ class SmartMeterScreen extends PureComponent {
keyExtractor={(item, index) => item.deviceId}
ItemSeparatorComponent={() => <View style={theme.mt1} />}
ListEmptyComponent={() => (
<View>
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}>
<Text style={[theme.normalText, { marginTop: 20 }]}>
{isLoading ? '' : this._isMounted ? 'No Device Connected' : ''}
</Text>
......@@ -123,11 +122,12 @@ class SmartMeterScreen extends PureComponent {
renderItem={(item, index) => this.renderItem(item)}
/>
</View>
) : (
<View>
<Text>{'Something went wrong ' + error}</Text>
</View>
);
// ) : (
// <View>
// <Text>{'Something went wrong ' + error}</Text>
// </View>
// );
}
}
......
import React, { Component } from 'react';
import { ActivityIndicator, View, StatusBar, Image } from 'react-native';
import { ActivityIndicator, View, StatusBar, Image, Keyboard } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import logo from '../../assets/images/logo2.png';
import { width } from '../../constants/Layout';
......@@ -29,21 +29,22 @@ class AuthLoadingScreen extends Component {
}, 900); // 1200
};
getToken = async () => {
const { uid } = app.auth().currentUser;
try {
const user = await fireStore
.collection('user')
.doc(uid)
.get();
const { token } = user.data();
await AsyncStorage.setItem('token', token);
} catch (error) {
alert(error);
}
};
// getToken = async () => {
// const { uid } = app.auth().currentUser;
// try {
// const user = await fireStore
// .collection('user')
// .doc(uid)
// .get();
// const { token } = user.data();
// await AsyncStorage.setItem('token', token);
// } catch (error) {
// alert(error);
// }
// };
bootstrapAsync = async () => {
Keyboard.dismiss();
this.showLogoThenIndicator();
try {
// Preload data from an external API && Preload data using AsyncStorage
......@@ -54,9 +55,8 @@ class AuthLoadingScreen extends Component {
if (RememberedLogin === 'true') {
app.auth().onAuthStateChanged(async user => {
if (user) {
console.log(user);
await this.props.getCurrentUser(user);
await this.getToken();
// await this.getToken();
this.props.navigation.navigate('Main');
}
});
......
......@@ -7,7 +7,7 @@ import { HeaderButtons, Item } from 'react-navigation-header-buttons';
import IoniconsHeaderButton from '../../components/IoniconsHeaderButton';
import app from '../../firebase';
import { connect } from 'react-redux';
import { getCurrentUser, updateUser } from '../../reduxStore/actions/cerrentUserAction';
import { getCurrentUser, createNewUser } from '../../reduxStore/actions/cerrentUserAction';
class RegisterScreen extends Component {
static navigationOptions = ({ navigation }) => ({
......@@ -41,16 +41,14 @@ class RegisterScreen extends Component {
}
};
createAccount = async values => {
const userData = { firstName: values.firstName, lastName: values.lastName, phoneNumber: values.phoneno };
// const userData = { firstName: values.firstName, lastName: values.lastName, phoneNumber: values.phoneno };
try {
app.auth()
.createUserWithEmailAndPassword(values.email, values.password)
.then(async value => {
this.sendEmail();
await this.props.getCurrentUser(value);
await this.props.updateUser(userData);
});
this.props.navigation.navigate('Success');
const newUser = await app.auth().createUserWithEmailAndPassword(values.email, values.password);
if (newUser) {
await this.props.createNewUser(values, newUser.user);
this.sendEmail();
this.props.navigation.navigate('Success');
}
} catch (error) {
alert(error);
}
......@@ -96,7 +94,7 @@ class RegisterScreen extends Component {
}
const mapDispatchToProps = {
updateUser,
createNewUser,
getCurrentUser,
};
......
......@@ -56,4 +56,11 @@ const WRITE_SHADOW = gql`
}
}
`;
export { READ_SHADOW, WRITE_SHADOW };
const QUERY_DEVICE_BY_TAG = gql`
query($tag: String!) {
device(tag: $tag) {
deviceid
}
}
`;
export { READ_SHADOW, WRITE_SHADOW, QUERY_DEVICE_BY_TAG };
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment