use of com.eveningoutpost.dexdrip.Models.TransmitterData in project xDrip-plus by jamorham.
the class ListenerService method getWearTransmitterData.
private synchronized DataMap getWearTransmitterData(int count, long last_send_time, int min_count) {
// KS
forceGoogleApiConnect();
Log.d(TAG, "getWearTransmitterData last_send_time:" + JoH.dateTimeText(last_send_time));
TransmitterData last_bg = TransmitterData.last();
if (last_bg != null) {
Log.d(TAG, "getWearTransmitterData last_bg.timestamp:" + JoH.dateTimeText(last_bg.timestamp));
}
if (last_bg != null && last_send_time <= last_bg.timestamp) {
// startTime
long last_send_success = last_send_time;
Log.d(TAG, "getWearTransmitterData last_send_time < last_bg.timestamp:" + JoH.dateTimeText(last_bg.timestamp));
List<TransmitterData> graph_bgs = TransmitterData.latestForGraphAsc(count, last_send_time);
if (!graph_bgs.isEmpty() && graph_bgs.size() > min_count) {
// Log.d(TAG, "getWearTransmitterData count = " + graph_bgs.size());
DataMap entries = dataMap(last_bg);
final ArrayList<DataMap> dataMaps = new ArrayList<>(graph_bgs.size());
for (TransmitterData bg : graph_bgs) {
dataMaps.add(dataMap(bg));
last_send_success = bg.timestamp;
// Log.d(TAG, "getWearTransmitterData bg getId:" + bg.getId() + " raw_data:" + bg.raw_data + " filtered_data:" + bg.filtered_data + " timestamp:" + bg.timestamp + " uuid:" + bg.uuid);
}
// MOST IMPORTANT LINE FOR TIMESTAMP
entries.putLong("time", new Date().getTime());
entries.putDataMapArrayList("entries", dataMaps);
Log.i(TAG, "getWearTransmitterData SYNCED BGs up to " + JoH.dateTimeText(last_send_success) + " count = " + graph_bgs.size());
return entries;
} else
Log.i(TAG, "getWearTransmitterData SYNCED BGs up to " + JoH.dateTimeText(last_send_success) + " count = 0");
}
return null;
}
use of com.eveningoutpost.dexdrip.Models.TransmitterData in project xDrip-plus by jamorham.
the class Ob1G5StateMachine method processNewTransmitterData.
// Save/process the data in xDrip style
private static synchronized void processNewTransmitterData(int raw_data, int filtered_data, int sensor_battery_level, long captureTime) {
final TransmitterData transmitterData = TransmitterData.create(raw_data, filtered_data, sensor_battery_level, captureTime);
if (transmitterData == null) {
UserError.Log.e(TAG, "TransmitterData.create failed: Duplicate packet");
return;
} else {
UserError.Log.d(TAG, "Created transmitter data " + transmitterData.uuid + " " + JoH.dateTimeText(transmitterData.timestamp));
// TODO timeInMillisecondsOfLastSuccessfulSensorRead = captureTime;
}
Sensor sensor = Sensor.currentSensor();
if (sensor == null) {
UserError.Log.e(TAG, "setSerialDataToTransmitterRawData: No Active Sensor, Data only stored in Transmitter Data");
return;
}
// TODO : LOG if unfiltered or filtered values are zero
Sensor.updateBatteryLevel(sensor, transmitterData.sensor_battery_level);
if (d)
UserError.Log.i(TAG, "timestamp create: " + Long.toString(transmitterData.timestamp));
BgReading bgreading = BgReading.create(transmitterData.raw_data, transmitterData.filtered_data, xdrip.getAppContext(), transmitterData.timestamp);
// KS
UserError.Log.d(TAG, "Dex raw_data " + Double.toString(transmitterData.raw_data));
// KS
UserError.Log.d(TAG, "Dex filtered_data " + Double.toString(transmitterData.filtered_data));
// KS
UserError.Log.d(TAG, "Dex sensor_battery_level " + Double.toString(transmitterData.sensor_battery_level));
// KS
UserError.Log.d(TAG, "Dex timestamp " + JoH.dateTimeText(transmitterData.timestamp));
UserError.Log.d(TAG, "BgReading created: " + bgreading.uuid + " " + JoH.dateTimeText(bgreading.timestamp));
// TODO static_last_timestamp = transmitterData.timestamp;
}
use of com.eveningoutpost.dexdrip.Models.TransmitterData in project xDrip-plus by jamorham.
the class WixelReader method readData.
private void readData() {
Long LastReportedTime = 0L;
TransmitterData lastTransmitterData = TransmitterData.last();
if (lastTransmitterData != null) {
LastReportedTime = lastTransmitterData.timestamp;
// jamorham fix to avoid going twice to network when we just got a packet
if ((new Date().getTime() - LastReportedTime) < DEXCOM_PERIOD - 2000) {
Log.d(TAG, "Already have a recent packet - returning");
if (JoH.ratelimit("deferred-msg", 60)) {
statusLog(" Deferred", "Already have recent reading");
}
return;
} else {
statusLog(" Deferred", "");
}
}
Long startReadTime = LastReportedTime;
TransmitterRawData LastReportedReading = null;
Log.d(TAG, "Starting... LastReportedReading " + LastReportedReading);
// try to read one object...
TransmitterRawData[] LastReadingArr = null;
String recieversIpAddresses;
if (!WixelReader.IsConfigured()) {
return;
}
if ((DexCollectionType.getDexCollectionType() == DexCollectionType.Mock) && Home.get_engineering_mode()) {
recieversIpAddresses = "fake://FAKE_DATA";
} else {
recieversIpAddresses = Pref.getString("wifi_recievers_addresses", "");
}
// How many packets should we read? we look at the maximum time between last calibration and last reading time
// and calculate how much are needed.
final Calibration lastCalibration = Calibration.lastValid();
if (lastCalibration != null) {
startReadTime = Math.max(startReadTime, lastCalibration.timestamp);
}
Long gapTime = new Date().getTime() - startReadTime + 120000;
int packetsToRead = (int) (gapTime / (5 * 60000));
// don't read too much, but always read 1.
packetsToRead = Math.min(packetsToRead, 200);
packetsToRead = Math.max(packetsToRead, 1);
Log.d(TAG, "reading " + packetsToRead + " packets");
LastReadingArr = Read(recieversIpAddresses, packetsToRead);
if (LastReadingArr == null || LastReadingArr.length == 0) {
return;
}
for (TransmitterRawData LastReading : LastReadingArr) {
// Make sure we do not report packets from the far future...
if ((LastReading.CaptureDateTime > LastReportedTime + 120000) && (!almostEquals(LastReading, LastReportedReading)) && LastReading.CaptureDateTime < new Date().getTime() + 120000) {
// We have a real new reading...
Log.d(TAG, "calling setSerialDataToTransmitterRawData " + LastReading.RawValue + " LastReading.CaptureDateTime " + LastReading.CaptureDateTime + " " + LastReading.TransmissionId);
setSerialDataToTransmitterRawData(LastReading.RawValue, LastReading.FilteredValue, LastReading.BatteryLife, LastReading.CaptureDateTime);
LastReportedReading = LastReading;
LastReportedTime = LastReading.CaptureDateTime;
if (LastReading.UploaderBatteryLife > 0) {
Pref.setInt("parakeet_battery", LastReading.UploaderBatteryLife);
CheckBridgeBattery.checkParakeetBattery();
if (Home.get_master()) {
GcmActivity.sendParakeetBattery(LastReading.UploaderBatteryLife);
}
}
}
}
}
use of com.eveningoutpost.dexdrip.Models.TransmitterData in project xDrip-plus by jamorham.
the class GcmListenerSvc method onMessageReceived.
@Override
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;
String from = rmessage.getFrom();
final Bundle data = new Bundle();
for (Map.Entry<String, String> entry : rmessage.getData().entrySet()) {
data.putString(entry.getKey(), entry.getValue());
}
if (from == null)
from = "null";
String message = data.getString("message");
Log.d(TAG, "From: " + from);
if (message != null) {
Log.d(TAG, "Message: " + message);
} else {
message = "null";
}
final Bundle notification = data.getBundle("notification");
if (notification != null) {
Log.d(TAG, "Processing notification bundle");
try {
sendNotification(notification.getString("body"), notification.getString("title"));
} catch (NullPointerException e) {
Log.d(TAG, "Null pointer exception within sendnotification");
}
}
if (from.startsWith(getString(R.string.gcmtpc))) {
String xfrom = data.getString("xfrom");
String payload = data.getString("datum");
String action = data.getString("action");
if ((xfrom != null) && (xfrom.equals(GcmActivity.token))) {
GcmActivity.queueAction(action + payload);
return;
}
String[] tpca = from.split("/");
if ((tpca[2] != null) && (tpca[2].length() > 30) && (!tpca[2].equals(GcmActivity.myIdentity()))) {
Log.e(TAG, "Received invalid channel: " + from + " instead of: " + GcmActivity.myIdentity());
if ((GcmActivity.myIdentity() != null) && (GcmActivity.myIdentity().length() > 30)) {
try {
FirebaseMessaging.getInstance().unsubscribeFromTopic(tpca[2]);
} catch (Exception e) {
Log.e(TAG, "Exception unsubscribing: " + e.toString());
}
}
return;
}
byte[] bpayload = null;
if (payload == null)
payload = "";
if (action == null)
action = "null";
if (payload.length() > 16) {
if (GoogleDriveInterface.keyInitialized()) {
// handle binary message types
switch(action) {
case "btmm":
case "bgmm":
bpayload = CipherUtils.decryptStringToBytes(payload);
if (JoH.checkChecksum(bpayload)) {
bpayload = Arrays.copyOfRange(bpayload, 0, bpayload.length - 4);
Log.d(TAG, "Binary payload received: length: " + bpayload.length + " orig: " + payload.length());
} else {
Log.e(TAG, "Invalid binary payload received, possible key mismatch: ");
bpayload = null;
}
payload = "binary";
break;
default:
if (action.equals("sensorupdate")) {
try {
Log.i(TAG, "payload for sensorupdate " + payload);
byte[] inbytes = Base64.decode(payload, Base64.NO_WRAP);
byte[] inbytes1 = JoH.decompressBytesToBytes(CipherUtils.decryptBytes(inbytes));
payload = new String(inbytes1, "UTF-8");
Log.d(TAG, "inbytes size = " + inbytes.length + " inbytes1 size " + inbytes1.length + "payload len " + payload.length());
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Got unsupported encoding on UTF8 " + e.toString());
payload = "";
}
} else {
String decrypted_payload = CipherUtils.decryptString(payload);
if (decrypted_payload.length() > 0) {
payload = decrypted_payload;
} else {
Log.e(TAG, "Couldn't decrypt payload!");
payload = "";
Home.toaststaticnext("Having problems decrypting incoming data - check keys");
}
}
}
} else {
Log.e(TAG, "Couldn't decrypt as key not initialized");
payload = "";
}
} else {
if (payload.length() > 0)
UserError.Log.wtf(TAG, "Got short payload: " + payload + " on action: " + action);
}
Log.i(TAG, "Got action: " + action + " with payload: " + payload);
lastMessageReceived = JoH.tsl();
// new treatment
if (action.equals("nt")) {
Log.i(TAG, "Attempting GCM push to Treatment");
if (Home.get_master_or_follower() && Home.follower_or_accept_follower())
GcmActivity.pushTreatmentFromPayloadString(payload);
} else if (action.equals("dat")) {
Log.i(TAG, "Attempting GCM delete all treatments");
if (Home.get_master_or_follower() && Home.follower_or_accept_follower())
Treatments.delete_all();
} else if (action.equals("dt")) {
Log.i(TAG, "Attempting GCM delete specific treatment");
if (Home.get_master_or_follower() && Home.follower_or_accept_follower())
Treatments.delete_by_uuid(filter(payload));
} else if (action.equals("clc")) {
Log.i(TAG, "Attempting to clear last calibration");
if (Home.get_master_or_follower() && Home.follower_or_accept_follower()) {
if (payload.length() > 0) {
Calibration.clearCalibrationByUUID(payload);
} else {
Calibration.clearLastCalibration();
}
}
} else if (action.equals("cal")) {
if (Home.get_master_or_follower() && Home.follower_or_accept_follower()) {
String[] message_array = filter(payload).split("\\s+");
if ((message_array.length == 3) && (message_array[0].length() > 0) && (message_array[1].length() > 0) && (message_array[2].length() > 0)) {
// [0]=timestamp [1]=bg_String [2]=bgAge
Intent calintent = new Intent();
calintent.setClassName(getString(R.string.local_target_package), "com.eveningoutpost.dexdrip.AddCalibration");
calintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
long timediff = (long) ((new Date().getTime() - Double.parseDouble(message_array[0])) / 1000);
Log.i(TAG, "Remote calibration latency calculated as: " + Long.toString(timediff) + " seconds");
if (timediff > 0) {
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("bg_string", message_array[1]);
calintent.putExtra("bg_age", message_array[2]);
if (timediff < 3600) {
getApplicationContext().startActivity(calintent);
}
} else {
Log.e(TAG, "Invalid CAL payload");
}
}
} else if (action.equals("cal2")) {
Log.i(TAG, "Received cal2 packet");
if (Home.get_master() && Home.follower_or_accept_follower()) {
final NewCalibration newCalibration = GcmActivity.getNewCalibration(payload);
if (newCalibration != null) {
final Intent calintent = new Intent();
calintent.setClassName(getString(R.string.local_target_package), "com.eveningoutpost.dexdrip.AddCalibration");
calintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
long timediff = (long) ((new Date().getTime() - newCalibration.timestamp) / 1000);
Log.i(TAG, "Remote calibration latency calculated as: " + timediff + " seconds");
Long bg_age = newCalibration.offset;
if (timediff > 0) {
bg_age += timediff;
}
Log.i(TAG, "Processing remote CAL " + newCalibration.bgValue + " age: " + bg_age);
calintent.putExtra("bg_string", "" + (Pref.getString("units", "mgdl").equals("mgdl") ? newCalibration.bgValue : newCalibration.bgValue * Constants.MGDL_TO_MMOLL));
calintent.putExtra("bg_age", "" + bg_age);
if (timediff < 3600) {
getApplicationContext().startActivity(calintent);
} else {
Log.w(TAG, "warninig ignoring calibration because timediff is " + timediff);
}
}
} else {
Log.e(TAG, "Received cal2 packet packet but we are not a master, so ignoring it");
}
} else if (action.equals("ping")) {
if (payload.length() > 0) {
RollCall.Seen(payload);
}
// don't respond to wakeup pings
} else if (action.equals("rlcl")) {
if (Home.get_master_or_follower()) {
if (payload.length() > 0) {
RollCall.Seen(payload);
}
GcmActivity.requestPing();
}
} else if (action.equals("p")) {
GcmActivity.send_ping_reply();
} else if (action.equals("q")) {
Home.toaststatic("Received ping reply");
} else if (action.equals("plu")) {
// process map update
if (Home.get_follower()) {
MapsActivity.newMapLocation(payload, (long) JoH.ts());
}
} else if (action.equals("sbu")) {
if (Home.get_follower()) {
Log.i(TAG, "Received sensor battery level update");
Sensor.updateBatteryLevel(Integer.parseInt(payload), true);
TransmitterData.updateTransmitterBatteryFromSync(Integer.parseInt(payload));
}
} else if (action.equals("bbu")) {
if (Home.get_follower()) {
Log.i(TAG, "Received bridge battery level update");
Pref.setInt("bridge_battery", Integer.parseInt(payload));
CheckBridgeBattery.checkBridgeBattery();
}
} else if (action.equals("pbu")) {
if (Home.get_follower()) {
Log.i(TAG, "Received parakeet battery level update");
Pref.setInt("parakeet_battery", Integer.parseInt(payload));
CheckBridgeBattery.checkParakeetBattery();
}
} else if (action.equals("psu")) {
if (Home.get_follower()) {
Log.i(TAG, "Received pump status update");
PumpStatus.fromJson(payload);
}
} else if (action.equals("not")) {
if (Home.get_follower()) {
try {
final int GCM_NOTIFICATION_ITEM = 543;
final String[] payloadA = payload.split("\\^");
final String title = payloadA[0];
final String body = payloadA[1];
final PendingIntent pendingIntent = android.app.PendingIntent.getActivity(xdrip.getAppContext(), 0, new Intent(xdrip.getAppContext(), Home.class), android.app.PendingIntent.FLAG_UPDATE_CURRENT);
showNotification(title, body, pendingIntent, GCM_NOTIFICATION_ITEM, true, true, false);
} catch (Exception e) {
UserError.Log.e(TAG, "Error showing follower notification with payload: " + payload);
}
}
} else if (action.equals("sbr")) {
if ((Home.get_master()) && JoH.ratelimit("gcm-sbr", 300)) {
Log.i(TAG, "Received sensor battery request");
if (Sensor.currentSensor() != null) {
try {
TransmitterData td = TransmitterData.last();
if ((td != null) && (td.sensor_battery_level != 0)) {
GcmActivity.sendSensorBattery(td.sensor_battery_level);
} else {
GcmActivity.sendSensorBattery(Sensor.currentSensor().latest_battery_level);
}
} catch (NullPointerException e) {
Log.e(TAG, "Cannot send sensor battery as sensor is null");
}
} else {
Log.d(TAG, "No active sensor so not sending anything.");
}
}
} else if (action.equals("amu")) {
if ((Pref.getBoolean("motion_tracking_enabled", false)) && (Pref.getBoolean("use_remote_motion", false))) {
if (!Pref.getBoolean("act_as_motion_master", false)) {
ActivityRecognizedService.spoofActivityRecogniser(getApplicationContext(), payload);
} else {
Home.toaststaticnext("Receiving motion updates from a different master! Make only one the master!");
}
}
} else if (action.equals("sra")) {
if ((Home.get_follower() || Home.get_master())) {
if (Pref.getBooleanDefaultFalse("accept_remote_snoozes")) {
try {
long snoozed_time = 0;
String sender_ssid = "";
try {
snoozed_time = Long.parseLong(payload);
} catch (NumberFormatException e) {
String[] ii = payload.split("\\^");
snoozed_time = Long.parseLong(ii[0]);
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 (JoH.pratelimit("received-remote-snooze", 30)) {
AlertPlayer.getPlayer().Snooze(xdrip.getAppContext(), -1, false);
UserError.Log.ueh(TAG, "Accepted remote snooze");
JoH.static_toast_long("Received remote snooze!");
} else {
Log.e(TAG, "Rate limited remote snooze");
}
} else {
UserError.Log.uel(TAG, "Ignoring snooze as outside 5 minute window, sync lag or clock difference");
}
} else {
UserError.Log.uel(TAG, "Ignoring snooze as wifi network names do not match closely enough");
}
} catch (Exception e) {
UserError.Log.e(TAG, "Exception processing remote snooze: " + e);
}
} else {
UserError.Log.uel(TAG, "Rejecting remote snooze");
}
}
} else if (action.equals("bgs")) {
Log.i(TAG, "Received BG packet(s)");
if (Home.get_follower()) {
String[] bgs = payload.split("\\^");
for (String bgr : bgs) {
BgReading.bgReadingInsertFromJson(bgr);
}
if (Pref.getBooleanDefaultFalse("follower_chime") && JoH.pratelimit("bgs-notify", 1200)) {
JoH.showNotification("New glucose data @" + JoH.hourMinuteString(), "Follower Chime: will alert whenever it has been more than 20 minutes since last", null, 60311, true, true, true);
}
} else {
Log.e(TAG, "Received remote BG packet but we are not set as a follower");
}
// Home.staticRefreshBGCharts();
} else if (action.equals("bfb")) {
final String[] bfb = payload.split("\\^");
if (Pref.getString("dex_collection_method", "").equals("Follower")) {
Log.i(TAG, "Processing backfill location packet as we are a follower");
staticKey = CipherUtils.hexToBytes(bfb[1]);
final Handler mainHandler = new Handler(getMainLooper());
final Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
new WebAppHelper(new GcmListenerSvc.ServiceCallback()).executeOnExecutor(xdrip.executor, getString(R.string.wserviceurl) + "/joh-getsw/" + bfb[0]);
} catch (Exception e) {
Log.e(TAG, "Exception processing run on ui thread: " + e);
}
}
};
mainHandler.post(myRunnable);
} else {
Log.i(TAG, "Ignoring backfill location packet as we are not follower");
}
} else if (action.equals("bfr")) {
if (Pref.getBooleanDefaultFalse("plus_follow_master")) {
Log.i(TAG, "Processing backfill location request as we are master");
GcmActivity.syncBGTable2();
}
} else if (action.equals("sensorupdate")) {
Log.i(TAG, "Received sensorupdate packet(s)");
if (Home.get_follower()) {
GcmActivity.upsertSensorCalibratonsFromJson(payload);
} else {
Log.e(TAG, "Received sensorupdate packets but we are not set as a follower");
}
} else if (action.equals("sensor_calibrations_update")) {
if (Home.get_master()) {
Log.i(TAG, "Received request for sensor calibration update");
GcmActivity.syncSensor(Sensor.currentSensor(), false);
}
} else if (action.equals("btmm")) {
if (Home.get_master_or_follower() && Home.follower_or_accept_follower()) {
BloodTest.processFromMultiMessage(bpayload);
} else {
Log.i(TAG, "Receive multi blood test but we are neither master or follower");
}
} else if (action.equals("bgmm")) {
if (Home.get_follower()) {
BgReading.processFromMultiMessage(bpayload);
} else {
Log.i(TAG, "Receive multi glucose readings but we are not a follower");
}
} else {
Log.e(TAG, "Received message action we don't know about: " + action);
}
} else {
// direct downstream message.
Log.i(TAG, "Received downstream message: " + message);
}
} finally {
JoH.releaseWakeLock(wl);
}
}
Aggregations