Browse Source

PluviometerGraphics now is from user data

master
GabrielTrettel 4 years ago
parent
commit
786ed0c5b0
  1. 7
      src/app/api/pluviometer.js
  2. 8
      src/app/components/MapModal.js
  3. 18
      src/app/components/PluviometerGraphics.js
  4. 55
      src/app/database/databaseLoader.js
  5. 28
      src/app/database/db.js
  6. 97
      src/app/hooks/selectFromDB.js
  7. 8
      src/app/hooks/useFocus.js
  8. 8
      src/app/screens/PluviometerSharingDataScreen.js

7
src/app/api/pluviometer.js

@ -0,0 +1,7 @@
export default function requestPluviometerData() {
console.log(Math.floor(Math.random() * 10));
return {
labels: ["1", "2", "3"],
values: [1, 2, 3],
};
}

8
src/app/components/MapModal.js

@ -155,10 +155,14 @@ function reviews(props) {
); );
} }
function moreInfo() {
function moreInfo(props) {
return ( return (
<View style={styles.pluviometer_diary}> <View style={styles.pluviometer_diary}>
<PluviometerGraphics chartHeight={chartHeight} />
<PluviometerGraphics
chartHeight={chartHeight}
values={props.data.values}
labels={props.data.labels}
/>
</View> </View>
); );
} }

18
src/app/components/PluviometerGraphics.js

@ -1,22 +1,20 @@
import React from "react"; import React from "react";
import { StyleSheet, Text, View } from "react-native"; import { StyleSheet, Text, View } from "react-native";
import Screen from "../components/Screen";
import { dimensions, scaleDimsFromWidth } from "../config/dimensions";
import colors from "../config/colors/"; import colors from "../config/colors/";
import { LineChart } from "react-native-chart-kit"; import { LineChart } from "react-native-chart-kit";
import requestPluviometerData from "../api/pluviometer";
import { Dimensions } from "react-native"; import { Dimensions } from "react-native";
const screenWidth = Dimensions.get("window").width * 0.95; const screenWidth = Dimensions.get("window").width * 0.95;
const screenHeight = Dimensions.get("window").height * 0.3; const screenHeight = Dimensions.get("window").height * 0.3;
const data = {
//substituir por dados da API
labels: ["01/01", "01/02", "01/03", "01/04", "01/05"],
function figure_config(labels, values) {
return {
labels: labels,
datasets: [ datasets: [
{ {
data: [0, 10, 20, 25, 5],
data: values,
color: () => colors.gold, color: () => colors.gold,
strokeWidth: 2, strokeWidth: 2,
}, },
@ -24,6 +22,8 @@ const data = {
legend: ["Registros pluviométricos"], legend: ["Registros pluviométricos"],
}; };
}
const chartConfig = { const chartConfig = {
backgroundGradientFrom: 0, backgroundGradientFrom: 0,
backgroundGradientFromOpacity: 0, backgroundGradientFromOpacity: 0,
@ -37,7 +37,7 @@ const chartConfig = {
}, },
}; };
function PluviometerGraphics({ chartHeight = screenHeight }) {
function PluviometerGraphics({ chartHeight, labels, values }) {
return ( return (
<View <View
style={{ style={{
@ -48,7 +48,7 @@ function PluviometerGraphics({ chartHeight = screenHeight }) {
}} }}
> >
<LineChart <LineChart
data={data}
data={figure_config(labels, values)}
width={screenWidth} width={screenWidth}
height={chartHeight} height={chartHeight}
chartConfig={chartConfig} chartConfig={chartConfig}

55
src/app/database/databaseLoader.js

@ -18,7 +18,15 @@ function transaction(db, query, values) {
}); });
} }
function insertFloodZone({ images, description, passable, location, date, time, address }) {
function insertFloodZone({
images,
description,
passable,
location,
date,
time,
address,
}) {
const query = `INSERT INTO FloodZones(Description, Images, Latitude, Longitude, Passable, Date, Time, Address) VALUES(?, ?, ?, ?, ?, ?, ?, ?);`; const query = `INSERT INTO FloodZones(Description, Images, Latitude, Longitude, Passable, Date, Time, Address) VALUES(?, ?, ?, ?, ?, ?, ?, ?);`;
if (location === undefined) { if (location === undefined) {
console.debug("undefined location"); console.debug("undefined location");
@ -39,28 +47,41 @@ function insertFloodZone({ images, description, passable, location, date, time,
transaction(global.userDataBase, query, values); transaction(global.userDataBase, query, values);
} }
function insertPluviometerData({ pluviometer, description, images, dateTime, time, location, address }) {
const query = `INSERT INTO Pluviometer(Date, Images, Latitude, Longitude, Precipitation, Address, Description) VALUES(?, ?, ?, ?, ?, ?, ?);`;
function insertPluviometerData({
pluviometer,
description,
images,
dateTime,
time,
}) {
const query = `INSERT INTO PluviometerData(Date, Images, Precipitation, Description) VALUES(?, ?, ?, ?);`;
if (location === undefined) {
console.debug("undefined location");
return;
}
// if (location === undefined) {
// console.debug("undefined location");
// return;
// }
const values = [ const values = [
moment(dateTime).format("DD/MM/YYYY") +" | "+ moment(time).format("HH:mm"),
moment(dateTime).format("DD/MM/YYYY") +
" | " +
moment(time).format("HH:mm"),
JSON.stringify(images), JSON.stringify(images),
parseFloat(location["latitude"]),
parseFloat(location["longitude"]),
parseFloat(pluviometer), parseFloat(pluviometer),
address,
description, description,
]; ];
transaction(global.userDataBase, query, values); transaction(global.userDataBase, query, values);
} }
function insertRainData({ images, description, rain, location, date, time, address }) {
function insertRainData({
images,
description,
rain,
location,
date,
time,
address,
}) {
const query = `INSERT INTO RainLevel(RainIdx, Description, Images, Latitude, Longitude, Date, Time, Address) VALUES(?, ?, ?, ?, ?, ?, ?, ?);`; const query = `INSERT INTO RainLevel(RainIdx, Description, Images, Latitude, Longitude, Date, Time, Address) VALUES(?, ?, ?, ?, ?, ?, ?, ?);`;
if (location === undefined) { if (location === undefined) {
@ -84,7 +105,15 @@ function insertRainData({ images, description, rain, location, date, time, addre
transaction(global.userDataBase, query, values); transaction(global.userDataBase, query, values);
} }
function insertRiverData({ images, description, riverScale, location, date, time, address }) {
function insertRiverData({
images,
description,
riverScale,
location,
date,
time,
address,
}) {
const query = `INSERT INTO RiverLevel(RiverIdx, Description, Images, Latitude, Longitude, Date, Time, Address) VALUES(?, ?, ?, ?, ?, ?, ?, ?);`; const query = `INSERT INTO RiverLevel(RiverIdx, Description, Images, Latitude, Longitude, Date, Time, Address) VALUES(?, ?, ?, ?, ?, ?, ?, ?);`;
if (location === undefined) { if (location === undefined) {

28
src/app/database/db.js

@ -1,6 +1,13 @@
// FIXME: Refactor to our database ERM already combined // FIXME: Refactor to our database ERM already combined
const init_queries = [ const init_queries = [
`CREATE TABLE IF NOT EXISTS PluviometerData (
Id integer PRIMARY KEY autoincrement,
Date text NOT NULL,
Images text,
Precipitation real NOT NULL,
Description text
)`,
`CREATE TABLE IF NOT EXISTS FloodZones ( `CREATE TABLE IF NOT EXISTS FloodZones (
Id integer PRIMARY KEY autoincrement, Id integer PRIMARY KEY autoincrement,
Description text, Description text,
@ -12,17 +19,16 @@ const init_queries = [
Time text, Time text,
Address text Address text
);`, );`,
`CREATE TABLE IF NOT EXISTS Pluviometer (
Id integer PRIMARY KEY autoincrement,
Date text NOT NULL,
Images text,
Latitude real NOT NULL,
Longitude real NOT NULL,
Precipitation real NOT NULL,
Time text,
Address text,
Description text
);`,
// `CREATE TABLE IF NOT EXISTS Pluviometer (
// Id integer PRIMARY KEY autoincrement,
// Date text NOT NULL,
// Latitude real NOT NULL,
// Longitude real NOT NULL,
// Address text,
// School text,
// );`,
// `INSERT INTO Pluviometer(Latitude, Longitude, Precipitation, Address, Description) VALUES(?, ?, ?, ?, ?, ?, ?);`,
`CREATE TABLE IF NOT EXISTS RainLevel ( `CREATE TABLE IF NOT EXISTS RainLevel (
Id integer PRIMARY KEY autoincrement, Id integer PRIMARY KEY autoincrement,
Description text, Description text,

97
src/app/hooks/selectFromDB.js

@ -1,5 +1,6 @@
import { useEffect, useReducer } from "react";
import { useState, useEffect, useReducer, useContext } from "react";
import { CurrentLocationContext } from "../context/CurrentLocationContext";
import "../config/globals"; import "../config/globals";
import assets from "../config/assets"; import assets from "../config/assets";
@ -44,32 +45,6 @@ function is_valid(id, category) {
return true; return true;
} }
function partsePluviometer(row) {
if (!is_valid(row["Id"], "pluv")) {
return null;
}
const description = row["Description"] ? "\n\n" + row["Description"] : "";
// displacement += offset;
const i = {
ID: ++ID,
name: "pluviometer",
title: "Pluviometro",
coordinate: {
latitude: row["Latitude"] + displacement,
longitude: row["Longitude"],
},
image: custom_assets.pluviometer,
date: row["Date"],
description:
row["Precipitation"] + "mm" + ", " + row["Date"] + description,
pictures: row["Images"],
address: row["Address"],
};
console.log(i);
return i;
}
function parseFloodZones(row) { function parseFloodZones(row) {
if (!is_valid(row["Id"], "flood")) { if (!is_valid(row["Id"], "flood")) {
return null; return null;
@ -96,6 +71,7 @@ function parseFloodZones(row) {
} }
function parseRiverLevel(row) { function parseRiverLevel(row) {
console.log("IDDD " + row["Id"]);
if (!is_valid(row["Id"], "river")) { if (!is_valid(row["Id"], "river")) {
return null; return null;
} }
@ -152,7 +128,9 @@ function parseRainLevel(row) {
}; };
} }
function parseResult(db_result, parseRow) {
function parseResult(db_result, parseRow, cleanParse) {
if (cleanParse) return parseRow(db_result);
var warnings = []; var warnings = [];
for (let i = 0; i < db_result.rows.length; ++i) { for (let i = 0; i < db_result.rows.length; ++i) {
@ -174,10 +152,10 @@ function genericSelect(queriesToParsersMapper, dispatch, isFocused) {
useEffect(() => { useEffect(() => {
console.log("requesting data"); console.log("requesting data");
if (isAvailable(global.userDataBase)) { if (isAvailable(global.userDataBase)) {
queriesToParsersMapper.forEach(([query, parser]) => {
queriesToParsersMapper.forEach(([query, parser, cleanParse]) => {
global.userDataBase.transaction((tx) => { global.userDataBase.transaction((tx) => {
tx.executeSql(query, [], (tx, results) => { tx.executeSql(query, [], (tx, results) => {
dispatch({ increment: parseResult(results, parser) });
dispatch({ increment: parseResult(results, parser, cleanParse) });
}); });
}); });
}); });
@ -188,6 +166,13 @@ function genericSelect(queriesToParsersMapper, dispatch, isFocused) {
const initialState = { markers: new Set() }; const initialState = { markers: new Set() };
function reducer(state = initialState, action) { function reducer(state = initialState, action) {
// NOTE: removing old pluviometer value to new data can be displayed
state.markers.forEach((m) => {
if (m.name === "pluviometer") {
state.markers.delete(m);
}
});
action.increment.map((val) => { action.increment.map((val) => {
state.markers.add(val); state.markers.add(val);
}); });
@ -200,11 +185,55 @@ function reducer(state = initialState, action) {
function useMarkers(isFocused) { function useMarkers(isFocused) {
const [state, dispatch] = useReducer(reducer, initialState); const [state, dispatch] = useReducer(reducer, initialState);
const context = useContext(CurrentLocationContext);
const location = context.currentCoordinates;
const addr = context.currentLocation;
const parsePluviometer = (db_result) => {
if (db_result.rows.length <= 0) return [];
const values = {
pictures: null,
data: {
labels: [],
values: [],
},
description: "",
date: "",
};
const start = Math.max(0, db_result.rows.length - 7);
for (let i = start; i < db_result.rows.length; ++i) {
var row = db_result.rows.item(i);
description = row["Description"] ? "\n\n" + row["Description"] : "";
values.image = custom_assets.pluviometer;
values.date = row["Date"];
values.description =
row["Precipitation"] + "mm" + ", " + row["Date"] + description;
values.pictures = row["Images"];
values.data.labels.push(row["Date"].slice(0, 5));
values.data.values.push(parseInt(row["Precipitation"]));
}
const result = {
ID: ++ID,
name: "pluviometer",
title: "Pluviometro 1",
coordinate: location,
address: addr,
...values,
};
console.log(result);
return [result];
};
const queriesToParsersMapper = [ const queriesToParsersMapper = [
["SELECT * FROM FloodZones;", parseFloodZones],
["SELECT * FROM Pluviometer;", partsePluviometer],
["SELECT * FROM RiverLevel;", parseRiverLevel],
["SELECT * FROM RainLevel;", parseRainLevel],
["SELECT * FROM FloodZones;", parseFloodZones, false],
["SELECT * FROM RiverLevel;", parseRiverLevel, false],
["SELECT * FROM RainLevel;", parseRainLevel, false],
["SELECT * FROM PluviometerData;", parsePluviometer, true],
]; ];
genericSelect(queriesToParsersMapper, dispatch, isFocused); genericSelect(queriesToParsersMapper, dispatch, isFocused);

8
src/app/hooks/useFocus.js

@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { useEffect, useState, useContext } from "react";
import { useIsFocused } from "@react-navigation/native"; import { useIsFocused } from "@react-navigation/native";
import { CurrentLocationContext } from "../context/CurrentLocationContext";
/* /*
NOTE: This hook is used this way because react-navigation/native NOTE: This hook is used this way because react-navigation/native
@ -13,13 +13,15 @@ import { useIsFocused } from "@react-navigation/native";
export default function attachFocusToQuery() { export default function attachFocusToQuery() {
const isFocused = useIsFocused(); const isFocused = useIsFocused();
const context = useContext(CurrentLocationContext);
const [hasToQuery, setHasToQuery] = useState(null); const [hasToQuery, setHasToQuery] = useState(null);
useEffect(() => { useEffect(() => {
if (isFocused == true) { if (isFocused == true) {
setHasToQuery(!hasToQuery); setHasToQuery(!hasToQuery);
} }
}, [isFocused]);
}, [isFocused, context.getCurrentLocation]);
return hasToQuery; return hasToQuery;
} }

8
src/app/screens/PluviometerSharingDataScreen.js

@ -53,11 +53,11 @@ function PluviometerSharingDataScreen(props) {
<Form <Form
initialValues={{ initialValues={{
pluviometer: "", pluviometer: "",
images: [],
description: "", description: "",
images: [],
}} }}
onSubmit={(values) => { onSubmit={(values) => {
insertPluviometerData({ ...values, dateTime, time, location, address });
insertPluviometerData({ ...values, dateTime, time });
showMessage({ showMessage({
message: "Informação enviada!", message: "Informação enviada!",
duration: 3000, duration: 3000,
@ -93,9 +93,7 @@ function PluviometerSharingDataScreen(props) {
}} }}
> >
{/*Data da coleta:*/} {/*Data da coleta:*/}
<View
style={{ flex: 1 }}
>
<View style={{ flex: 1 }}>
<FormDatePicker <FormDatePicker
textStyle={{ textStyle={{
borderColor: colors.gray, borderColor: colors.gray,

Loading…
Cancel
Save