Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Implemented GEOFENCE_REFRESH on Android. Added Location request to ensure geofences get triggered

Michael Rademakerc8150a52a64a
diff --git a/console/android/src/main/java/org/openremote/android/MainActivity.java b/console/android/src/main/java/org/openremote/android/MainActivity.java
index 9158caf0c..6c95c8190 100644
--- a/console/android/src/main/java/org/openremote/android/MainActivity.java
+++ b/console/android/src/main/java/org/openremote/android/MainActivity.java
@@ -59,6 +59,8 @@ public class MainActivity extends Activity {
private final int WRITE_PERMISSION_REQUEST = 999;
+ public static final String ACTION_BROADCAST = "ACTION_BROADCAST";
+
protected final ConnectivityChangeReceiver connectivityChangeReceiver = new ConnectivityChangeReceiver();
protected WebView webView;
protected ErrorViewHolder errorViewHolder;
@@ -66,7 +68,7 @@ public class MainActivity extends Activity {
protected SharedPreferences sharedPreferences;
protected GeofenceProvider geofenceProvider;
- BroadcastReceiver onDownloadCompleteReciever = new BroadcastReceiver() {
+ protected BroadcastReceiver onDownloadCompleteReciever = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
@@ -75,6 +77,20 @@ public class MainActivity extends Activity {
}
};
+ protected BroadcastReceiver actionReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (intent.hasExtra("action")) {
+ String action = intent.getStringExtra("action");
+ switch (action) {
+ case "GEOFENCE_REFRESH":
+ geofenceProvider.refreshGeofences();
+ break;
+ }
+ }
+ }
+ };
+
protected class ErrorViewHolder {
View errorView;
Button btnReload;
@@ -181,6 +197,7 @@ public class MainActivity extends Activity {
super.onResume();
registerReceiver(connectivityChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
registerReceiver(onDownloadCompleteReciever, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
+ registerReceiver(actionReceiver, new IntentFilter(ACTION_BROADCAST));
}
@Override
@@ -188,6 +205,7 @@ public class MainActivity extends Activity {
super.onPause();
unregisterReceiver(connectivityChangeReceiver);
unregisterReceiver(onDownloadCompleteReciever);
+ unregisterReceiver(actionReceiver);
}
@Override
diff --git a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
index 63d7885d1..417d8affc 100644
--- a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
+++ b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
@@ -9,8 +9,10 @@ import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
+
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.firebase.messaging.RemoteMessage;
+
import org.openremote.android.service.AlertAction;
import org.openremote.android.service.AlertNotification;
import org.openremote.android.service.TokenService;
@@ -65,23 +67,29 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
if (remoteMessage.getNotification() != null) {
LOG.fine("Message contains notification body: " + remoteMessage.getNotification().getBody());
} else if (remoteMessage.getData() != null && !remoteMessage.getData().isEmpty()) {
- // Check if message contains a data payload with or-title or-body and actions
-
- LOG.fine("Message data payload: " + remoteMessage.getData());
- String title = remoteMessage.getData().get("or-title");
- String body = remoteMessage.getData().get("or-body");
- String actionsJson = remoteMessage.getData().get("actions");
- AlertAction[] actions = null;
-
- if (actionsJson != null && actionsJson.length() > 0) {
- try {
- actions = new ObjectMapper().readValue(actionsJson, AlertAction[].class);
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Failed to de-serialise alert actions", e);
+ if (remoteMessage.getData().containsKey("action")) {
+ String action = remoteMessage.getData().get("action");
+ Intent broadCastIntent = new Intent(MainActivity.ACTION_BROADCAST);
+ broadCastIntent.putExtra("action", action);
+ sendBroadcast(broadCastIntent);
+ } else {
+ // Check if message contains a data payload with or-title or-body and actions
+
+ LOG.fine("Message data payload: " + remoteMessage.getData());
+ String title = remoteMessage.getData().get("or-title");
+ String body = remoteMessage.getData().get("or-body");
+ String actionsJson = remoteMessage.getData().get("actions");
+ AlertAction[] actions = null;
+
+ if (actionsJson != null && actionsJson.length() > 0) {
+ try {
+ actions = new ObjectMapper().readValue(actionsJson, AlertAction[].class);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Failed to de-serialise alert actions", e);
+ }
}
+ handleNotification(title, body, actions);
}
-
- handleNotification(title, body, actions);
}
// tokenService.getAlerts(new Callback<List<AlertNotification>>() {
@@ -124,13 +132,13 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
int id = title.hashCode() + body.hashCode();
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
- .setContentTitle(title)
- .setStyle(new NotificationCompat.BigTextStyle().bigText(body))
- .setContentText(body)
- .setSmallIcon(R.drawable.notification_icon)
- .setWhen(0)
- .setPriority(Notification.PRIORITY_MAX)
- .setSound(defaultSoundUri);
+ .setContentTitle(title)
+ .setStyle(new NotificationCompat.BigTextStyle().bigText(body))
+ .setContentText(body)
+ .setSmallIcon(R.drawable.notification_icon)
+ .setWhen(0)
+ .setPriority(Notification.PRIORITY_MAX)
+ .setSound(defaultSoundUri);
for (AlertAction alertAction : actions) {
Intent actionIntent = new Intent(this, ORMessagingActionService.class);
@@ -139,18 +147,18 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
actionIntent.putExtra("action", alertAction);
actionIntent.setAction(Long.toString(System.currentTimeMillis()));
PendingIntent actionPendingIntent = PendingIntent.getService(this,
- 0,
- actionIntent,
- PendingIntent.FLAG_ONE_SHOT);
+ 0,
+ actionIntent,
+ PendingIntent.FLAG_ONE_SHOT);
notificationBuilder = notificationBuilder.addAction(new NotificationCompat.Action(R.drawable.empty,
- alertAction.getTitle(),
- actionPendingIntent));
+ alertAction.getTitle(),
+ actionPendingIntent));
}
LOG.fine("Showing notification (" + actions.length + " actions): " + body);
NotificationManager notificationManager =
- (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+ (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build());
}
@@ -161,21 +169,21 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
intent.putExtra("notification", alertNotification);
PendingIntent pendingIntent = PendingIntent.getService(this,
- notificationId,
- intent,
- PendingIntent.FLAG_ONE_SHOT);
+ notificationId,
+ intent,
+ PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
- .setContentTitle(alertNotification.getTitle())
- .setStyle(new NotificationCompat.BigTextStyle().bigText(alertNotification.getMessage()))
- .setContentText(alertNotification.getMessage())
- .setDeleteIntent(pendingIntent)
- .setSmallIcon(R.drawable.notification_icon)
- .setWhen(0)
- .setPriority(Notification.PRIORITY_MAX)
- .setSound(defaultSoundUri);
+ .setContentTitle(alertNotification.getTitle())
+ .setStyle(new NotificationCompat.BigTextStyle().bigText(alertNotification.getMessage()))
+ .setContentText(alertNotification.getMessage())
+ .setDeleteIntent(pendingIntent)
+ .setSmallIcon(R.drawable.notification_icon)
+ .setWhen(0)
+ .setPriority(Notification.PRIORITY_MAX)
+ .setSound(defaultSoundUri);
for (AlertAction alertAction : alertNotification.getActions()) {
Intent actionIntent = new Intent(this, ORMessagingActionService.class);
@@ -185,18 +193,18 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
actionIntent.putExtra("notification", alertNotification);
actionIntent.setAction(Long.toString(System.currentTimeMillis()));
PendingIntent actionPendingIntent = PendingIntent.getService(this,
- notificationId,
- actionIntent,
- PendingIntent.FLAG_ONE_SHOT);
+ notificationId,
+ actionIntent,
+ PendingIntent.FLAG_ONE_SHOT);
notificationBuilder = notificationBuilder.addAction(new NotificationCompat.Action(R.drawable.empty,
- alertAction.getTitle(),
- actionPendingIntent));
+ alertAction.getTitle(),
+ actionPendingIntent));
}
LOG.fine("Showing notification (" + alertNotification.getActions().size() + " actions): " + alertNotification.getMessage());
NotificationManager notificationManager =
- (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+ (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt b/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt
index 100482e8d..a80e20464 100644
--- a/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt
+++ b/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt
@@ -10,11 +10,9 @@ import android.content.Intent
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
+import android.util.Log
import com.fasterxml.jackson.databind.ObjectMapper
-import com.google.android.gms.location.Geofence
-import com.google.android.gms.location.GeofencingClient
-import com.google.android.gms.location.GeofencingRequest
-import com.google.android.gms.location.LocationServices
+import com.google.android.gms.location.*
import org.openremote.android.R
import java.io.*
import java.net.URL
@@ -38,17 +36,20 @@ class GeofenceProvider(val activity: Activity) {
lateinit var geofencingClient: GeofencingClient
private val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(activity, GeofenceTransitionsIntentService::class.java)
- intent.putExtra(baseUrlKey, baseURL)
+ intent.putExtra(consoleIdKey, consoleId)
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
// addGeofences() and removeGeofences().
PendingIntent.getService(activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
+ private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
+ private lateinit var locationCallback: LocationCallback
var baseURL: String? = null
var consoleId: String? = null
fun initialize(): Map<String, Any> {
+ fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(activity)
geofencingClient = LocationServices.getGeofencingClient(activity)
var inputStream: ObjectInputStream? = null
@@ -72,6 +73,7 @@ class GeofenceProvider(val activity: Activity) {
)
}
+ @SuppressLint("MissingPermission")
fun enable(baseUrl: String, consoleId: String): Map<String, Any> {
baseURL = baseUrl
this.consoleId = consoleId
@@ -81,6 +83,23 @@ class GeofenceProvider(val activity: Activity) {
.putString(consoleIdKey, this.consoleId)
.apply()
+ //Force location updates
+ val locationRequest = LocationRequest().apply {
+ interval = 60000//1min
+ fastestInterval = 10000//10sec
+ priority = LocationRequest.PRIORITY_HIGH_ACCURACY
+ }
+
+ locationCallback = object : LocationCallback() {
+ override fun onLocationResult(locationResult: LocationResult?) {
+ locationResult ?: return
+ Log.i("GeofenceProvider", "Location received: $locationResult")
+ }
+ }
+
+ fusedLocationProviderClient.requestLocationUpdates(locationRequest,
+ locationCallback,
+ null)
fetchGeofences()
@@ -99,6 +118,7 @@ class GeofenceProvider(val activity: Activity) {
.apply()
baseURL = null
consoleId = null
+ fusedLocationProviderClient.removeLocationUpdates(locationCallback)
clearAllRegions()
}
@@ -152,7 +172,9 @@ class GeofenceProvider(val activity: Activity) {
}
fun refreshGeofences() {
- fetchGeofences()
+ Thread({
+ fetchGeofences()
+ }).start()
}
protected fun fetchGeofences() {
diff --git a/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt b/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt
index b04543d44..de781e644 100644
--- a/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt
+++ b/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt
@@ -2,16 +2,32 @@ package org.openremote.android.service
import android.app.IntentService
import android.content.Intent
+import android.util.Log
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingEvent
-import java.net.HttpURLConnection
-import java.net.URL
+import org.openremote.android.R
+import retrofit2.Retrofit
+import retrofit2.converter.jackson.JacksonConverterFactory
+import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.logging.Logger
class GeofenceTransitionsIntentService : IntentService("or-geofence") {
private val LOG = Logger.getLogger(GeofenceTransitionsIntentService::class.java.name)
+ private val restApiResource: RestApiResource by lazy {
+ Retrofit.Builder()
+ .baseUrl(applicationContext.getString(R.string.OR_BASE_SERVER))
+ .addConverterFactory(ScalarsConverterFactory.create())
+ .addConverterFactory(JacksonConverterFactory.create())
+ .build().create(RestApiResource::class.java);
+ }
+
+ override fun onCreate() {
+ super.onCreate()
+
+
+ }
override fun onHandleIntent(intent: Intent?) {
@@ -24,41 +40,31 @@ class GeofenceTransitionsIntentService : IntentService("or-geofence") {
LOG.fine("Geofence '" + geofencingEvent.geofenceTransition + "' occurred")
- val baseUrl = intent!!.getStringExtra(GeofenceProvider.baseUrlKey)
+ val consoleId = intent!!.getStringExtra(GeofenceProvider.consoleIdKey)
val geofenceTransition = geofencingEvent.geofenceTransition
- val geofence = geofencingEvent.triggeringGeofences.first()
- val postUrl = GeofenceProvider.geoPostUrls[geofence.requestId]
-
- val url = URL("$baseUrl$postUrl")
- val connection = url.openConnection() as HttpURLConnection
- connection.setRequestProperty("Content-Type", "application/json")
- connection.requestMethod = "POST"
- connection.connectTimeout = 10000
- connection.doInput = false
-
- if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
-
- val postJson = hashMapOf(
- "objectValue" to hashMapOf(
- "type" to "Point",
- "coordinates" to arrayOf(geofencingEvent.triggeringLocation.longitude, geofencingEvent.triggeringLocation.latitude)
- )
- )
- connection.doOutput = true
- connection.setChunkedStreamingMode(0)
- connection.outputStream
- ObjectMapper().writeValue(connection.outputStream, postJson)
+ val postJson = when (geofenceTransition) {
+ Geofence.GEOFENCE_TRANSITION_ENTER -> {
+ hashMapOf(
+ "type" to "Point",
+ "coordinates" to arrayOf(geofencingEvent.triggeringLocation.longitude, geofencingEvent.triggeringLocation.latitude)
+ )
+ }
+ else -> {
+ hashMapOf(
+ "type" to "Point",
+ "coordinates" to arrayOf(0, 0)
+ )
+ }
}
try {
- connection.outputStream.flush()
- val responseCode = connection.responseCode
- LOG.fine("Location posted to server '" + postUrl + "': response=" + responseCode);
+ val response = restApiResource
+ .updateAssetAction(application.getString(R.string.OR_REALM), null, consoleId, "location", ObjectMapper().writeValueAsString(postJson))
+ .execute()
+ LOG.fine("Location posted to server: response=" + response.code());
} catch (exception: Exception) {
- print(exception)
- } finally {
- connection.disconnect()
+ Log.e("Geofence", exception.message, exception)
}
}
}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/service/RestApiResource.java b/console/android/src/main/java/org/openremote/android/service/RestApiResource.java
index 63a401702..c917f461e 100644
--- a/console/android/src/main/java/org/openremote/android/service/RestApiResource.java
+++ b/console/android/src/main/java/org/openremote/android/service/RestApiResource.java
@@ -22,7 +22,4 @@ public interface RestApiResource {
@PUT("/{realm}/asset/{assetId}/attribute/{attributeName}")
@Headers("Content-Type:application/json")
Call<Void> updateAssetAction(@Path("realm") String realm, @Header("Authorization") String accessToken,@Path("assetId") String assetId,@Path("attributeName") String attributeName,@Body String rawJson);
-
- @POST("{realm}/asset/public/{assetId}/updateLocation")
- Call<Void> updatePublicAssetLocation(@Path("realm") String realm, String assetId, @Body JSONObject json);
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
index 08371a45d..8b10e209e 100644
--- a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
@@ -57,6 +57,7 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
private static final Logger LOG = Logger.getLogger(ORConsoleGeofenceAssetAdapter.class.getName());
public static final String NAME = "ORConsole";
+ //TODO not needed anymore? We use writeAttributeValue now
public static final String LOCATION_URL_FORMAT_TEMPLATE = "/asset/%1$s/location";
protected Map<String, RulesEngine.AssetStateLocationPredicates> assetLocationPredicatesMap = new HashMap<>();
protected NotificationService notificationService;