Browse Source

caching forms markers

master
analuizaff 3 years ago
parent
commit
4129cb3bbd
  1. 80
      src/app/hooks/useSocketMarkers.js
  2. 8
      src/app/screens/MapFeedScreen.js
  3. 18
      src/app/utility/cache.js

80
src/app/hooks/useSocketMarkers.js

@ -3,6 +3,7 @@ import assets from "../config/assets";
import PinIntransitavel from "../assets/floodZonesAssets/PinIntransitavel"; import PinIntransitavel from "../assets/floodZonesAssets/PinIntransitavel";
import PinTransitavel from "../assets/floodZonesAssets/PinTransitavel"; import PinTransitavel from "../assets/floodZonesAssets/PinTransitavel";
import moment from "moment"; import moment from "moment";
import cache from "../utility/cache";
const custom_assets = { const custom_assets = {
pluviometer: assets.pluviometer, pluviometer: assets.pluviometer,
@ -115,8 +116,10 @@ function buildPolygonsObject(response, name) {
} }
function buildMarkerObject(response, name) { function buildMarkerObject(response, name) {
console.log("\n\n--------------------------------------------------------");
//console.log(response);
const r = JSON.parse(response); const r = JSON.parse(response);
// console.log(r);
const resposta = r.formsanswersgeom; const resposta = r.formsanswersgeom;
const formsanswersgeom = JSON.parse(resposta).coordinates; const formsanswersgeom = JSON.parse(resposta).coordinates;
var situation = null; var situation = null;
@ -141,23 +144,30 @@ function buildMarkerObject(response, name) {
function verifyResponse(response, name) { function verifyResponse(response, name) {
var markers = []; var markers = [];
var cache_marker = [];
if (response) { if (response) {
const answer = JSON.parse(response); const answer = JSON.parse(response);
if (answer.success == true) { if (answer.success == true) {
const formAnswer = answer.responseData.array_to_json; const formAnswer = answer.responseData.array_to_json;
answer.responseData.array_to_json.forEach((r) =>
r.formcode == "FLOODZONES_OFFICIAL"
? markers.push(buildPolygonsObject(JSON.stringify(r), name))
: markers.push(buildMarkerObject(JSON.stringify(r), name))
);
answer.responseData.array_to_json.forEach((r) => {
if (r.formcode == "FLOODZONES_OFFICIAL") {
markers.push(buildPolygonsObject(JSON.stringify(r), name));
} else {
markers.push(buildMarkerObject(JSON.stringify(r), name));
} }
});
if (name !== "susceptibilityAreas") {
cache.store(name, markers);
} }
}
}
return markers; return markers;
} }
function getFormsAnswers(socketObject, dispatch) {
function getFormsAnswers(socketObject, dispatch, fetchFromCache) {
const [socketResponse, setSocketResponse] = useState(); const [socketResponse, setSocketResponse] = useState();
// GATO: Was getting an error due to too long timer (10min), so counting 10 // GATO: Was getting an error due to too long timer (10min), so counting 10
@ -170,14 +180,21 @@ function getFormsAnswers(socketObject, dispatch) {
}; };
socketObject.socketUrl.onmessage = ({ data }) => { socketObject.socketUrl.onmessage = ({ data }) => {
console.log(`\t ====== Getting data from: ${socketObject.name} => ${moment().format('DD/MM, h:mm:ss:SSS')}`);
console.log(
`\t ====== Getting data from: ${
socketObject.name
} => ${moment().format("DD/MM, h:mm:ss:SSS")}`
);
setSocketResponse(data); setSocketResponse(data);
}; };
socketObject.socketUrl.onclose = () => { socketObject.socketUrl.onclose = () => {
console.log(`\t ====== Socket closed : ${socketObject.name} => ${moment().format('DD/MM, h:mm:ss:SSS')}`);
}
console.log(
`\t ====== Socket closed : ${socketObject.name} => ${moment().format(
"DD/MM, h:mm:ss:SSS"
)}`
);
};
}; };
openListeners(); openListeners();
@ -188,14 +205,17 @@ function getFormsAnswers(socketObject, dispatch) {
// we were told to "fix" this issue this way for a while. // we were told to "fix" this issue this way for a while.
useEffect(() => { useEffect(() => {
if (timerCounter % 4 == 0) { if (timerCounter % 4 == 0) {
console.log(`========> Closing/Opening socket: ${socketObject.name} => ${moment().format('DD/MM, h:mm:ss:SSS')}`);
console.log(
`========> Closing/Opening socket: ${
socketObject.name
} => ${moment().format("DD/MM, h:mm:ss:SSS")}`
);
socketObject.socketUrl.close(); socketObject.socketUrl.close();
socketObject.socketUrl = new WebSocket(socketObject.url); socketObject.socketUrl = new WebSocket(socketObject.url);
openListeners(); openListeners();
} }
}, [timerCounter]); }, [timerCounter]);
// Timer acting like a clock at F = 1/60 Hz // Timer acting like a clock at F = 1/60 Hz
useEffect(() => { useEffect(() => {
const timer = setInterval(() => { const timer = setInterval(() => {
@ -204,9 +224,12 @@ function getFormsAnswers(socketObject, dispatch) {
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, []); }, []);
useEffect(() => { useEffect(() => {
dispatch({ increment: verifyResponse(socketResponse, socketObject.name) });
if (!fetchFromCache) {
dispatch({
increment: verifyResponse(socketResponse, socketObject.name),
});
}
}, [socketResponse]); }, [socketResponse]);
} }
@ -218,9 +241,32 @@ function reducer(state = initialState, action) {
return { markers: state.markers }; return { markers: state.markers };
} }
export default function useSocketMarkers() {
export default function useSocketMarkers(fetchFromCache) {
const [state, dispatch] = useReducer(reducer, initialState); const [state, dispatch] = useReducer(reducer, initialState);
global.formsSockets.forEach((socket) => getFormsAnswers(socket, dispatch));
const [dataFromCache, setDataFromCache] = useState();
const formsKeys = [
"floodZones",
"rain",
"pluviometer",
"automaticPluviometer",
"riverFlood",
];
useEffect(() => {
if (fetchFromCache) {
formsKeys.forEach((key) => {
cache.get(key).then((cachedData) => {
if (cachedData) {
dispatch({ increment: JSON.parse(cachedData) });
}
});
});
}
}, []);
global.formsSockets.forEach((socket) =>
getFormsAnswers(socket, dispatch, fetchFromCache)
);
//console.log(state.markers)
return state; return state;
} }

8
src/app/screens/MapFeedScreen.js

@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import { StyleSheet, View, Text } from "react-native"; import { StyleSheet, View, Text } from "react-native";
import OpenStreetMap from "../components/map/OpenStreetMap"; import OpenStreetMap from "../components/map/OpenStreetMap";
import attachFocusToQuery from "../hooks/useFocus"; import attachFocusToQuery from "../hooks/useFocus";
@ -7,6 +7,8 @@ import useSocketMarkers from "../hooks/useSocketMarkers";
import LoadingMarkersModal from "../components/LoadingMarkersModal"; import LoadingMarkersModal from "../components/LoadingMarkersModal";
import NoGPSError from "../components/NoGPSError"; import NoGPSError from "../components/NoGPSError";
import NetInfo, { useNetInfo } from "@react-native-community/netinfo";
export default function MapFeedScreen(props) { export default function MapFeedScreen(props) {
HeaderBarMenu(props.navigation); HeaderBarMenu(props.navigation);
@ -24,7 +26,9 @@ export default function MapFeedScreen(props) {
}, },
}); });
const markers = useSocketMarkers();
const markers = useSocketMarkers(!(useNetInfo().isConnected));
// console.log("============= qtd markers " + markers.markers.size + " ================" ) // console.log("============= qtd markers " + markers.markers.size + " ================" )
// console.log("location: " + JSON.stringify(global.location)) // console.log("location: " + JSON.stringify(global.location))

18
src/app/utility/cache.js

@ -10,13 +10,12 @@ const store = async (key, value) => {
value, value,
timestamp: Date.now(), timestamp: Date.now(),
}; };
await AsyncStorage.setItem(prefix + key, JSON.stringify(value)); await AsyncStorage.setItem(prefix + key, JSON.stringify(value));
} catch (error) {
console.log(error);
}
} catch (error) {}
}; };
const isExpired = (intem) => {
const isExpired = (item) => {
const now = moment(Date.now()); const now = moment(Date.now());
const storedTime = moment(item.timestamp); const storedTime = moment(item.timestamp);
return now.diff(storedTime, "minutes") > expiryInMinutes; return now.diff(storedTime, "minutes") > expiryInMinutes;
@ -24,14 +23,15 @@ const isExpired = (intem) => {
const get = async (key) => { const get = async (key) => {
try { try {
const value = await AsyncStorage.get(prefix + key);
const value = await AsyncStorage.getItem(prefix + key);
if (!item) return null;
if (isExpired(isExperired)) {
/*if (isExpired(isExperired)) {
await AsyncStorage.removeItem(prefix + key); await AsyncStorage.removeItem(prefix + key);
return null; return null;
}
}*/
if (!value) return null;
return value;
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} }

Loading…
Cancel
Save