Skip to content

Commit

Permalink
xDripCloud: add feature
Browse files Browse the repository at this point in the history
  • Loading branch information
jamorham committed Sep 15, 2024
1 parent 2b9f3a8 commit 49669b7
Show file tree
Hide file tree
Showing 20 changed files with 962 additions and 76 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -285,9 +285,9 @@ dependencies {
// implementation 'com.google.android.gms:play-services-maps:15.0.0'
implementation 'com.google.android.gms:play-services-wearable:15.0.0'
implementation 'com.google.android.gms:play-services-location:15.0.0'
implementation "com.google.android.gms:play-services-gcm:15.0.0"
implementation "androidx.work:work-runtime:2.9.1"
implementation "com.google.android.gms:play-services-oss-licenses:15.0.0"

implementation "com.google.protobuf:protobuf-java:4.27.2"
implementation 'com.squareup.wire:wire-runtime:2.2.0'
implementation 'com.squareup.okhttp:okhttp:2.7.5'
implementation 'com.squareup.okhttp3:okhttp:3.12.13'
Expand Down
Binary file added app/libs/xdrip-cloud-1.0-SNAPSHOT.jar
Binary file not shown.
10 changes: 2 additions & 8 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -637,14 +637,6 @@
android:enabled="true"
android:exported="true"></receiver>

<service
android:name=".TaskService"
android:exported="true"
android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
<intent-filter>
<action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
</intent-filter>
</service>
<service
android:name=".services.AlwaysOnDisplayService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
Expand Down Expand Up @@ -827,6 +819,8 @@
<meta-data
android:name="com.sec.android.multiwindow.MINIMUM_SIZE_H"
android:value="598.0dip" />
<meta-data android:name="delivery_metrics_exported_to_big_query_enabled"
android:value="false"/>

<activity android:name=".utilitymodels.XDripDreamSettingsActivity" />

Expand Down
6 changes: 4 additions & 2 deletions app/src/main/java/com/eveningoutpost/dexdrip/GcmActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,8 @@ private static void queueCheckOld(Context context, boolean recursive) {
Log.i(TAG, "Resending unacknowledged queue item: " + datum.bundle.getString("action") + datum.bundle.getString("payload"));
datum.resent++;
// GoogleCloudMessaging.getInstance(context).send(senderid + "@gcm.googleapis.com", Integer.toString(msgId.incrementAndGet()), datum.bundle);
JamCm.sendMessage(datum.bundle);
datum.bundle.putBoolean("resend-from-queue", true);
JamCm.sendMessageBackground(datum.bundle);
} catch (Exception e) {
Log.e(TAG, "Got exception during resend: " + e.toString());
}
Expand Down Expand Up @@ -778,7 +779,7 @@ private static synchronized String sendMessageNow(String identity, String action
if (last_ack == -1) last_ack = JoH.tsl();
last_send_previous = last_send;
last_send = JoH.tsl();
JamCm.sendMessage(data);
JamCm.sendMessageBackground(data);
msg = "Sent message OK " + messageid;
DesertSync.fromGCM(data);
} catch (Exception ex) {
Expand All @@ -800,6 +801,7 @@ private static boolean shouldAddQueue(final Bundle data) {
case "bfr":
case "nscu":
case "nscusensor-expiry":
case "nscus-expiry":
case "esup":
case "sencalup":
synchronized (queue_lock) {
Expand Down
35 changes: 27 additions & 8 deletions app/src/main/java/com/eveningoutpost/dexdrip/GcmListenerSvc.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@
import java.util.List;
import java.util.Map;

import static com.eveningoutpost.dexdrip.GcmActivity.cease_all_activity;
import static com.eveningoutpost.dexdrip.models.JoH.isAnyNetworkConnected;
import static com.eveningoutpost.dexdrip.models.JoH.showNotification;
import static com.eveningoutpost.dexdrip.models.JoH.tsl;

public class GcmListenerSvc extends JamListenerSvc {

Expand All @@ -66,7 +68,7 @@ public class GcmListenerSvc extends JamListenerSvc {
private static byte[] staticKey;

public static int lastMessageMinutesAgo() {
return (int) ((JoH.tsl() - GcmListenerSvc.lastMessageReceived) / 60000);
return (int) ((tsl() - GcmListenerSvc.lastMessageReceived) / 60000);
}

// data for MegaStatus
Expand Down Expand Up @@ -128,7 +130,7 @@ public void onMessageReceived(RemoteMessage rmessage) {
final PowerManager.WakeLock wl = JoH.getWakeLock("xdrip-onMsgRec", 120000);
try {
if (rmessage == null) return;
if (GcmActivity.cease_all_activity) return;
if (cease_all_activity) return;
String from = rmessage.getFrom();

final Bundle data = new Bundle();
Expand Down Expand Up @@ -250,7 +252,7 @@ public void onMessageReceived(RemoteMessage rmessage) {
}

Log.i(TAG, "Got action: " + action + " with payload: " + payload);
lastMessageReceived = JoH.tsl();
lastMessageReceived = tsl();


// new treatment
Expand Down Expand Up @@ -291,7 +293,7 @@ public void onMessageReceived(RemoteMessage rmessage) {
message_array[2] = Long.toString(Long.parseLong(message_array[2]) + timediff);
}
Log.i(TAG, "Processing remote CAL " + message_array[1] + " age: " + message_array[2]);
calintent.putExtra("timestamp", JoH.tsl());
calintent.putExtra("timestamp", tsl());
calintent.putExtra("bg_string", message_array[1]);
calintent.putExtra("bg_age", message_array[2]);
calintent.putExtra("cal_source", "gcm cal packet");
Expand All @@ -318,7 +320,7 @@ public void onMessageReceived(RemoteMessage rmessage) {
bg_age += timediff;
}
Log.i(TAG, "Processing remote CAL " + newCalibration.bgValue + " age: " + bg_age);
calintent.putExtra("timestamp", JoH.tsl());
calintent.putExtra("timestamp", tsl());
calintent.putExtra("bg_string", "" + (Pref.getString("units", "mgdl").equals("mgdl") ? newCalibration.bgValue : newCalibration.bgValue * Constants.MGDL_TO_MMOLL));
calintent.putExtra("bg_age", "" + bg_age);
calintent.putExtra("cal_source", "gcm cal2 packet");
Expand Down Expand Up @@ -434,7 +436,7 @@ public void onMessageReceived(RemoteMessage rmessage) {
if (ii.length > 1) sender_ssid = JoH.base64decode(ii[1]);
}
if (!Pref.getBooleanDefaultFalse("remote_snoozes_wifi_match") || JoH.getWifiFuzzyMatch(sender_ssid, JoH.getWifiSSID())) {
if (Math.abs(JoH.tsl() - snoozed_time) < 300000) {
if (Math.abs(tsl() - snoozed_time) < 300000) {
if (JoH.pratelimit("received-remote-snooze", 30)) {
AlertPlayer.getPlayer().Snooze(xdrip.getAppContext(), -1, false);
UserError.Log.ueh(TAG, "Accepted remote snooze");
Expand Down Expand Up @@ -508,7 +510,7 @@ public void run() {
} else {
Log.e(TAG, "Received sensorupdate packets but we are not set as a follower");
}
} else if (action.equals("sensor_calibrations_update")) {
} else if (action.equals("sencalup")) {
if (Home.get_master()) {
Log.i(TAG, "Received request for sensor calibration update");
GcmActivity.syncSensor(Sensor.currentSensor(), false);
Expand Down Expand Up @@ -563,7 +565,24 @@ public void run() {
} else if (action.equals("libreBlock") || action.equals("libreBlck")) {
HandleLibreBlock(payload);
} else {
Log.e(TAG, "Received message action we don't know about: " + action);
switch (action) {
case "cease0":
case "cease1":
case "cease2":
case "cease3":
case "cease4":
case "cease5":
case "cease6":
case "cease7":
case "cease8":
case "cease9":
cease_all_activity = true;
Log.wtf(TAG, "Server requested to cease all activity for reason: " + action);
break;
default:
Log.e(TAG, "Received message action we don't know about: " + action);
break;
}
}
} else {
// direct downstream message.
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/com/eveningoutpost/dexdrip/Home.java
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ protected void onCreate(Bundle savedInstanceState) {
}

nanoStatus = new NanoStatus("collector", 1000);
expiryStatus = new NanoStatus("sensor-expiry", 15000);
expiryStatus = new NanoStatus("s-expiry", 15000);

set_is_follower();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
* Created by jamorham on 11/01/16.
*/

import static com.eveningoutpost.dexdrip.GcmActivity.TASK_TAG_UNMETERED;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
Expand All @@ -13,22 +15,29 @@
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.WorkRequest;

import com.eveningoutpost.dexdrip.models.JoH;
import com.eveningoutpost.dexdrip.services.PlusSyncService;
import com.google.android.gms.gcm.GcmNetworkManager;
import com.google.android.gms.gcm.PeriodicTask;
import com.google.android.gms.gcm.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;

import org.json.JSONObject;

import lombok.val;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class RegistrationIntentService extends IntentService {
private static final String TAG = "jamorham regService";
private static final String[] PREDEF = {"global"};
private static final String[] PREDEF2 = {"global2"};

public RegistrationIntentService() {
super(TAG);
Expand All @@ -39,7 +48,7 @@ protected void onHandleIntent(Intent intent) {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
final PowerManager.WakeLock wl = JoH.getWakeLock("registration-intent", 120000);
try {
GcmActivity.senderid = getString(R.string.gcm_defaultSenderId);
// GcmActivity.senderid = getString(R.string.gcm_defaultSenderId);
String token = FirebaseInstanceId.getInstance().getToken();
try {
final JSONObject json = new JSONObject(token);
Expand All @@ -64,28 +73,41 @@ protected void onHandleIntent(Intent intent) {
}
}

private void sendRegistrationToServer(String token) {
private synchronized void sendRegistrationToServer(String token) {
try {
Log.d(TAG, "Scheduling tasks");
PeriodicTask task = new PeriodicTask.Builder()
.setService(TaskService.class)
.setTag(GcmActivity.TASK_TAG_UNMETERED)
.setRequiredNetwork(Task.NETWORK_STATE_UNMETERED)
.setPeriod(7200L)

val constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
//.setRequiresCharging(true)
.build();

GcmNetworkManager.getInstance(this).cancelAllTasks(TaskService.class);
GcmNetworkManager.getInstance(this).schedule(task);
val uploadWorkRequest =
new PeriodicWorkRequest.Builder(TaskService.class,12, TimeUnit.HOURS)
.addTag(TASK_TAG_UNMETERED)
.setConstraints(constraints)
.build();
val uploadWorkRequest2 =
new OneTimeWorkRequest.Builder(TaskService.class)
.addTag(TASK_TAG_UNMETERED)
.build();
WorkManager.getInstance(getApplicationContext()).cancelAllWorkByTag(TASK_TAG_UNMETERED);
WorkManager.getInstance(getApplicationContext()).enqueue(uploadWorkRequest2);
WorkManager.getInstance(getApplicationContext()).enqueue(uploadWorkRequest);

PlusSyncService.startSyncService(getApplicationContext(), "RegistrationToServer");
GcmActivity.queueCheckOld(getApplicationContext());
} catch (Exception e) {
Log.e(TAG, "Exception in sendRegistration: " + e.toString());
}
}

private void subscribeTpcs(String token) throws IOException {
private void subscribeTpcs(String token) {
FirebaseMessaging.getInstance().subscribeToTopic(GcmActivity.myIdentity());
for (String tpc : PREDEF) {
FirebaseMessaging.getInstance().unsubscribeFromTopic(tpc);
}
for (String tpc : PREDEF2) {
FirebaseMessaging.getInstance().subscribeToTopic(tpc);
}
}
Expand Down
55 changes: 20 additions & 35 deletions app/src/main/java/com/eveningoutpost/dexdrip/TaskService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,57 +4,42 @@
* Created by jamorham on 04/02/2016.
*/

import android.content.Intent;
import android.util.Log;
import static com.eveningoutpost.dexdrip.GcmActivity.token;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.eveningoutpost.dexdrip.cloud.jamcm.Legacy;
import com.eveningoutpost.dexdrip.models.JoH;
import com.eveningoutpost.dexdrip.utilitymodels.UpdateActivity;
import com.google.android.gms.gcm.GcmNetworkManager;
import com.google.android.gms.gcm.GcmTaskService;
import com.google.android.gms.gcm.TaskParams;


public class TaskService extends GcmTaskService {
public class TaskService extends Worker {

private static final String TAG = "jamorham TaskService";


@Override
public void onInitializeTasks() {
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}

@Override
public int onRunTask(TaskParams taskParams) {
Log.d(TAG, "onRunTask: " + taskParams.getTag());

String tag = taskParams.getTag();

// Default result is success.
int result = GcmNetworkManager.RESULT_SUCCESS;

// Choose method based on the tag.
if (GcmActivity.TASK_TAG_UNMETERED.equals(tag)) {
result = doUnmeteredTask();
} else if (GcmActivity.TASK_TAG_CHARGING.equals(tag)) {
result = doChargingTask();
}
// Return one of RESULT_SUCCESS, RESULT_FAILURE, or RESULT_RESCHEDULE
return result;
public TaskService(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}

private int doUnmeteredTask() {
if (GcmActivity.token != null) {
private boolean doUnmeteredTask() {
if (token != null) {
if (JoH.pratelimit("unmetered-update", 43200)) {
UpdateActivity.checkForAnUpdate(getApplicationContext());
}
Legacy.migration(token);
}
return GcmNetworkManager.RESULT_SUCCESS;
return true;
}

private int doChargingTask() {
return GcmNetworkManager.RESULT_SUCCESS;
@NonNull
@Override
public Result doWork() {
boolean result = doUnmeteredTask();
return result ? Result.success() : Result.failure();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,19 @@ public static String getId() {
/**
* @noinspection DataFlowIssue
*/
public static void sendMessage(Bundle input) {
public static void sendMessage(final Bundle input) {
if (Pusher.enabled()) {
Pusher.sendMessage(input);
} else {
sendMessagePrevious(input);
}
}

public static void sendMessageBackground(final Bundle input) {
new Thread(() -> sendMessage(input)).start();
}

public static void sendMessagePrevious(Bundle input) {

val ids = getId();
if (ids == null) {
Expand Down
Loading

0 comments on commit 49669b7

Please sign in to comment.