Skip to content
Snippets Groups Projects
Commit 884b15f1 authored by Sara Savanovic Djordjevic's avatar Sara Savanovic Djordjevic
Browse files

add: read saved data on server connection failure

parent 0a1524ab
No related branches found
No related tags found
2 merge requests!5Clhp map,!4Clhp map
import 'dart:async'; import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'widgets/map_widget.dart'; import 'widgets/map_widget.dart';
import 'marker_handler/marker_data.dart'; import 'marker_handler/marker_data.dart';
import 'consts.dart'; import 'consts.dart';
import 'marker_handler/get_markers.dart'; import 'marker_handler/get_markers.dart';
import 'marker_handler/get_relation.dart'; import 'marker_handler/get_relation.dart';
import 'dart:typed_data'; import 'dart:typed_data';
import 'dart:io';
import 'dart:convert';
class DefaultPage extends StatefulWidget { class DefaultPage extends StatefulWidget {
const DefaultPage({Key? key}) : super(key: key); const DefaultPage({Key? key}) : super(key: key);
...@@ -17,6 +20,7 @@ class DefaultPage extends StatefulWidget { ...@@ -17,6 +20,7 @@ class DefaultPage extends StatefulWidget {
class _DefaultPageState extends State<DefaultPage> { class _DefaultPageState extends State<DefaultPage> {
late Timer _timer; late Timer _timer;
bool showBar = false; bool showBar = false;
bool serverConnection = true;
late Future<List<Measurement>> markerListFuture; late Future<List<Measurement>> markerListFuture;
late Future<Uint8List> relationFuture; late Future<Uint8List> relationFuture;
...@@ -24,8 +28,19 @@ class _DefaultPageState extends State<DefaultPage> { ...@@ -24,8 +28,19 @@ class _DefaultPageState extends State<DefaultPage> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
markerListFuture = fetchMarkerData(); markerListFuture = fetchMarkerData().then((fetchResult) {
relationFuture = fetchRelation(); List<Measurement> measurements = fetchResult.measurements;
serverConnection = fetchResult.connected;
// Return the measurements
return measurements;
}).catchError((error) {
throw Exception("Failed to fetch measurements: $error");
});
//relationFuture = fetchRelation();
relationFuture = Future.value(Uint8List(0));
// Schedule fetchMarkerData to run periodically based on fetchInterval from consts // Schedule fetchMarkerData to run periodically based on fetchInterval from consts
const Duration interval = Duration(minutes: fetchInterval); // NB fetchInterval value to be determined const Duration interval = Duration(minutes: fetchInterval); // NB fetchInterval value to be determined
...@@ -72,6 +87,9 @@ class _DefaultPageState extends State<DefaultPage> { ...@@ -72,6 +87,9 @@ class _DefaultPageState extends State<DefaultPage> {
} else if (snapshot.hasError) { } else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}')); return Center(child: Text('Error: ${snapshot.error}'));
} else { } else {
if (!serverConnection) {
print("Failed to connect to server");
}
// Display default page once all data is loaded from server // Display default page once all data is loaded from server
List<Measurement> markerList = snapshot.data![0] as List<Measurement>; List<Measurement> markerList = snapshot.data![0] as List<Measurement>;
Uint8List relation = snapshot.data![1] as Uint8List; Uint8List relation = snapshot.data![1] as Uint8List;
......
...@@ -5,9 +5,17 @@ import '../consts.dart'; ...@@ -5,9 +5,17 @@ import '../consts.dart';
import 'marker_data.dart'; import 'marker_data.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
class FetchResult {
final List<Measurement> measurements;
final bool connected;
FetchResult(this.measurements, this.connected);
}
// fetchMarkerTemplate requests all marker data from the server // fetchMarkerTemplate requests all marker data from the server
Future<List<Measurement>> fetchMarkerData() async { Future<FetchResult> fetchMarkerData() async {
try { try {
// Custom HTTP client // Custom HTTP client
HttpClient client = HttpClient() HttpClient client = HttpClient()
...@@ -41,17 +49,29 @@ Future<List<Measurement>> fetchMarkerData() async { ...@@ -41,17 +49,29 @@ Future<List<Measurement>> fetchMarkerData() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.setString('lastUpdate', '${DateTime.now()}'); await prefs.setString('lastUpdate', '${DateTime.now()}');
return jsonData.map((data) => Measurement.fromJson(data)).toList(); return FetchResult(jsonData.map((data) => Measurement.fromJson(data)).toList(), true);
} else {
throw Exception('Failed to parse marker data: Unexpected response format');
} }
} else {
throw Exception('Failed to parse marker data: Empty response body');
} }
} else {
throw Exception('Failed to fetch marker data: Status code ${response.statusCode}');
} }
return loadSavedData();
} catch (e) { } catch (e) {
throw Exception('Failed to fetch marker data: ${e.toString()}'); return loadSavedData();
}
}
Future<FetchResult> loadSavedData() async {
// Get latest saved data from file if the server does not respond
Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
String filePath = '${appDocumentsDirectory.path}/last_data.json';
// Read file contents
File file = File(filePath);
if (await file.exists()) {
String contents = await file.readAsString();
List<dynamic> jsonData = json.decode(contents); // Parse JSON string from file
List<Measurement> measurements = jsonData.map((data) => Measurement.fromJson(data)).toList();
return FetchResult(measurements, false);
} else {
throw Exception('File does not exist');
} }
} }
...@@ -38,7 +38,7 @@ class _ChoroplethMapState extends State<ChoroplethMap> { ...@@ -38,7 +38,7 @@ class _ChoroplethMapState extends State<ChoroplethMap> {
super.initState(); super.initState();
final Random random = Random(); final Random random = Random();
for (int i = 0; i <= 100; i++) { for (int i = 0; i <= 60; i++) {
int randomNumber = random.nextInt(21); // 0 -> 20 int randomNumber = random.nextInt(21); // 0 -> 20
iceThicknessList.add(IceThicknessModel(i.toString(), randomNumber)); iceThicknessList.add(IceThicknessModel(i.toString(), randomNumber));
} }
...@@ -67,24 +67,25 @@ class _ChoroplethMapState extends State<ChoroplethMap> { ...@@ -67,24 +67,25 @@ class _ChoroplethMapState extends State<ChoroplethMap> {
color: Color.fromRGBO(223,169,254, 1), color: Color.fromRGBO(223,169,254, 1),
text: '0-3'), text: '0-3'),
MapColorMapper( MapColorMapper(
from: 3, from: 4,
to: 8, to: 8,
color: Color.fromRGBO(190,78,253, 1), color: Color.fromRGBO(190,78,253, 1),
text: '3-8'), text: '4-8'),
MapColorMapper( MapColorMapper(
from: 8, from: 9,
to: 15, to: 15,
color: Color.fromRGBO(167,17,252, 1), color: Color.fromRGBO(167,17,252, 1),
text: '8-15'), text: '9-15'),
MapColorMapper( MapColorMapper(
from: 15, from: 16,
to: 20, to: 20,
color: Color.fromRGBO(170,20,250, 1), color: Color.fromRGBO(170,20,250, 1),
text: '15-20'), text: '16-20'),
], ],
), ),
color: Colors.lightBlueAccent, //color: Colors.lightBlueAccent,
zoomPanBehavior: _zoomPanBehavior, zoomPanBehavior: _zoomPanBehavior,
strokeColor: Colors.orange,
), ),
], ],
); );
......
...@@ -34,10 +34,10 @@ class StatCharts extends StatelessWidget { ...@@ -34,10 +34,10 @@ class StatCharts extends StatelessWidget {
], ],
), ),
), ),
const SizedBox(height: 20), // Add appropriate padding between charts const SizedBox(height: 20),
SizedBox( SizedBox(
width: MediaQuery.of(context).size.width * 0.8, // Adjust width as needed width: MediaQuery.of(context).size.width * 0.8,
height: 160, // Adjust height as needed height: 160,
child: BarChart( child: BarChart(
BarChartData( BarChartData(
alignment: BarChartAlignment.spaceAround, alignment: BarChartAlignment.spaceAround,
...@@ -77,19 +77,19 @@ class StatCharts extends StatelessWidget { ...@@ -77,19 +77,19 @@ class StatCharts extends StatelessWidget {
BarChartGroupData( BarChartGroupData(
x: 0, x: 0,
barRods: [ barRods: [
BarChartRodData(y: 15, width: 10), // Example width BarChartRodData(y: 15, width: 10),
], ],
), ),
BarChartGroupData( BarChartGroupData(
x: 1, x: 1,
barRods: [ barRods: [
BarChartRodData(y: 10, width: 10), // Example width BarChartRodData(y: 10, width: 10),
], ],
), ),
BarChartGroupData( BarChartGroupData(
x: 2, x: 2,
barRods: [ barRods: [
BarChartRodData(y: 18, width: 10), // Example width BarChartRodData(y: 18, width: 10),
], ],
), ),
], ],
......
No preview for this file type
import geopandas as gpd import geopandas as gpd
from shapely.geometry import Polygon from shapely.geometry import Polygon
def get_relation(self, body_of_water: str): def get_relation(self, body_of_water: str):
# Load GeoJSON data using geopandas # Load GeoJSON data using geopandas
geo_data = gpd.read_file("server/map/mjosa.geojson") geo_data = gpd.read_file("server/map/mjosa.geojson")
...@@ -33,7 +32,7 @@ def get_relation(self, body_of_water: str): ...@@ -33,7 +32,7 @@ def get_relation(self, body_of_water: str):
def divide_relation(polygons): def divide_relation(polygons):
# Define tile size # Define tile size
tile_size = 0.05 tile_size = 0.1
subdiv_id = 0 subdiv_id = 0
tiles = [] tiles = []
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment