From 884b15f1ce1b36f6970464dc904f70237b53d9e7 Mon Sep 17 00:00:00 2001
From: Sara <sarasdj@stud.ntnu.no>
Date: Thu, 7 Mar 2024 13:50:27 +0100
Subject: [PATCH] add: read saved data on server connection failure

---
 app/lib/pages/default_page.dart               |  22 +++++++++-
 app/lib/pages/marker_handler/get_markers.dart |  38 +++++++++++++-----
 app/lib/pages/widgets/cloropleth_map.dart     |  17 ++++----
 app/lib/pages/widgets/stat_charts.dart        |  12 +++---
 .../__pycache__/get_relation.cpython-311.pyc  | Bin 3040 -> 3040 bytes
 server/map/get_relation.py                    |   3 +-
 6 files changed, 65 insertions(+), 27 deletions(-)

diff --git a/app/lib/pages/default_page.dart b/app/lib/pages/default_page.dart
index 8a73f557..0879ac6a 100644
--- a/app/lib/pages/default_page.dart
+++ b/app/lib/pages/default_page.dart
@@ -1,11 +1,14 @@
 import 'dart:async';
 import 'package:flutter/material.dart';
+import 'package:path_provider/path_provider.dart';
 import 'widgets/map_widget.dart';
 import 'marker_handler/marker_data.dart';
 import 'consts.dart';
 import 'marker_handler/get_markers.dart';
 import 'marker_handler/get_relation.dart';
 import 'dart:typed_data';
+import 'dart:io';
+import 'dart:convert';
 
 class DefaultPage extends StatefulWidget {
   const DefaultPage({Key? key}) : super(key: key);
@@ -17,6 +20,7 @@ class DefaultPage extends StatefulWidget {
 class _DefaultPageState extends State<DefaultPage> {
   late Timer _timer;
   bool showBar = false;
+  bool serverConnection = true;
 
   late Future<List<Measurement>> markerListFuture;
   late Future<Uint8List> relationFuture;
@@ -24,8 +28,19 @@ class _DefaultPageState extends State<DefaultPage> {
   @override
   void initState() {
     super.initState();
-    markerListFuture = fetchMarkerData();
-    relationFuture = fetchRelation();
+    markerListFuture = fetchMarkerData().then((fetchResult) {
+      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
     const Duration interval = Duration(minutes: fetchInterval); // NB fetchInterval value to be determined
@@ -72,6 +87,9 @@ class _DefaultPageState extends State<DefaultPage> {
             } else if (snapshot.hasError) {
               return Center(child: Text('Error: ${snapshot.error}'));
             } else {
+              if (!serverConnection) {
+                print("Failed to connect to server");
+              }
               // Display default page once all data is loaded from server
               List<Measurement> markerList = snapshot.data![0] as List<Measurement>;
               Uint8List relation = snapshot.data![1] as Uint8List;
diff --git a/app/lib/pages/marker_handler/get_markers.dart b/app/lib/pages/marker_handler/get_markers.dart
index f649a9a9..89db2d36 100644
--- a/app/lib/pages/marker_handler/get_markers.dart
+++ b/app/lib/pages/marker_handler/get_markers.dart
@@ -5,9 +5,17 @@ import '../consts.dart';
 import 'marker_data.dart';
 import 'package:path_provider/path_provider.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
-Future<List<Measurement>> fetchMarkerData() async {
+Future<FetchResult> fetchMarkerData() async {
   try {
     // Custom HTTP client
     HttpClient client = HttpClient()
@@ -41,17 +49,29 @@ Future<List<Measurement>> fetchMarkerData() async {
           final prefs = await SharedPreferences.getInstance();
           await prefs.setString('lastUpdate', '${DateTime.now()}');
 
-          return jsonData.map((data) => Measurement.fromJson(data)).toList();
-        } else {
-          throw Exception('Failed to parse marker data: Unexpected response format');
+          return FetchResult(jsonData.map((data) => Measurement.fromJson(data)).toList(), true);
         }
-      } 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) {
-    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');
   }
 }
diff --git a/app/lib/pages/widgets/cloropleth_map.dart b/app/lib/pages/widgets/cloropleth_map.dart
index 068f9e79..65804c00 100644
--- a/app/lib/pages/widgets/cloropleth_map.dart
+++ b/app/lib/pages/widgets/cloropleth_map.dart
@@ -38,7 +38,7 @@ class _ChoroplethMapState extends State<ChoroplethMap> {
     super.initState();
 
     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
       iceThicknessList.add(IceThicknessModel(i.toString(), randomNumber));
     }
@@ -67,24 +67,25 @@ class _ChoroplethMapState extends State<ChoroplethMap> {
                     color: Color.fromRGBO(223,169,254, 1),
                     text: '0-3'),
                 MapColorMapper(
-                    from: 3,
+                    from: 4,
                     to: 8,
                     color: Color.fromRGBO(190,78,253, 1),
-                    text: '3-8'),
+                    text: '4-8'),
                 MapColorMapper(
-                    from: 8,
+                    from: 9,
                     to: 15,
                     color: Color.fromRGBO(167,17,252, 1),
-                    text: '8-15'),
+                    text: '9-15'),
                 MapColorMapper(
-                    from: 15,
+                    from: 16,
                     to: 20,
                     color: Color.fromRGBO(170,20,250, 1),
-                    text: '15-20'),
+                    text: '16-20'),
               ],
             ),
-            color: Colors.lightBlueAccent,
+            //color: Colors.lightBlueAccent,
             zoomPanBehavior: _zoomPanBehavior,
+            strokeColor: Colors.orange,
           ),
         ],
     );
diff --git a/app/lib/pages/widgets/stat_charts.dart b/app/lib/pages/widgets/stat_charts.dart
index da6039af..86d511e6 100644
--- a/app/lib/pages/widgets/stat_charts.dart
+++ b/app/lib/pages/widgets/stat_charts.dart
@@ -34,10 +34,10 @@ class StatCharts extends StatelessWidget {
             ],
           ),
         ),
-        const SizedBox(height: 20), // Add appropriate padding between charts
+        const SizedBox(height: 20),
         SizedBox(
-          width: MediaQuery.of(context).size.width * 0.8, // Adjust width as needed
-          height: 160, // Adjust height as needed
+          width: MediaQuery.of(context).size.width * 0.8,
+          height: 160,
           child: BarChart(
             BarChartData(
               alignment: BarChartAlignment.spaceAround,
@@ -77,19 +77,19 @@ class StatCharts extends StatelessWidget {
                 BarChartGroupData(
                   x: 0,
                   barRods: [
-                    BarChartRodData(y: 15, width: 10), // Example width
+                    BarChartRodData(y: 15, width: 10),
                   ],
                 ),
                 BarChartGroupData(
                   x: 1,
                   barRods: [
-                    BarChartRodData(y: 10, width: 10), // Example width
+                    BarChartRodData(y: 10, width: 10),
                   ],
                 ),
                 BarChartGroupData(
                   x: 2,
                   barRods: [
-                    BarChartRodData(y: 18, width: 10), // Example width
+                    BarChartRodData(y: 18, width: 10),
                   ],
                 ),
               ],
diff --git a/server/map/__pycache__/get_relation.cpython-311.pyc b/server/map/__pycache__/get_relation.cpython-311.pyc
index fbf72ef0cb5cb3bcab0c487f7b27ce8a2c27086a..da501c6267762271e0dd9c0b31c4f6279b5267e2 100644
GIT binary patch
delta 36
qcmaDL{y>~}IWI340}#w!{4!N<Bd;F^<Ic@796F4Q!kare!<hid2MR?1

delta 36
qcmaDL{y>~}IWI340}!xGf0?Skk=KudapmS14jo2Dk<Fc);Y<Lzw+WO0

diff --git a/server/map/get_relation.py b/server/map/get_relation.py
index 0f4a251b..b277b8d5 100644
--- a/server/map/get_relation.py
+++ b/server/map/get_relation.py
@@ -1,7 +1,6 @@
 import geopandas as gpd
 from shapely.geometry import Polygon
 
-
 def get_relation(self, body_of_water: str):
     # Load GeoJSON data using geopandas
     geo_data = gpd.read_file("server/map/mjosa.geojson")
@@ -33,7 +32,7 @@ def get_relation(self, body_of_water: str):
 
 def divide_relation(polygons):
     # Define tile size
-    tile_size = 0.05
+    tile_size = 0.1
     subdiv_id = 0
     tiles = []
 
-- 
GitLab