Newer
Older
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'datamodel.dart';
import 'databaseconnector.dart';
import 'dart:async';
import 'package:geolocator/geolocator.dart';
class AddEventKottasPegel extends StatefulWidget {
const AddEventKottasPegel({Key? key}) : super(key: key);
@override
State<AddEventKottasPegel> createState() => _AddEventKottasPegelPageState();
}
class _AddEventKottasPegelPageState extends State<AddEventKottasPegel> {
List<String> measurementStatusItems = ['ok', 'broken', 'missing' 'tilted',];
int measurementStatusId = -1;
List<String> angleStatusItems = ['90° (vertical)', '80°', '70°', '60°', '50°', '40°', '30°', ];
List<double> measurementOffsets = [0, 1000.0, 2000.0, 3000.0]; //Colors no, green, red, blue
//Parameters which shall be added to the measurement event as json string data
String angleStatus = '';
double lengthOld = 0.0;
double lengthNew = 0.0;
bool syncGNSSData = true;
bool _addButtonEnabled = true;
bool displayAngle = true;
bool displayOldLength = true;
bool displayNewLength = true;
late String long = "";
late String lat = "";
late String alt = "";
late double accuracy = 0.0;
late StreamSubscription<Position> streamHandler; //For canceling GNSS stream on dispose
late Timer restQueryTimer;
final prefs = SharedPreferences.getInstance(); // Is async
var database = DatabaseInstance();
late OverlayEntry _overlayEntry; //For event creation success notifications
late Timer _overlayCloseTimer;
Future startRest() async {
final ConfigurationStoreInstance configuration = ConfigurationStoreInstance();
final EventStoreInstance event = EventStoreInstance();
/* Function which starts querying the URL configuration.restRequestUrl */
restQueryTimer = Timer.periodic(const Duration(seconds: 1), (timer) async {
// Query data from raspberry pi here
try{
Map data = await restConnector.fetchData(configuration.restRequestUrl);
debugPrint("Rest Query succeeded: $data");
event.currentEvent.latitude = data['lat'];
event.currentEvent.longitude = data['lon'];
event.currentEvent.startDate = data['timestamp'];
rawMeasurementValue = data['length']; //in mm //accept only int values
accuracy = double.parse(data['precision'].toString()); //accept int and double and string values
}catch(e){
debugPrint("Rest Query failed $e");
}
});
}
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
Future startGNSS() async {
final EventStoreInstance eventStore = EventStoreInstance();
debugPrint("Check Location Permission");
bool serviceStatus = false;
bool hasPermission = false;
serviceStatus = await Geolocator.isLocationServiceEnabled();
if(serviceStatus){
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
debugPrint('Location permissions are denied');
}else if(permission == LocationPermission.deniedForever){
debugPrint('Location permissions are permanently denied');
}else{
hasPermission = true;
}
}else{
hasPermission = true;
}
if(hasPermission){
debugPrint('Location permissions granted');
if(mounted){
setState(() {
//refresh the UI
});}
debugPrint('Starting location stream');
streamHandler = Geolocator.getPositionStream(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 0,
)).listen((Position position) {
debugPrint('Get Location: Lat:${position.latitude} Long:${position.longitude} Alt:${position.altitude}');
long = position.longitude.toString();
lat = position.latitude.toString();
alt = position.altitude.toString();
accuracy = position.accuracy;
if (eventStore.gnssSync == true) {
if(mounted){
setState(() {
//refresh UI on update
});}
}
});
}
}else{
debugPrint("GPS Service is not enabled, turn on GPS location");
}
if(mounted){
setState(() {
//refresh the UI
});}
}
@override
void initState() {
final EventStoreInstance event = EventStoreInstance();
final ConfigurationStoreInstance configuration = ConfigurationStoreInstance();
//TODO: start async 1s rest poll to get length and position value from raspberries rest url
startRest(); //To query data from raspberry Pi measurement
//Update current event with prefix and cnt
event.currentEvent.label = configuration.labelConfig.prefix + configuration.labelConfig.cnt.toString();
//Set the device URN for the event fixed here! TODO: create device in sensor, add to a collection!
//event.currentEvent.urn TODO: set the urn here!
//event.currentEvent.urnId
super.initState();
}
@override
void dispose() async {
try {
streamHandler.cancel();
debugPrint('Cancel location stream');
}catch(e){
debugPrint('Canceling location stream failed');
}
try {
_overlayEntry.remove();
}catch(e){
debugPrint('Dispose error on overlay remove: $e');
try{
restQueryTimer.cancel();
}catch(e){
debugPrint('Timer cancel error on dispose: $e');
}
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*Async update current event configuration to shared preferences*/
final EventStoreInstance event = EventStoreInstance();
event.storeToSharedPrefs();
super.dispose();
}
bool _validateLatitude(value){
if (value == ""){
return true; //Empty string is valid
}
var number = num.tryParse(value);
if(number != null){
if (number >= -90.0 && number <= 90.0){
return true; // Latitude valid
}
}
return false;
}
bool _validateLongitude(value){
if (value == ""){
return true; //Empty string is valid
}
var number = num.tryParse(value);
if(number != null){
if (number >= -180.0 && number <= 180.0){
return true; // Longitude valid
}
}
return false;
}
bool _validateElevation(value){
if (value == ""){
return true; //Empty string is valid
}
var number = num.tryParse(value);
if(number != null){
return true; // Any numerical value is valid for elevation
}
return false;
}
bool _validateInput(){
final EventStoreInstance event = EventStoreInstance();
if (RegExp(r'^[a-z A-Z . \- 0-9 , ( ) + - _ :]+$').hasMatch(
event.currentEvent.label)) {
if (RegExp(r'^[a-z A-Z . \- 0-9 , ( ) + - _ :]+$').hasMatch(
event.currentEvent.description) || event.currentEvent.description == '') {
if(_validateLatitude(event.currentEvent.latitude)){
if(_validateLongitude(event.currentEvent.longitude)){
if(_validateElevation(event.currentEvent.elevation)){
return true;
}
}
}
}
}
return false;
}
bool _addButtonStatus(){
if((_validateInput() == true) && (_addButtonEnabled == true)){
return true;
}
return false;
}
Future<void> _showResultPopup(BuildContext context, String text, bool error) async {
OverlayState? overlayState = Overlay.of(context);
try {
_overlayEntry.remove(); // Allow only one Overlay Popup at a time
}catch(e){
debugPrint('Overlay already removed, during dispose: $e');
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
}
_overlayEntry = OverlayEntry(builder: (context) {
Color backGroundColor;
Color textColor;
if (error == true){
backGroundColor = Colors.redAccent; //Style for error message
textColor = Colors.black;
}
else {
backGroundColor = Colors.greenAccent; //Style for notification
textColor = Colors.black;
}
return Stack(
alignment: Alignment.center,
children: [
Positioned(
// Position at 10% of height from bottom
bottom: MediaQuery.of(context).size.height * 0.1,
child: Material(
borderRadius: BorderRadius.circular(8.0),
color: backGroundColor, //Some transparency remains
child: Container(
padding: const EdgeInsets.all(5.0), // Space between Text and Bubble
width: MediaQuery.of(context).size.width * 0.95,
child: TextFormField(
minLines: 1,
maxLines: 5,
readOnly: true,
autofocus: false,
enabled: false,
style: TextStyle(color: textColor),
controller: TextEditingController(
text: text,
),
),
),
),
),
],
);
});
overlayState?.insert(_overlayEntry);
try {
_overlayCloseTimer.cancel(); // Kill old timers
}catch(e){
debugPrint('Timer cancel error: $e');
}
_overlayCloseTimer = Timer(
const Duration(seconds: 3),
() {
try {
_overlayEntry.remove(); // Allow only one Overlay Popup. NOTE: Is this a quick an dirty or a proper solution?
}catch(e){
debugPrint('Overlay already removed, during dispose: $e');
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
}
},
);
}
Future<void> _storeCurrentEvent(BuildContext context) async {
final EventStoreInstance event = EventStoreInstance();
final ConfigurationStoreInstance configuration = ConfigurationStoreInstance();
event.currentEvent.typeId = configuration.getEventIdFromName(event.currentEvent.type);
event.currentEvent.status = "PENDING";
await database.addEvent(event.currentEvent);
HapticFeedback.vibrate(); //Feedback that adding event succeeded
_addButtonEnabled = true; //Activate button for add more events
setState(() {});
//_showAddSuccessOverlay(context); //Show pop up to indicated adding event succeeded.
_showResultPopup(context, "Successfully created Event !", false );
//Update timestamp in UI
var date = DateTime.now().toUtc();
var isoDate = date.toIso8601String();
event.currentEvent.startDate = isoDate;
event.currentEvent.endDate = isoDate;
}
@override
Widget build(BuildContext context) {
/* Get singletons to access relevant data here.*/
final EventStoreInstance eventStore = EventStoreInstance();
final ConfigurationStoreInstance configuration = ConfigurationStoreInstance();
String gnssStatusText = "";
String gnssStatusTextLine2 = "";
if (true == eventStore.gnssSync){
var date = DateTime.now().toUtc();
var isoDate = date.toIso8601String();
eventStore.currentEvent.startDate = isoDate;
eventStore.currentEvent.endDate = isoDate;
if(accuracy == 0.0){
gnssStatusTextLine2 = "No-Fix";
}
else{
gnssStatusTextLine2 = "Precision ${accuracy.toStringAsFixed(1)}m";
// Update current event coordinates from external Rest data
eventStore.currentEvent.latitude = lat;
eventStore.currentEvent.longitude = long;
eventStore.currentEvent.elevation = alt;
gnssStatusText = "REST Off"; // Use Smartphone internal GNSS data
gnssStatusTextLine2 = "Precision ${accuracy.toStringAsFixed(1)}m";
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Set visibility parameters
measurementStatusItems = ['ok', 'broken', 'missing' 'tilted',];
displayAngle = false;
displayOldLength = false;
displayNewLength = false;
if(measurementStatusId == 0){
//ok
displayAngle = true;
displayOldLength = true;
}else if (measurementStatusId == 1){
//broken
displayNewLength = true;
}else if (measurementStatusId == 2){
//missing
displayNewLength = true;
}else {
//tilted / to short
displayAngle = true;
displayOldLength = true;
displayNewLength = true;
}
if (configuration.initialized == true) {
return Scaffold(
appBar: AppBar(
title: const Text("Kottaspegel"),
actions: <Widget>[
Column(
children: [
Text(gnssStatusText, style: const TextStyle(fontStyle: FontStyle.italic)),
Text(gnssStatusTextLine2, style: const TextStyle(fontStyle: FontStyle.italic)),
],
),
Switch( //Enable showing all or only pending events. Default is to show only pending events
value: eventStore.gnssSync,
onChanged: (value) {
eventStore.gnssSync = value;
debugPrint('Switched to:${eventStore.gnssSync}');
setState(() {
//refresh the UI
});
}),
],
)
,
body: SingleChildScrollView(
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 5.0),
child:
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
const SizedBox(height: 10.0),
TextFormField(
readOnly: false,
keyboardType: TextInputType.number,
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: TextEditingController(
text: ""
"${eventStore.currentEvent.startDate.substring(11,19)} / "
"${double.parse(eventStore.currentEvent.latitude).toStringAsFixed(7)} / "
"${double.parse(eventStore.currentEvent.longitude).toStringAsFixed(7)} / "
"${double.parse(eventStore.currentEvent.elevation).toStringAsFixed(2)}"
labelText: 'UTC / Lat / Long / Elv / Voltage ', //Example
border: OutlineInputBorder(),
),
),
const SizedBox(height: 15.0),
TextFormField(
readOnly: false,
enabled: false,
style: const TextStyle(fontSize: 30.0),
keyboardType: TextInputType.number,
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: TextEditingController(
text: "Length: ${rawMeasurementValue.toString()} [mm]"
),
border: OutlineInputBorder(),
),
),
const SizedBox(height: 15.0),
TextFormField(
autovalidateMode: AutovalidateMode.always,
decoration: const InputDecoration(
setState(() {});
},
validator: (value) {
if (!RegExp(r'^[a-z A-Z . \- 0-9 , ( ) + - _ :]+$').hasMatch(
value!)) {
return "Only: a-z , A-Z , _ , 0-9 , ,(Comma) , ( , ) , + , - , . , :";
} else {
return null; // Entered Text is valid
}
},
),
const SizedBox(height: 15.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: measurementStatusId == 0 ? Colors.blue : Colors.grey,
measurementStatusId = 0;
setState(() {});
},
child: const Text('Ok'),
),
const SizedBox(width: 5),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: measurementStatusId == 1 ? Colors.blue : Colors.grey,
measurementStatusId = 1;
setState(() {});
},
child: const Text('broken'),
),
const SizedBox(width: 5),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: measurementStatusId == 2 ? Colors.blue : Colors.grey,
measurementStatusId = 2;
setState(() {});
},
child: const Text('?'),
),
const SizedBox(width: 5),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: measurementStatusId == 3 ? Colors.blue : Colors.grey,
measurementStatusId = 3;
setState(() {});
},
child: const Text('tilted'),
),
]
),
const SizedBox(height: 15.0),
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
Visibility(
visible: displayAngle,
child:
DropdownButtonFormField(
iconDisabledColor: Colors.green,
value: angleStatusItems[0],
isExpanded: true,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Angle',
),
items:
angleStatusItems.map((String angle) {
return DropdownMenuItem(
value: angle,
//enabled: displayAngle,
child: Text(angle),
);
}).toList(),
onChanged: (value) {
//TODO: update chosen angle value
//eventStore.currentEvent.type = value.toString();
}
),
),
const SizedBox(height: 15.0),
Visibility(
visible: displayOldLength,
child:
TextFormField(
readOnly: false,
enabled: !eventStore.gnssSync,
keyboardType: TextInputType.number,
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: TextEditingController(
text: lengthOld.toString(),
),
labelText: 'old length', //Example
border: OutlineInputBorder(),
),
onChanged: (value) {
lengthOld = double.parse(value);
},
onFieldSubmitted: (value){
if (!eventStore.gnssSync) {
setState(() {});
}
},
validator: (value) {
if (value == "") {
return null; // Empty value is allowed
}
final number = num.tryParse(value!);
if (number != null){
return null; // Elevation valid
}
return "Only numerical values [mm]";
},
),
),
const SizedBox(height: 5.0),
Visibility(
visible: displayOldLength,
child:
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: eventStore.gnssSync == true ? Colors.grey : Colors.grey,
),
onPressed: () {
lengthOld = rawMeasurementValue + measurementOffsets[0];
setState(() {});
},
child: const Text('+0m'),
const SizedBox(width: 5),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: eventStore.gnssSync == true ? Colors.green : Colors.grey,
),
onPressed: () {
lengthOld = rawMeasurementValue + measurementOffsets[1];
setState(() {});
},
child: const Text('+1m'),
const SizedBox(width: 5),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: eventStore.gnssSync == true ? Colors.red : Colors.grey,
),
onPressed: () {
lengthOld = rawMeasurementValue + measurementOffsets[2];
setState(() {});
},
child: const Text('+2m'),
const SizedBox(width: 5),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: eventStore.gnssSync == true ? Colors.blue : Colors.grey,
),
onPressed: () {
lengthOld = rawMeasurementValue + measurementOffsets[3];
setState(() {});
},
child: const Text('+3m'),
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
Visibility(
visible: displayNewLength,
child:
TextFormField(
readOnly: false,
enabled: !eventStore.gnssSync,
keyboardType: TextInputType.number,
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: TextEditingController(
text: lengthNew.toString()
),
decoration: const InputDecoration(
labelText: 'new length', //Example
border: OutlineInputBorder(),
),
onChanged: (value) {
lengthNew = double.parse(value);
},
onFieldSubmitted: (value){
if (!eventStore.gnssSync) {
setState(() {});
}
},
validator: (value) {
if (value == "") {
return null; // Empty value is allowed
}
final number = num.tryParse(value!);
if (number != null){
return null; // Elevation valid
}
return "Only numerical values for elevation in [m]";
},
),
),
const SizedBox(height: 5.0),
Visibility(
visible: displayNewLength,
child:
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: eventStore.gnssSync == true ? Colors.grey : Colors.grey,
),
onPressed: () {
lengthNew = rawMeasurementValue + measurementOffsets[0];
setState(() {});
},
child: const Text('+0m'),
const SizedBox(width: 5),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: eventStore.gnssSync == true ? Colors.green : Colors.grey,
),
onPressed: () {
lengthNew = rawMeasurementValue + measurementOffsets[1];
setState(() {});
},
child: const Text('+1m'),
const SizedBox(width: 5),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: eventStore.gnssSync == true ? Colors.red : Colors.grey,
),
onPressed: () {
lengthNew = rawMeasurementValue + measurementOffsets[2];
setState(() {});
},
child: const Text('+2m'),
const SizedBox(width: 5),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 20.0), //TODO: find a more dynamic solution without a fixed value
primary: eventStore.gnssSync == true ? Colors.blue : Colors.grey,
),
onPressed: () {
lengthNew = rawMeasurementValue + measurementOffsets[3];
setState(() {});
},
child: const Text('+3m'),
const SizedBox(height: 15.0),
TextFormField(
initialValue: eventStore.currentEvent.description,
autovalidateMode: AutovalidateMode.always,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Description'
),
onChanged: (value){
eventStore.currentEvent.description = value;
setState(() {});
},
validator: (value) {
if (!RegExp(r'^[a-z A-Z . \- 0-9 , ( ) + - _ :]+$').hasMatch(
value!)) {
if(value == ''){
return null; //An empty description is also allowed.
}
return "Only: a-z , A-Z , _ , 0-9 , ,(Comma) , ( , ) , + , - , . , :";
} else {
return null; // Entered Text is valid
}
},
),
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
]
),
),
),
bottomNavigationBar:
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: _addButtonStatus() ?
FloatingActionButton.extended(
heroTag: null,
tooltip: 'Create new event in local database',
icon: null,
label: const Text('Create Event'),
onPressed: () {
if (_validateInput()) {
_addButtonEnabled = false; //Disable button until event is stored
_storeCurrentEvent(context);
}
setState(() {});
},
):
FloatingActionButton.extended(
heroTag: null,
tooltip: 'Input invalid',
icon: null,
backgroundColor: Colors.grey,
label: const Text('Create Event'),
onPressed: () {
},
),
),
const SizedBox(width: 5.0),
],
),
);
}else {
return Scaffold(
appBar: AppBar(title: const Text("Add Event")),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Container(
margin: const EdgeInsets.all(10.0),
child:const Text(
'Check Configuration Page for initial setup!',
style: TextStyle(fontSize: 20)
),
),
],
),
);
}
}
}
//TODO: The app shall prefill the label with a configurable prefix and optionally a running number. E.g. prefix: (PS122.3-4_) running number: 1 label = PS122.3-4_1