Skip to content

Commit

Permalink
Changes to frontend for route
Browse files Browse the repository at this point in the history
  • Loading branch information
Norukh committed Dec 3, 2023
1 parent 8a1217c commit 202c8bd
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 45 deletions.
7 changes: 4 additions & 3 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions lib/path_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
no_empty_if_below = 0.4
n_days = 5


def get_next_n_days(n_days: int, no_empty_if_below: float):
all_needed_time = []
all_needed_capacity = []
Expand All @@ -59,15 +60,15 @@ def get_next_n_days(n_days: int, no_empty_if_below: float):
print(needed_capacity)
print(visited_stations_by_id)
most_left_point = np.argmin([float(x["lat"]) for x in visited_stations[1:-1]])
tour, locations = path_finder.refine_path(most_left_point+1, visited_stops) # +1 because visited_stations[1:-1]
tour, locations = path_finder.refine_path(most_left_point+1, visited_stops) #+1 because visited_stations[1:-1]
locations = [station_0] + locations + [station_0]
print(tour)

all_needed_time.append(needed_time)
all_needed_capacity.append(needed_capacity)
all_visited_locations.append(locations)
all_visited_locations.append(visited_stations)

# calculate predictions for next iteration
#calculate predictions for next iteration
for sensor_id, values_raw in list(sensor_data_raw.groupby('sensor_id')):
last_5_values = values_raw.sort_values(by="date").tail(5-i)["level"].to_numpy()
if all_predictions.get(sensor_id):
Expand All @@ -86,7 +87,7 @@ def get_next_n_days(n_days: int, no_empty_if_below: float):
for sensor_id, predictions in all_predictions.items():
#has_been_emptied = np.in1d(sensor_id, visited_stations_by_id)[0]
#if has_been_emptied:
# predictions[-1] = 0 # updates value in all_predictions
# predictions[-1] = 0 #updates value in all_predictions

sensor = sensor_data[sensor_data["sensor_id"] == sensor_id].iloc[0]
new_entry = pd.Series({
Expand All @@ -102,9 +103,9 @@ def get_next_n_days(n_days: int, no_empty_if_below: float):

#get_next_n_days(n_days, no_empty_if_below)


@path_api.route("", methods=['GET'])
def get_path():
selected_date = request.args.get('date')
no_empty_if_below = float(request.args.get('no_empty_if_below')) if request.args.get('no_empty_if_below') is not None else 0.4
glass_type_list = request.args.get('glass_type_list').split(",") if request.args.get('glass_type_list') is not None else None

Expand Down
9 changes: 3 additions & 6 deletions predictor-app/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,16 @@ const App = () => {
const dispatch = useDispatch();
const sensors = useSelector((state) => state.sensor.sensors);

const [keyForChild, setKeyForChild] = useState(1);

useEffect(() => {
if (sensors === undefined || sensors.length === 0) {
if (sensors === undefined || sensors.length < 1) {
getSensors()
.then((result) => {
console.log(result);
dispatch(setSensors(result));
})
.then(() => setKeyForChild((prevKey) => prevKey + 1))
.catch((ex) => console.error(ex));
}
}, [dispatch, sensors]);
});

return (
<ThemeProvider theme={theme}>
Expand Down Expand Up @@ -72,7 +69,7 @@ const App = () => {
<Box component="main" sx={{ flexGrow: 1 }}>
<Toolbar />

<GlassCollectionMap key={keyForChild} sensors={sensors} />
<GlassCollectionMap />

</Box>
</Box>
Expand Down
15 changes: 2 additions & 13 deletions predictor-app/src/api.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* Use the exported functions to call the API.
* If necessary, adjust the backend address below:
*/
const backend = "http://127.0.0.1:5000";
const backend = "http://localhost:5000";

export function getPath(params) {
return getJson("/path", params).then(parseJSON);
Expand Down Expand Up @@ -39,15 +39,4 @@ function getJson(endpoint, params) {

function parseJSON(response) {
return response.json();
}

function postJson(endpoint, params) {
return fetch(`${backend}${endpoint}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(params),
}).then(checkStatus);
}
}
10 changes: 2 additions & 8 deletions predictor-app/src/components/GlassCollectionMap.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,6 @@ const center = {
const zoom = 13;

const GlassCollectionMap = ({ key }) => {
useEffect(() => {
// This effect will run whenever the key prop changes
console.log('ChildComponent has been re-rendered with a new key:', key);

// Add any logic here to update the component with new data
}, [key]);

const sensors = useSelector((state) => state.sensor.sensors);
const predictedRoute = useSelector((state) => state.predictedRoute.predictedRoute);
Expand All @@ -39,7 +33,7 @@ const GlassCollectionMap = ({ key }) => {
const [travelMode, setTravelMode] = useState('DRIVING'); // You can change the travel mode as needed

useEffect(() => {
if (isLoaded && predictedRoute) {
if (isLoaded && predictedRoute && predictedRoute.length > 0) {
const directionsService = new window.google.maps.DirectionsService();

const origin = {
Expand Down Expand Up @@ -123,7 +117,7 @@ const GlassCollectionMap = ({ key }) => {
)) : null
}

{directions}
{predictedRoute ? directions : null}

</GoogleMap>
);
Expand Down
1 change: 0 additions & 1 deletion predictor-app/src/components/GlassMarker.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ const GlassMarker = (props) => {
<TableContainer style={{ marginTop: '1em' }} component={Paper}>
<Table sx={{ minWidth: 200 }} aria-label="simple table">
<TableBody>


<TableRow key={2} sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
<TableCell component="th" scope="row">
Expand Down
61 changes: 52 additions & 9 deletions predictor-app/src/components/Sidebar.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import FunctionsIcon from '@mui/icons-material/Functions';
import dayjs from 'dayjs';
import LinearProgress from '@mui/material/LinearProgress';
import Badge from '@mui/material/Badge';
import { getPath } from '../api';
import { getPath, getSensors } from '../api';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Typography from '@mui/material/Typography';
Expand All @@ -27,7 +27,9 @@ import ListItemAvatar from '@mui/material/ListItemAvatar';
import Avatar from '@mui/material/Avatar';
import RoomIcon from '@mui/icons-material/Room';
import RecyclingIcon from '@mui/icons-material/Recycling';
import { useSelector } from "react-redux";
import { useSelector, useDispatch } from "react-redux";
import { setPredictedRoute } from '../redux/predictedRouteSlice';
import { setSensors } from '../redux/sensorSlice';

const marks = [
{
Expand Down Expand Up @@ -68,9 +70,9 @@ const durationMarks = [
];

const Sidebar = () => {


const dispatch = useDispatch();
const predictedRoute = useSelector((state) => state.predictedRoute.predictedRoute);
const sensors = useSelector((state) => state.sensor.sensors);

const [state, setState] = React.useState({
brown: true,
Expand Down Expand Up @@ -127,13 +129,19 @@ const Sidebar = () => {
<b>Nächste Leerung {selectedDate.format('DD.MM.YYYY')}</b>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DateCalendar defaultValue={dayjs().add(1, 'day')}

disablePast={true}

onChange={(newValue) => {
if (newValue > dayjs().add(5, 'day')) {
console.log('too far in the future');
}
setState({ ...state, selectedDate: newValue });

const selectedIndex = newValue.diff(dayjs(), 'day');
dispatch(setPredictedRoute(state.predictionResult.visited_locations[selectedIndex]));

filterSensors(selectedIndex, state.predictionResult.visited_locations);
}}

slots={{
Expand Down Expand Up @@ -167,15 +175,15 @@ const Sidebar = () => {
</Card>
</Grid>

{state.predictionresult && Object.isEmpty(state.predictionresult) ?
{state.predictionResult ?
<Grid item xs={12}>
<Card style={{ backgroundColor: '#16A74E42' }}>
<CardContent>
<b>Vorhersage zur Leerung am {selectedDate.format('DD.MM.YYYY')}</b>
<Typography>
Geleerte Glascontainer: {state.predictionResult ? state.predictionResult?.visited_locations[0].length : ''}
Sum. geleerte Kapazitäten: {state.predictionResult ? state.predictionResult?.needed_capacities[0] : ''}<br/>
Berechnte Tourdauer (in h): {state.predictionResult ? state.predictionResult?.needed_times[0] / 3600 : ''}h<br/>
Geleerte Glascontainer: {state.predictionResult ? state.predictionResult?.visited_locations[selectedDate.diff(dayjs(), 'day')].length -2 : ''}<br/>
Sum. geleerte Kapazitäten: {state.predictionResult ? state.predictionResult?.needed_capacities[selectedDate.diff(dayjs(), 'day')] : ''}<br/>
Berechnte Tourdauer (in h): {state.predictionResult ? state.predictionResult?.needed_times[selectedDate.diff(dayjs(), 'day')] / 3600 : ''}h<br/>
</Typography>

</CardContent>
Expand Down Expand Up @@ -327,22 +335,57 @@ const Sidebar = () => {
white: state.white,
green: state.green,
no_empty_if_below: state.no_empty_if_below,
tour_duration: state.tour_duration,
};

getPath(params)
.then((result) => {
dispatch(setPredictedRoute(result.visited_locations[0]));
setState({ ...state, predictionRunning: false, predictionDone: true, predictionResult: result });

filterSensors(0, result.visited_locations);
})
.catch((ex) => console.error(ex));
}

function handleBack() {
setState({ ...state, predictionDone: false });
dispatch(setPredictedRoute([]));
setState({ ...state, predictionDone: false, predictionResult: {} });

fetchSensors();
}

function fetchSensors() {
getSensors()
.then((result) => {
dispatch(setSensors(result));
})
.catch((ex) => console.error(ex));
}

function percentValueText(value) {
return `${value}%`;
}

function filterSensors(selectedIndex, visited_locations) {
getSensors()
.then((result) => {

const filteredSensors = [];

for (const sensor of result) {
for (let i = 1; i < visited_locations[selectedIndex].length - 1; i++) {
if (sensor.sensor_id.includes(visited_locations[selectedIndex][i].sensor_id)) {
filteredSensors.push(sensor);
}
}
}

dispatch(setSensors(filteredSensors));

})
.catch((ex) => console.error(ex));
}
};

export default Sidebar;

0 comments on commit 202c8bd

Please sign in to comment.