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. 20
      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 PinTransitavel from "../assets/floodZonesAssets/PinTransitavel";
import moment from "moment";
import cache from "../utility/cache";
const custom_assets = {
pluviometer: assets.pluviometer,
@ -115,8 +116,10 @@ function buildPolygonsObject(response, name) {
}
function buildMarkerObject(response, name) {
console.log("\n\n--------------------------------------------------------");
//console.log(response);
const r = JSON.parse(response);
// console.log(r);
const resposta = r.formsanswersgeom;
const formsanswersgeom = JSON.parse(resposta).coordinates;
var situation = null;
@ -141,23 +144,30 @@ function buildMarkerObject(response, name) {
function verifyResponse(response, name) {
var markers = [];
var cache_marker = [];
if (response) {
const answer = JSON.parse(response);
if (answer.success == true) {
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;
}
function getFormsAnswers(socketObject, dispatch) {
function getFormsAnswers(socketObject, dispatch, fetchFromCache) {
const [socketResponse, setSocketResponse] = useState();
// 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 }) => {
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);
};
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();
@ -188,14 +205,17 @@ function getFormsAnswers(socketObject, dispatch) {
// we were told to "fix" this issue this way for a while.
useEffect(() => {
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 = new WebSocket(socketObject.url);
openListeners();
}
}, [timerCounter]);
// Timer acting like a clock at F = 1/60 Hz
useEffect(() => {
const timer = setInterval(() => {
@ -204,9 +224,12 @@ function getFormsAnswers(socketObject, dispatch) {
return () => clearTimeout(timer);
}, []);
useEffect(() => {
dispatch({ increment: verifyResponse(socketResponse, socketObject.name) });
if (!fetchFromCache) {
dispatch({
increment: verifyResponse(socketResponse, socketObject.name),
});
}
}, [socketResponse]);
}
@ -218,9 +241,32 @@ function reducer(state = initialState, action) {
return { markers: state.markers };
}
export default function useSocketMarkers() {
export default function useSocketMarkers(fetchFromCache) {
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;
}

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 OpenStreetMap from "../components/map/OpenStreetMap";
import attachFocusToQuery from "../hooks/useFocus";
@ -7,6 +7,8 @@ import useSocketMarkers from "../hooks/useSocketMarkers";
import LoadingMarkersModal from "../components/LoadingMarkersModal";
import NoGPSError from "../components/NoGPSError";
import NetInfo, { useNetInfo } from "@react-native-community/netinfo";
export default function MapFeedScreen(props) {
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("location: " + JSON.stringify(global.location))

20
src/app/utility/cache.js

@ -10,28 +10,28 @@ const store = async (key, value) => {
value,
timestamp: Date.now(),
};
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 storedTime = moment(item.timestamp);
return now.diff(storedTime, "minutes") > expiryInMinutes;
};
const get = async(key) => {
const get = async (key) => {
try {
const value = await AsyncStorage.get(prefix + key);
if (!item) return null;
const value = await AsyncStorage.getItem(prefix + key);
if (isExpired(isExperired)) {
/*if (isExpired(isExperired)) {
await AsyncStorage.removeItem(prefix + key);
return null;
}
}*/
if (!value) return null;
return value;
} catch (error) {
console.log(error);
}

Loading…
Cancel
Save