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

add: write most recenet get_relation time to file

parent 48f8158b
No related branches found
No related tags found
2 merge requests!5Clhp map,!4Clhp map
......@@ -3,7 +3,9 @@ import 'dart:convert';
import 'dart:io';
import '../consts.dart';
import 'dart:typed_data';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
/// Fetch relation data from server
Future<Uint8List> fetchRelation() async {
......@@ -17,11 +19,20 @@ Future<Uint8List> fetchRelation() async {
var request = await client.getUrl(Uri.parse('${serverURI}get_relation'));
var response = await request.close(); // Close response body at end of function
// Parse body to JSON if request is ok
// Try to parse body to JSON if request is ok
if (response.statusCode == 200) {
var responseBody = await response.transform(utf8.decoder).join();
if (responseBody.isNotEmpty) {
Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
String filePath = '${appDocumentsDirectory.path}/last_update.txt';
try { // Write most recent time of update to file
await File(filePath).writeAsString('${DateTime.now()}', mode: FileMode.write);
print('Update time written to file');
} catch (error) { print('Error in writing to file: $error');}
// Return relation data from the response body
return Uint8List.fromList(utf8.encode(responseBody));
} else {
throw Exception('Response body is empty');
......
......@@ -48,7 +48,7 @@ class _ChoroplethMapState extends State<ChoroplethMap> {
MapShapeLayer(
source: MapShapeSource.memory(
widget.relation,
shapeDataField: 'name',
shapeDataField: 'SubDivID',
),
color: Colors.orange,
zoomPanBehavior: _zoomPanBehavior,
......
......@@ -252,7 +252,7 @@ packages:
source: hosted
version: "0.2.1"
path_provider:
dependency: transitive
dependency: "direct main"
description:
name: path_provider
sha256: b27217933eeeba8ff24845c34003b003b2b22151de3c908d0e679e8fe1aa078b
......
......@@ -16,6 +16,7 @@ dependencies:
fl_chart: ^0.20.0-nullsafety1
google_fonts: any
syncfusion_flutter_maps: ^20.4.41
path_provider: ^2.0.8
dev_dependencies:
flutter_test:
......@@ -25,4 +26,4 @@ dev_dependencies:
flutter:
uses-material-design: true
assets:
- assets/icons/
- assets/
......@@ -11,6 +11,7 @@ import sqlite3
app = Flask(__name__)
terminate_server = 0
class IceHTTPServer(HTTPServer):
def __init__(self, server_address, handler_class, cursor):
super().__init__(server_address, handler_class)
......@@ -34,31 +35,21 @@ class IceHTTP(BaseHTTPRequestHandler):
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(b"Root path hit!")
self.wfile.write(b"The root path provides no functionality. Please use a valid endpoint")
elif self.path == '/update_map': # NB: should be POST?
get_all_markers(self.cursor, False, 'Mjosa') # Get all markers
get_all_markers(self, self.cursor, False, 'Mjosa') # Get all markers
# NB: temporary hardcoded waterBodyName
elif self.path == '/get_valid_markers': # NB: should be POST?
get_all_markers(self.cursor, True, 'Mjosa') # Get only valid markers
get_all_markers(self, self.cursor, True, 'Mjosa') # Get only valid markers
# NB: temporary hardcoded waterBodyName
elif self.path == '/get_relation':
get_relation(self, 'Mjosa') # NB temp hardcoded value
get_relation(self, 'Mjosa') # NB temp hardcoded value
def do_POST(self):
if self.path == '/get_weather_data':
get_weather(self)
# Terminate server on key press q
def on_key_press(server, event, cursor, conn):
if event.name == 'q':
print('Terminating server...')
server.server_close()
cursor.close()
conn.close()
keyboard.unhook_all()
quit()
# Start a server on port 8443 using self defined HTTP class
if __name__ == "__main__":
......@@ -77,11 +68,6 @@ if __name__ == "__main__":
print("Server running on port ", PORT)
# Register key press event handler
keyboard.on_press(lambda event: on_key_press(server, event, cursor, conn))
print("Server running on port ", PORT)
# Run server indefinitely
server.serve_forever()
......
No preview for this file type
No preview for this file type
......@@ -4,7 +4,7 @@ from math import pi, cos
# get_markers requests all marker data or valid markers, converts the data to json, and writes
# the data to the response object
def get_all_markers(cursor, valid: bool, waterBodyName):
def get_all_markers(self, cursor, valid: bool, waterBodyName):
try:
sql_query = '''
SELECT m.MeasurementID, m.SensorID, m.TimeMeasured, m.CenterLat, m.CenterLon,
......@@ -72,7 +72,7 @@ def get_all_markers(cursor, valid: bool, waterBodyName):
data = list(measurement_data.values())
if len(rows) == 0 or len(data) == 0: # Return 500 and empty list if no data is found
print(f"Error in querying database")
print(f"No data which meets the condition found")
marker_data = '[]'
else:
# Convert list of dictionaries to JSON
......@@ -82,7 +82,13 @@ def get_all_markers(cursor, valid: bool, waterBodyName):
print(f"Error in querying database: {e}")
marker_data = '[]'
return marker_data
# Set headers
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
# Write marker data to response object
self.wfile.write(marker_data.encode('utf-8'))
EARTH = 6378.137 # Radius of the earth in kilometer
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment