This repository has been archived on 2023-11-18. You can view files and clone it, but cannot push or open issues or pull requests.
ha_client/lib/managers/location_manager.class.dart

200 lines
7.1 KiB
Dart
Raw Normal View History

part of '../main.dart';
class LocationManager {
2019-10-20 20:54:29 +03:00
static final LocationManager _instance = LocationManager
._internal();
factory LocationManager() {
return _instance;
}
LocationManager._internal() {
init();
}
2019-10-21 21:22:25 +03:00
final int defaultUpdateIntervalMinutes = 20;
final String backgroundTaskId = "haclocationtask4352";
final String backgroundTaskTag = "haclocation";
2019-10-20 20:54:29 +03:00
Duration _updateInterval;
bool _isEnabled;
void init() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.reload();
_updateInterval = Duration(minutes: prefs.getInt("location-interval") ??
defaultUpdateIntervalMinutes);
_isEnabled = prefs.getBool("location-enabled") ?? false;
if (_isEnabled) {
_startLocationService();
}
}
void setSettings(bool enabled, int interval) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (interval != _updateInterval.inMinutes) {
prefs.setInt("location-interval", interval);
_updateInterval = Duration(minutes: interval);
}
if (enabled && !_isEnabled) {
Logger.d("Enabling location service");
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("location-enabled", enabled);
_isEnabled = true;
_startLocationService();
} else if (!enabled && _isEnabled) {
Logger.d("Disabling location service");
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("location-enabled", enabled);
_isEnabled = false;
_stopLocationService();
}
}
void _startLocationService() async {
Logger.d("Scheduling location update for every ${_updateInterval
.inMinutes} minutes...");
2019-10-21 21:22:25 +03:00
String webhookId = ConnectionManager().webhookId;
String httpWebHost = ConnectionManager().httpWebHost;
if (webhookId != null && webhookId.isNotEmpty) {
await workManager.Workmanager.registerPeriodicTask(
backgroundTaskId,
"haClientLocationTracking",
tag: backgroundTaskTag,
inputData: {
"webhookId": webhookId,
"httpWebHost": httpWebHost
},
frequency: _updateInterval,
2019-10-22 21:42:30 +03:00
existingWorkPolicy: workManager.ExistingWorkPolicy.keep,
2019-10-21 21:22:25 +03:00
backoffPolicy: workManager.BackoffPolicy.linear,
2019-10-22 21:42:30 +03:00
backoffPolicyDelay: _updateInterval,
2019-10-21 21:22:25 +03:00
constraints: workManager.Constraints(
networkType: workManager.NetworkType.connected
)
);
}
2019-10-20 20:54:29 +03:00
}
void _stopLocationService() async {
Logger.d("Canceling previous schedule if any...");
2019-10-21 21:22:25 +03:00
await workManager.Workmanager.cancelByTag(backgroundTaskTag);
2019-10-20 20:54:29 +03:00
}
void updateDeviceLocation() async {
2019-10-21 21:22:25 +03:00
if (ConnectionManager().webhookId != null &&
2019-10-20 20:54:29 +03:00
ConnectionManager().webhookId.isNotEmpty) {
String url = "${ConnectionManager()
.httpWebHost}/api/webhook/${ConnectionManager().webhookId}";
Map<String, String> headers = {};
Logger.d("[Location] Getting device location...");
Position location = await Geolocator().getCurrentPosition(
desiredAccuracy: LocationAccuracy.medium);
Logger.d("[Location] Got location: ${location.latitude} ${location
.longitude}. Sending home...");
int battery = DateTime
.now()
.hour;
var data = {
"type": "update_location",
"data": {
"gps": [location.latitude, location.longitude],
"gps_accuracy": location.accuracy,
"battery": battery
}
};
headers["Content-Type"] = "application/json";
await http.post(
url,
headers: headers,
body: json.encode(data)
);
Logger.d("[Location] ...done.");
}
}
}
void updateDeviceLocationIsolate() {
2019-10-21 21:22:25 +03:00
workManager.Workmanager.executeTask((backgroundTask, data) {
2019-10-22 21:42:30 +03:00
print("[Background $backgroundTask] Started");
2019-10-20 20:54:29 +03:00
2019-10-21 21:22:25 +03:00
String webhookId = data["webhookId"];
String httpWebHost = data["httpWebHost"];
if (webhookId != null && webhookId.isNotEmpty) {
2019-10-22 21:42:30 +03:00
int battery = DateTime.now().hour;
print("[Background $backgroundTask] hour=$battery");
String url = "$httpWebHost/api/webhook/$webhookId";
Map<String, String> headers = {};
headers["Content-Type"] = "application/json";
print("[Background $backgroundTask] Getting device location...");
2019-10-20 20:54:29 +03:00
Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.medium).then((location) {
2019-10-22 21:42:30 +03:00
print("[Background $backgroundTask] Got location: ${location.latitude} ${location.longitude}");
print("[Background $backgroundTask] sending data home...");
2019-10-20 20:54:29 +03:00
var data = {
"type": "update_location",
"data": {
"gps": [location.latitude, location.longitude],
"gps_accuracy": location.accuracy,
"battery": battery
}
};
http.post(
url,
headers: headers,
body: json.encode(data)
).catchError((e) {
2019-10-22 21:42:30 +03:00
print("[Background $backgroundTask] Error sending data: ${e.toString()}");
2019-10-20 20:54:29 +03:00
}).then((_) {
2019-10-22 21:42:30 +03:00
print("[Background $backgroundTask] Success!");
2019-10-20 20:54:29 +03:00
});
2019-10-21 21:22:25 +03:00
}).catchError((e) {
2019-10-22 21:42:30 +03:00
print("[Background $backgroundTask] Error getting current location: ${e.toString()}. Trying last known...");
Geolocator().getLastKnownPosition(desiredAccuracy: LocationAccuracy.medium).then((location){
print("[Background $backgroundTask] Got last known location: ${location.latitude} ${location.longitude}");
print("[Background $backgroundTask] sending data home...");
var data = {
"type": "update_location",
"data": {
"gps": [location.latitude, location.longitude],
"gps_accuracy": location.accuracy,
"battery": battery
}
};
http.post(
url,
headers: headers,
body: json.encode(data)
).catchError((e) {
print("[Background $backgroundTask] Error sending data: ${e.toString()}");
}).then((_) {
print("[Background $backgroundTask] Success!");
});
}).catchError((e){
print("[Background $backgroundTask] Error getting last known location: ${e.toString()}. Sending fake...");
print("[Background $backgroundTask] sending data home...");
var data = {
"type": "update_location",
"data": {
"gps": [40.34, 30.34],
"gps_accuracy": 300,
"battery": battery
}
};
http.post(
url,
headers: headers,
body: json.encode(data)
).catchError((e) {
print("[Background $backgroundTask] Error sending data: ${e.toString()}");
}).then((_) {
print("[Background $backgroundTask] Success!");
});
});
2019-10-20 20:54:29 +03:00
});
2019-10-21 21:22:25 +03:00
} else {
2019-10-22 21:42:30 +03:00
print("[Background $backgroundTask] No webhook id. Aborting");
2019-10-21 21:22:25 +03:00
}
2019-10-20 20:54:29 +03:00
return Future.value(true);
});
}