Commit 77afa811 by HaOuiha

subscribtion detail page

parent a0ea765d
......@@ -23,7 +23,7 @@ const MeterCard = ({ item, onPressEachCard, data, isFocused, ...rest }) => {
document: SUBSCRIBE_SHADOW,
variables: { deviceid: item.deviceId },
updateQuery: (prev, { subscriptionData }) => {
console.log(subscriptionData);
// console.log(subscriptionData);
if (subscriptionData.data.shadowUpdated.data.hasOwnProperty('SM1')) {
setBreakerStatus(subscriptionData.data.shadowUpdated.data.SM1.BK_S);
}
......@@ -56,7 +56,9 @@ const MeterCard = ({ item, onPressEachCard, data, isFocused, ...rest }) => {
</Text>
</View>
<View style={[theme.rowContainer, { position: 'absolute', top: 10, right: 5 }]}>
<View style={[styles.online, { backgroundColor: item.isOnline ? '#10ca88' : color.primary }]} />
<View
style={[styles.online, { backgroundColor: item.onlineStatus === 1 ? '#10ca88' : color.primary }]}
/>
<Icon name={item.isSharing ? 'users' : 'user'} type="FontAwesome" style={styles.iconStyle} />
<Icon name="wifi" type="FontAwesome" style={styles.iconStyle} />
</View>
......
import app, { fireStore, baseURL } from '../../firebase';
import { fireStore } from '../../firebase';
import _ from 'lodash';
import { apolloQuery, READ_SHADOW } from '../../utils/apollo/apollo';
import { apolloQuery, READ_SHADOW, QUERY_ONLINE_STATUS } from '../../utils/apollo/apollo';
export const GET_ALL_MAIN_DEVICE_INFO = 'GET_ALL_MAIN_DEVICE_INFO';
export const GET_ALL_MAIN_DEVICE_INFO_LOADING = 'GET_ALL_MAIN_DEVICE_INFO_LOADING';
......@@ -49,10 +49,10 @@ export const getAllMainDeviceInfo = () => async (dispatch, getState) => {
.get();
let ownerDeviceInfoData = ownerDeviceInfo.data();
const breakerStatus = await getBreakerStatus(deviceId);
const { breakerStatus, onlineStatus } = await getBreakerStatus(deviceId);
allMainDeviceInfoData.push(
Object.assign(ownerDeviceInfoData, { deviceId, isSharing: false, breakerStatus })
Object.assign(ownerDeviceInfoData, { deviceId, isSharing: false, breakerStatus, onlineStatus })
);
})
);
......@@ -65,10 +65,10 @@ export const getAllMainDeviceInfo = () => async (dispatch, getState) => {
.get();
let sharingDeviceInfoData = sharingDeviceInfo.data();
const breakerStatus = await getBreakerStatus(deviceId);
const { breakerStatus, onlineStatus } = await getBreakerStatus(deviceId);
allMainDeviceInfoData.push(
Object.assign(sharingDeviceInfoData, { deviceId, isSharing: true, breakerStatus })
Object.assign(sharingDeviceInfoData, { deviceId, isSharing: true, breakerStatus, onlineStatus })
);
})
);
......@@ -94,22 +94,16 @@ const getBreakerStatus = async deviceId => {
},
} = await apolloQuery(READ_SHADOW, { deviceid: deviceId });
// const hello = await apolloSubscription(READ_SHADOW, { deviceid: deviceId }, SUBSCRIBE_SHADOW, {
// deviceid: deviceId,
// });
// console.log('hello', hello);
// const res = await apolloSubscription(READ_SHADOW, { deviceid: deviceId });
// console.log(res);
const res = await apolloQuery(QUERY_ONLINE_STATUS, { deviceid: deviceId });
const onlineStatus = res.data.device[0].status;
// console.log(onlineStatus);
const tempBreakerStatus = _.pick(data, ['SM1']);
const breakerStatus = tempBreakerStatus.SM1.BK_S;
return breakerStatus;
return { breakerStatus, onlineStatus };
} catch (e) {
// alert('Something went wrong!!');
console.log(e);
return 0;
return { breakerStatus: 0, onlineStatus: 0 };
}
};
import { fireStore } from '../../firebase';
import _ from 'lodash';
import { apolloQuery, apolloMutation, READ_SHADOW, WRITE_SHADOW } from '../../utils/apollo/apollo';
import { apolloQuery, apolloMutation, READ_SHADOW, WRITE_SHADOW, QUERY_ONLINE_STATUS } from '../../utils/apollo/apollo';
import {
getExistedConnectedDeviceAction,
getExistedMcbLinksDataAction,
......@@ -14,7 +14,9 @@ export const GET_CURRENT_SELECTED_DATA_ERROR = 'GET_CURRENT_SELECTED_DATA_ERROR'
export const GET_CURRENT_SELECTED_SHADOW = 'GET_CURRENT_SELECTED_SHADOW';
export const GET_BREAKERS_STATUS_SHADOW = 'GET_BREAKER_STATUS_SHADOW';
export const SET_DESIRED_BREAKERS_STATUS_SHADOW = 'SET_DESIRED_BREAKERS_STATUS_SHADOW';
export const GET_ONLINE_STATUS = 'GET_ONLINE_STATUS';
// export const SET_DESIRED_BREAKERS_STATUS_SHADOW = 'SET_DESIRED_BREAKERS_STATUS_SHADOW';
export const getCurrentSelectedDataAction = currentSelectedData => ({
type: GET_CURRENT_SELECTED_DATA,
......@@ -41,6 +43,11 @@ export const getBreakersStatusAction = breakerStatus => ({
breakerStatus,
});
export const getOnlineStatusAction = onlineStatus => ({
type: GET_ONLINE_STATUS,
onlineStatus,
});
export const getCurrentSelectedShadow = deviceId => async (dispatch, getState) => {
const { currentSelectedDeviceReducer } = getState();
const { currentSelectedData } = currentSelectedDeviceReducer;
......@@ -53,7 +60,6 @@ export const getCurrentSelectedShadow = deviceId => async (dispatch, getState) =
},
} = await apolloQuery(READ_SHADOW, { deviceid: deviceId || selectedDeviceId });
// const tempBreakersStatus = _.pick(value, ['CMD_MSG', 'SM1', 'MD_STA', 'ML0', 'ML1', 'ML2', 'ML3', 'ML4']);
const tempBreakersStatus = _.pick(data, ['SM1', 'ML1', 'ML2', 'ML3', 'ML4']);
const breakersStatus = { ...tempBreakersStatus, SM1: { BK_S: tempBreakersStatus.SM1.BK_S } };
......@@ -77,8 +83,12 @@ export const getCurrentSelectedShadow = deviceId => async (dispatch, getState) =
}
}
const res = await apolloQuery(QUERY_ONLINE_STATUS, { deviceid: deviceId });
const onlineStatus = res.data.device[0].status;
dispatch(getOnlineStatusAction(onlineStatus));
dispatch(getBreakersStatusAction(breakersStatus));
dispatch(getCurrentSelectedShadowAction(shadowValue || null));
dispatch(getCurrentSelectedShadowAction(shadowValue));
} catch (error) {
dispatch(errorAction(error.message || error || 'Error'));
}
......@@ -127,8 +137,12 @@ export const getCurrentSelectedData = (deviceId, showLoading) => async dispatch
}
}
const res = await apolloQuery(QUERY_ONLINE_STATUS, { deviceid: deviceId });
const onlineStatus = res.data.device[0].status;
dispatch(getOnlineStatusAction(onlineStatus));
dispatch(getBreakersStatusAction(breakersStatus));
dispatch(getCurrentSelectedShadowAction(shadowValue || null));
dispatch(getCurrentSelectedShadowAction(shadowValue));
dispatch(getCurrentSelectedDataAction(currentSelectedDeviceDataMoreInfo));
showLoading && dispatch(loadingAction(false));
} catch (error) {
......@@ -137,6 +151,34 @@ export const getCurrentSelectedData = (deviceId, showLoading) => async dispatch
}
};
export const updateSubscriptionToStore = newWholeShadow => async dispatch => {
const tempBreakersStatus = _.pick(newWholeShadow, ['SM1', 'ML1', 'ML2', 'ML3', 'ML4']);
const breakersStatus = { ...tempBreakersStatus, SM1: { BK_S: tempBreakersStatus.SM1.BK_S } };
let shadowTimers = [];
let shadowValue = null;
for (let i = 1; i <= 4; i++) {
for (let j = 1; j <= 8; j++) {
shadowTimers.push(`L${i}B${j}T`);
shadowValue = _.omit(newWholeShadow, [
'CMD_MSG',
'TIME_NOW',
'TIME_ZONE',
'VERSION',
'ML1',
'ML2',
'ML3',
'ML4',
'MAB1T',
...shadowTimers,
]);
}
}
dispatch(getBreakersStatusAction(breakersStatus));
dispatch(getCurrentSelectedShadowAction(shadowValue));
};
export const updateDetail = (type, value) => async (dispatch, getState) => {
const { currentSelectedDeviceReducer } = getState();
const { currentSelectedData } = currentSelectedDeviceReducer;
......@@ -175,11 +217,13 @@ export const updateDetail = (type, value) => async (dispatch, getState) => {
}
};
export const setMainStatus = settingValue => async (dispatch, getState) => {
export const setMainStatus = settingValue => (dispatch, getState) => {
const { currentSelectedDeviceReducer } = getState();
const { currentSelectedData, breakerStatus } = currentSelectedDeviceReducer;
const selectedDeviceId = currentSelectedData.deviceId;
console.log(settingValue);
const command = () => {
switch (settingValue) {
case true:
......@@ -188,39 +232,18 @@ export const setMainStatus = settingValue => async (dispatch, getState) => {
return 'MAIN_OFF';
}
};
const data = { data: { CMD_MSG: { MSG1: command() } } };
const writingCommand = { CMD_MSG: { MSG1: command() } };
try {
const desiredBreakerStatus = { ...breakerStatus, SM1: { BK_S: settingValue ? 1 : 0 } };
dispatch(getBreakersStatusAction(desiredBreakerStatus));
await apolloMutation(WRITE_SHADOW, { deviceid: selectedDeviceId, data: data });
/*---------------polling-----------------*/
// let countTimes = 0;
// const queryShadowInterval = setInterval(async () => {
// const {
// data: {
// shadow: { data },
// },
// } = await apolloQuery(READ_SHADOW, { deviceid: selectedDeviceId });
// const tempBreakersStatus = _.pick(data, ['SM1', 'ML1', 'ML2', 'ML3', 'ML4']);
// const breakersStatus = { ...tempBreakersStatus, SM1: { BK_S: tempBreakersStatus.SM1.BK_S } };
// countTimes === 3 && dispatch(getBreakersStatusAction(breakersStatus));
// // console.log(countTimes);
// if (countTimes >= 3) {
// clearInterval(queryShadowInterval);
// countTimes = 0;
// }
// ++countTimes;
// }, 3000);
apolloMutation(WRITE_SHADOW, { deviceid: selectedDeviceId, data: writingCommand });
} catch (error) {
console.log(error);
}
};
export const setSubBreakerStatus = (settingValue, MainIndex, SubIndex) => async (dispatch, getState) => {
export const setSubBreakerStatus = (settingValue, MainIndex, SubIndex) => (dispatch, getState) => {
const { currentSelectedDeviceReducer } = getState();
const { currentSelectedData, breakerStatus } = currentSelectedDeviceReducer;
const selectedDeviceId = currentSelectedData.deviceId;
......@@ -233,7 +256,7 @@ export const setSubBreakerStatus = (settingValue, MainIndex, SubIndex) => async
return `L${MainIndex + 1}B${SubIndex + 1}_OFF`;
}
};
const data = { data: { CMD_MSG: { MSG1: command() } } };
const writingCommand = { CMD_MSG: { MSG1: command() } };
try {
const desiredBreakerStatus = {
......@@ -243,30 +266,8 @@ export const setSubBreakerStatus = (settingValue, MainIndex, SubIndex) => async
[`L${MainIndex + 1}B${SubIndex + 1}`]: settingValue ? 1 : 0,
},
};
// console.log('desiredBreakerStatus55', desiredBreakerStatus);
dispatch(getBreakersStatusAction(desiredBreakerStatus));
await apolloMutation(WRITE_SHADOW, { deviceid: selectedDeviceId, data: data });
/*---------------polling-----------------*/
// let countTimes = 0;
// const queryShadowInterval = setInterval(async () => {
// const {
// data: {
// shadow: { data },
// },
// } = await apolloQuery(READ_SHADOW, { deviceid: selectedDeviceId });
// const breakersStatus = _.pick(data, ['SM1', 'ML1', 'ML2', 'ML3', 'ML4']);
// // console.log('BreakerStatus_polling', breakersStatus);
// countTimes === 3 && dispatch(getBreakersStatusAction(breakersStatus));
// if (countTimes >= 3) {
// clearInterval(queryShadowInterval);
// countTimes = 0;
// }
// ++countTimes;
// }, 3000);
apolloMutation(WRITE_SHADOW, { deviceid: selectedDeviceId, data: writingCommand });
} catch (error) {
console.log(error);
}
......
......@@ -4,6 +4,7 @@ import {
GET_CURRENT_SELECTED_DATA_ERROR,
GET_CURRENT_SELECTED_SHADOW,
GET_BREAKERS_STATUS_SHADOW,
GET_ONLINE_STATUS,
// SET_DESIRED_BREAKERS_STATUS_SHADOW,
} from '../actions/currentSelectedAction';
......@@ -13,6 +14,7 @@ const initState = {
isLoading: true,
error: null,
breakerStatus: null,
onlineStatus: null,
// desiredBreakerStatus: null,
};
......@@ -29,6 +31,8 @@ const currentSelectedDeviceReducer = (state = initState, action) => {
case GET_BREAKERS_STATUS_SHADOW:
return { ...state, breakerStatus: action.breakerStatus };
case GET_ONLINE_STATUS:
return { ...state, onlineStatus: action.onlineStatus };
// case SET_DESIRED_BREAKERS_STATUS_SHADOW:
// return { ...state, desiredBreakerStatus: action.desiredBreakerStatus };
......
......@@ -10,11 +10,14 @@ import {
loadingAction,
setMainStatus,
setSubBreakerStatus,
updateSubscriptionToStore,
} from '../../../reduxStore/actions/currentSelectedAction';
import { getTimers, loadingTimersAction, errorTimersAction } from '../../../reduxStore/actions/timersAction';
import { isIphoneX } from '../../../utils/isPhoneX';
import { withNavigationFocus } from 'react-navigation';
import _ from 'lodash';
import { graphql } from '@apollo/react-hoc';
import { READ_SHADOW, SUBSCRIBE_SHADOW } from '../../../utils/apollo/apollo';
class SmartMeterDetailScreen extends Component {
static navigationOptions = ({ navigation }) => {
......@@ -50,21 +53,39 @@ class SmartMeterDetailScreen extends Component {
{ name: 'Units/KWh', limit: 1000, value: 0, unit: '' },
{ name: 'Arcing Fault', limit: 1000, value: 0, unit: '' },
],
shadow: null,
};
_mcbLinksListMounted = false;
getDataInterval = null;
deviceId = this.props.navigation.getParam('deviceId');
unsubscribeShadow = null;
subscribeToNewShadow = subscribeToMore => {
this.unsubscribeShadow = subscribeToMore({
document: SUBSCRIBE_SHADOW,
variables: { deviceid: this.deviceId },
updateQuery: (prev, { subscriptionData }) => {
this.setState((prevState, props) => ({
shadow: { ...prevState.shadow, ...subscriptionData.data.shadowUpdated.data },
}));
this.props.updateSubscriptionToStore(this.state.shadow);
},
});
};
getData = async () => {
await this.props.getCurrentSelectedData(this.deviceId, true);
await this.props.getTimers();
// this.getDataInterval = setInterval(() => this.props.getCurrentSelectedData(this.deviceId), 6000);
};
componentDidMount = async () => {
// console.log(this.state);
// console.log(this.props);
await this.getData();
this.setState({ shadow: this.props.data.shadow.data });
this.subscribeToNewShadow(this.props.data.subscribeToMore);
};
componentDidUpdate = (prevProps, prevState) => {
......@@ -85,15 +106,8 @@ class SmartMeterDetailScreen extends Component {
this.setSubBreakersState();
}
if (prevProps.isFocused !== this.props.isFocused) {
// if (this.props.isFocused === true) {
// clearInterval(this.getDataInterval);
// this.getDataInterval = setInterval(() => this.props.getCurrentSelectedData(this.deviceId), 6000);
// }
// when not focud this page
// if (this.props.isFocused === false) {
// this._mcbLinksListMounted = false;
// clearInterval(this.getDataInterval);
// }
this.props.isFocused === true && this.subscribeToNewShadow(this.props.data.subscribeToMore);
this.props.isFocused === false && this.unsubscribeShadow();
}
if (prevProps.shadow !== this.props.shadow) {
this.setState({
......@@ -107,29 +121,29 @@ class SmartMeterDetailScreen extends Component {
],
});
}
// console.log(this.state.shadow);
};
handleToggle = async value => {
// clearInterval(this.getDataInterval);
this.setState({ isWaiting: true });
await this.props.setMainStatus(value);
this.setState({ isWaiting: false });
// this.getDataInterval = setInterval(() => this.props.getCurrentSelectedData(this.deviceId), 6000);
};
componentWillUnmount = () => {
//reset new loading to redux; fix blink screen
this.props.loadingAction(true);
this.props.loadingTimersAction(true);
this.unsubscribeShadow();
};
setMainCardData = async () => {
const { currentSelectedData, breakerStatus } = this.props;
const { currentSelectedData, breakerStatus, onlineStatus } = this.props;
this.setState({
description: currentSelectedData.description,
name: currentSelectedData.name,
rcbo: currentSelectedData.rcbo,
isOnline: currentSelectedData.isOnline,
isOnline: onlineStatus === 1 ? true : false,
isPowerOn: breakerStatus ? breakerStatus.SM1.BK_S : false,
});
};
......@@ -146,7 +160,6 @@ class SmartMeterDetailScreen extends Component {
const subBreakersStatus = _.pick(breakerStatus, ['ML1', 'ML2', 'ML3', 'ML4']);
// console.log('subBreakersStatus', subBreakersStatus);
existedSubBreakersData.map(mcbLink => {
subBreakersInfo.push(
mcbLink.map(subBreaker =>
......@@ -161,7 +174,6 @@ class SmartMeterDetailScreen extends Component {
)
);
});
this.setState({ subBreakersInfo });
};
......@@ -256,11 +268,9 @@ class SmartMeterDetailScreen extends Component {
const renderSubBreaker = (subBreaker, indexSubBreakers) => {
const handleOnPressSubBreakerSwitch = async value => {
// clearInterval(this.getDataInterval);
this.setState({ isWaiting: true });
await this.props.setSubBreakerStatus(value, indexMcbLinks, indexSubBreakers);
this.setState({ isWaiting: false });
// this.getDataInterval = setInterval(() => this.props.getCurrentSelectedData(this.deviceId), 6000);
};
return (
......@@ -345,6 +355,7 @@ class SmartMeterDetailScreen extends Component {
render() {
const { mcbLinksInfo } = this.state;
const { isLoadingValues, isLoadingList, isFocused } = this.props;
const isRefreshing = () => this._mcbLinksListMounted && (isLoadingList || isLoadingValues);
return isFocused ? (
<ScrollView
......@@ -352,7 +363,7 @@ class SmartMeterDetailScreen extends Component {
contentContainerStyle={[theme.containerWithPadding]}
refreshControl={
<RefreshControl
refreshing={this._mcbLinksListMounted && (isLoadingList || isLoadingValues)}
refreshing={isRefreshing()}
onRefresh={async () => {
await this.getData();
this.props.errorTimersAction(null);
......@@ -406,6 +417,7 @@ const mapStateToProps = state => ({
shadow: state.currentSelectedDeviceReducer.shadow,
breakerStatus: state.currentSelectedDeviceReducer.breakerStatus,
onlineStatus: state.currentSelectedDeviceReducer.onlineStatus,
});
const mapDispatchToProps = {
......@@ -417,14 +429,19 @@ const mapDispatchToProps = {
setMainStatus,
errorTimersAction,
setSubBreakerStatus,
updateSubscriptionToStore,
};
const withNavSmartMeterDetailScreen = withNavigationFocus(SmartMeterDetailScreen);
const WithSubscription = graphql(READ_SHADOW, {
options: props => ({ variables: { deviceid: props.navigation.getParam('deviceId') } }),
});
const enhancedScreen = WithSubscription(withNavigationFocus(SmartMeterDetailScreen));
export default connect(
mapStateToProps,
mapDispatchToProps
)(withNavSmartMeterDetailScreen);
)(enhancedScreen);
const styles = StyleSheet.create({
currentCard: {
......
import React, { Component } from 'react';
import { ActivityIndicator, View, Image } from 'react-native';
import { View, Image } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import logo from '../../assets/images/logo2.png';
import { width } from '../../constants/Layout';
import app from '../../firebase';
import { connect } from 'react-redux';
import { getCurrentUser } from '../../reduxStore/actions/cerrentUserAction';
// import { fireStore } from '../../firebase';
class AuthLoadingScreen extends Component {
static navigationOptions = {
......@@ -21,12 +20,11 @@ class AuthLoadingScreen extends Component {
};
_isMounted = false;
showLogoThenIndicator = () => {
setTimeout(() => this._isMounted && this.setState({ isShowImg: false }), 1200); // 1200
};
// showLogoThenIndicator = () => {
// setTimeout(() => this._isMounted && this.setState({ isShowImg: false }), 1200); // 1200
// };
bootstrapAsync = async () => {
this.showLogoThenIndicator();
try {
// Preload data from an external API && Preload data using AsyncStorage
const alreadyLaunched = await AsyncStorage.getItem('alreadyLaunched');
......@@ -64,11 +62,7 @@ class AuthLoadingScreen extends Component {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
{this.state.isShowImg ? (
<Image style={{ width: width * 0.9, resizeMode: 'contain' }} source={logo} />
) : (
<ActivityIndicator size="large" color="#f44c4c" />
)}
<Image style={{ width: width * 0.9, resizeMode: 'contain' }} source={logo} />
</View>
);
}
......
......@@ -65,6 +65,7 @@ const apolloMutation = async (mutation, variables) => {
mutation,
variables,
errorPolicy: 'all',
fetchPolicy: 'no-cache',
});
};
......@@ -82,7 +83,7 @@ const READ_SHADOW = gql`
const WRITE_SHADOW = gql`
mutation($deviceid: String!, $data: JSON!) {
writeShadow(deviceid: $deviceid, value: $data) {
writeShadow(deviceid: $deviceid, data: $data) {
data
}
}
......@@ -103,7 +104,16 @@ const QUERY_DEVICE_BY_TAG = gql`
}
}
`;
export { READ_SHADOW, WRITE_SHADOW, QUERY_DEVICE_BY_TAG, SUBSCRIBE_SHADOW };
const QUERY_ONLINE_STATUS = gql`
query($deviceid: String!) {
device(deviceid: $deviceid) {
status
}
}
`;
export { READ_SHADOW, WRITE_SHADOW, SUBSCRIBE_SHADOW };
export { QUERY_DEVICE_BY_TAG, QUERY_ONLINE_STATUS };
// const apolloSubscription = async (query, queryVariables, subscribe, subscribeVariables) => {
// const queryData = client.watchQuery({
......
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