forked from Blendman974/faceclaw
Merge branch 'main' into ble-bandwidth-test
This commit is contained in:
commit
50cbc3a756
198 files changed
+15988
-2899
No files matched your search
@@ -0,0 +1,181 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.KeyguardManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Typeface;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.TypedValue;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The phone's ringing screen: shown over the lock screen by the alarm
|
||||
* notification's full-screen intent (or by tapping the notification). Pure
|
||||
* Java, so it works with the JavaScript side asleep or gone. Snooze and
|
||||
* Dismiss go to the service, which journals them for the engine.
|
||||
*/
|
||||
public class FaceclawAlarmActivity extends Activity {
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
private TextView titleView;
|
||||
private TextView textView;
|
||||
private TextView timeView;
|
||||
private Button snoozeButton;
|
||||
private long itemId;
|
||||
|
||||
private final Runnable poll = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
List<FaceclawAlarmService.Ringing> items = FaceclawAlarmService.snapshot();
|
||||
if (items.isEmpty()) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
FaceclawAlarmService.Ringing shown = null;
|
||||
for (FaceclawAlarmService.Ringing item : items) {
|
||||
if (item.id == itemId) {
|
||||
shown = item;
|
||||
}
|
||||
}
|
||||
if (shown == null) {
|
||||
shown = items.get(0);
|
||||
itemId = shown.id;
|
||||
}
|
||||
render(shown, items.size());
|
||||
handler.postDelayed(this, 1000);
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
showOverLockScreen();
|
||||
itemId = getIntent() == null ? 0 : getIntent().getLongExtra(FaceclawAlarms.EXTRA_ID, 0);
|
||||
setContentView(buildLayout());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
setIntent(intent);
|
||||
itemId = intent == null ? 0 : intent.getLongExtra(FaceclawAlarms.EXTRA_ID, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
handler.post(poll);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
handler.removeCallbacks(poll);
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
private void showOverLockScreen() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
|
||||
setShowWhenLocked(true);
|
||||
setTurnScreenOn(true);
|
||||
KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
|
||||
if (keyguard != null) {
|
||||
keyguard.requestDismissKeyguard(this, null);
|
||||
}
|
||||
} else {
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
|
||||
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
|
||||
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
|
||||
}
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
}
|
||||
|
||||
private View buildLayout() {
|
||||
LinearLayout root = new LinearLayout(this);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setGravity(Gravity.CENTER);
|
||||
root.setBackgroundColor(Color.BLACK);
|
||||
int pad = dp(32);
|
||||
root.setPadding(pad, pad, pad, pad);
|
||||
|
||||
timeView = new TextView(this);
|
||||
timeView.setTextColor(Color.WHITE);
|
||||
timeView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 64);
|
||||
timeView.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
timeView.setGravity(Gravity.CENTER);
|
||||
root.addView(timeView, wrap());
|
||||
|
||||
titleView = new TextView(this);
|
||||
titleView.setTextColor(Color.WHITE);
|
||||
titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28);
|
||||
titleView.setGravity(Gravity.CENTER);
|
||||
titleView.setPadding(0, dp(16), 0, 0);
|
||||
root.addView(titleView, wrap());
|
||||
|
||||
textView = new TextView(this);
|
||||
textView.setTextColor(Color.LTGRAY);
|
||||
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
|
||||
textView.setGravity(Gravity.CENTER);
|
||||
textView.setPadding(0, dp(8), 0, dp(40));
|
||||
root.addView(textView, wrap());
|
||||
|
||||
snoozeButton = new Button(this);
|
||||
snoozeButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
|
||||
snoozeButton.setOnClickListener(view -> act(FaceclawAlarmService.ACTION_SNOOZE));
|
||||
root.addView(snoozeButton, button());
|
||||
|
||||
Button dismissButton = new Button(this);
|
||||
dismissButton.setText("Dismiss");
|
||||
dismissButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
|
||||
dismissButton.setOnClickListener(view -> act(FaceclawAlarmService.ACTION_DISMISS));
|
||||
root.addView(dismissButton, button());
|
||||
return root;
|
||||
}
|
||||
|
||||
private void render(FaceclawAlarmService.Ringing item, int count) {
|
||||
timeView.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date()));
|
||||
titleView.setText(count > 1 ? item.title + " (+" + (count - 1) + " more)" : item.title);
|
||||
String status = item.silenced ? "Not answered" : item.escalated ? "" : "Ringing on the glasses";
|
||||
textView.setText(item.text.isEmpty() ? status : status.isEmpty() ? item.text : item.text + "\n" + status);
|
||||
snoozeButton.setText(FaceclawAlarms.KIND_TIMER.equals(item.kind)
|
||||
? "+" + item.snoozeMinutes + " min"
|
||||
: "Snooze " + item.snoozeMinutes + " min");
|
||||
}
|
||||
|
||||
/** Apply the action to every ringing item (one tap silences the phone). */
|
||||
private void act(String action) {
|
||||
for (FaceclawAlarmService.Ringing item : FaceclawAlarmService.snapshot()) {
|
||||
Intent intent = new Intent(this, FaceclawAlarmService.class)
|
||||
.setAction(action)
|
||||
.putExtra(FaceclawAlarms.EXTRA_ID, item.id);
|
||||
startService(intent);
|
||||
}
|
||||
finish();
|
||||
}
|
||||
|
||||
private LinearLayout.LayoutParams wrap() {
|
||||
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
|
||||
}
|
||||
|
||||
private LinearLayout.LayoutParams button() {
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp(64));
|
||||
params.topMargin = dp(12);
|
||||
return params;
|
||||
}
|
||||
|
||||
private int dp(int value) {
|
||||
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getResources().getDisplayMetrics()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
/** Phone-side alarm actions (dismiss / snooze), delivered to the JS engine; implemented in JS. */
|
||||
public interface FaceclawAlarmListener {
|
||||
void onPhoneAction(long id, String action, int minutes);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
/** The AlarmManager target: an item came due, start the ringing service. */
|
||||
public class FaceclawAlarmReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (intent == null || !FaceclawAlarms.ACTION_EXPIRE.equals(intent.getAction())) {
|
||||
return;
|
||||
}
|
||||
long id = intent.getLongExtra(FaceclawAlarms.EXTRA_ID, 0);
|
||||
if (id == 0) {
|
||||
return;
|
||||
}
|
||||
FaceclawAlarmService.ring(
|
||||
context.getApplicationContext(),
|
||||
id,
|
||||
intent.getStringExtra(FaceclawAlarms.EXTRA_TITLE),
|
||||
intent.getStringExtra(FaceclawAlarms.EXTRA_TEXT),
|
||||
intent.getStringExtra(FaceclawAlarms.EXTRA_KIND),
|
||||
intent.getIntExtra(FaceclawAlarms.EXTRA_SNOOZE_MINUTES, 10)
|
||||
);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
/**
|
||||
* Re-arms the persisted alarm schedule when the system would otherwise have
|
||||
* dropped it: after a reboot (AlarmManager alarms do not survive one), a
|
||||
* package update, or a wall-clock / time-zone change. Runs without the
|
||||
* JavaScript side; only the device-protected schedule file is needed.
|
||||
*/
|
||||
public class FaceclawAlarmRescheduleReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent == null ? null : intent.getAction();
|
||||
if (action == null) {
|
||||
return;
|
||||
}
|
||||
switch (action) {
|
||||
case Intent.ACTION_BOOT_COMPLETED:
|
||||
case Intent.ACTION_LOCKED_BOOT_COMPLETED:
|
||||
case Intent.ACTION_MY_PACKAGE_REPLACED:
|
||||
case Intent.ACTION_TIME_CHANGED:
|
||||
case Intent.ACTION_TIMEZONE_CHANGED:
|
||||
case "android.intent.action.QUICKBOOT_POWERON":
|
||||
case "com.htc.intent.action.QUICKBOOT_POWERON":
|
||||
FaceclawAlarms.rescheduleAll(context, action);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,649 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ServiceInfo;
|
||||
import android.media.AudioAttributes;
|
||||
import android.media.AudioFocusRequest;
|
||||
import android.media.AudioManager;
|
||||
import android.media.MediaPlayer;
|
||||
import android.media.RingtoneManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.IBinder;
|
||||
import android.os.Looper;
|
||||
import android.os.PowerManager;
|
||||
import android.os.VibrationEffect;
|
||||
import android.os.Vibrator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The ringing foreground service. One instance carries every item currently
|
||||
* ringing. Each item starts silent on the phone (a heads-up / lock-screen
|
||||
* notification only, the glasses do the ringing) and escalates to phone
|
||||
* sound and vibration when the glasses cannot carry it: not connected, not
|
||||
* on a head, charging, no delivery confirmation from the JS side within a
|
||||
* few seconds, or no acknowledgement within 30 seconds of delivery. Sound
|
||||
* uses the alarm stream, so media volume, the ringer switch and (unless set
|
||||
* to total silence) Do Not Disturb do not silence it.
|
||||
*/
|
||||
public class FaceclawAlarmService extends Service {
|
||||
public static final String CHANNEL_ID = "faceclaw-alarms";
|
||||
static final String ACTION_RING = "com.faceclaw.app.action.ALARM_RING";
|
||||
static final String ACTION_DELIVERED = "com.faceclaw.app.action.ALARM_DELIVERED";
|
||||
static final String ACTION_DISMISS = "com.faceclaw.app.action.ALARM_DISMISS";
|
||||
static final String ACTION_SNOOZE = "com.faceclaw.app.action.ALARM_SNOOZE";
|
||||
/** Stop an item quietly (acknowledged on the glasses / cancelled by the engine). */
|
||||
static final String ACTION_STOP_ITEM = "com.faceclaw.app.action.ALARM_STOP_ITEM";
|
||||
|
||||
/** How long to wait for the JS side to confirm the glasses are showing the item. */
|
||||
static final long DELIVERY_WAIT_MS = 5_000L;
|
||||
/** How long after delivery to the glasses before the phone joins in. */
|
||||
static final long ACK_WAIT_MS = 30_000L;
|
||||
/** Sound and vibration stop after this; the notification stays. */
|
||||
static final long AUTO_SILENCE_MS = 10 * 60_000L;
|
||||
/** Alarm-stream level (fraction of max) used when the wearer has it muted. */
|
||||
static final float MUTED_VOLUME_FRACTION = 0.6f;
|
||||
|
||||
static final class Ringing {
|
||||
final long id;
|
||||
final String title;
|
||||
final String text;
|
||||
final String kind;
|
||||
final int snoozeMinutes;
|
||||
final long ringAtMs;
|
||||
long deliveredAtMs;
|
||||
boolean escalated;
|
||||
boolean silenced;
|
||||
|
||||
Ringing(long id, String title, String text, String kind, int snoozeMinutes) {
|
||||
this.id = id;
|
||||
this.title = title == null || title.trim().isEmpty() ? "Alarm" : title;
|
||||
this.text = text == null ? "" : text;
|
||||
this.kind = kind == null ? FaceclawAlarms.KIND_ALARM : kind;
|
||||
this.snoozeMinutes = Math.max(1, snoozeMinutes);
|
||||
this.ringAtMs = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
/** Ringing items, oldest first; static so the activity can read them. */
|
||||
private static final Map<Long, Ringing> ringing = Collections.synchronizedMap(new LinkedHashMap<>());
|
||||
/**
|
||||
* Signals that arrived before the ring intent was processed (the JS
|
||||
* engine fires, launches its window and reports delivery on the same
|
||||
* main thread the service's onStartCommand queues behind), keyed by id
|
||||
* with their arrival time. Consumed by startRinging.
|
||||
*/
|
||||
private static final Map<Long, Long> deliveredEarly = Collections.synchronizedMap(new LinkedHashMap<>());
|
||||
private static final Map<Long, Long> stoppedEarly = Collections.synchronizedMap(new LinkedHashMap<>());
|
||||
private static final long EARLY_SIGNAL_MAX_AGE_MS = 15_000L;
|
||||
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
private MediaPlayer player;
|
||||
private Vibrator vibrator;
|
||||
private PowerManager.WakeLock wakeLock;
|
||||
private AudioManager audioManager;
|
||||
private AudioFocusRequest focusRequest;
|
||||
private int restoreAlarmVolume = -1;
|
||||
private long foregroundId;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Static entry points
|
||||
|
||||
public static void ring(Context context, long id, String title, String text, String kind, int snoozeMinutes) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
Intent intent = new Intent(appContext, FaceclawAlarmService.class)
|
||||
.setAction(ACTION_RING)
|
||||
.putExtra(FaceclawAlarms.EXTRA_ID, id)
|
||||
.putExtra(FaceclawAlarms.EXTRA_TITLE, title)
|
||||
.putExtra(FaceclawAlarms.EXTRA_TEXT, text)
|
||||
.putExtra(FaceclawAlarms.EXTRA_KIND, kind)
|
||||
.putExtra(FaceclawAlarms.EXTRA_SNOOZE_MINUTES, snoozeMinutes);
|
||||
FaceclawAlarms.startServiceCompat(appContext, intent);
|
||||
}
|
||||
|
||||
public static void delivered(Context context, long id) {
|
||||
if (!ringing.containsKey(id)) {
|
||||
deliveredEarly.put(id, System.currentTimeMillis());
|
||||
return;
|
||||
}
|
||||
Context appContext = context.getApplicationContext();
|
||||
appContext.startService(new Intent(appContext, FaceclawAlarmService.class)
|
||||
.setAction(ACTION_DELIVERED)
|
||||
.putExtra(FaceclawAlarms.EXTRA_ID, id));
|
||||
}
|
||||
|
||||
public static void stopItem(Context context, long id) {
|
||||
if (!ringing.containsKey(id)) {
|
||||
stoppedEarly.put(id, System.currentTimeMillis());
|
||||
return;
|
||||
}
|
||||
Context appContext = context.getApplicationContext();
|
||||
appContext.startService(new Intent(appContext, FaceclawAlarmService.class)
|
||||
.setAction(ACTION_STOP_ITEM)
|
||||
.putExtra(FaceclawAlarms.EXTRA_ID, id));
|
||||
}
|
||||
|
||||
public static boolean isRinging(long id) {
|
||||
return ringing.containsKey(id);
|
||||
}
|
||||
|
||||
public static boolean isAnythingRinging() {
|
||||
return !ringing.isEmpty();
|
||||
}
|
||||
|
||||
static List<Ringing> snapshot() {
|
||||
synchronized (ringing) {
|
||||
return new ArrayList<>(ringing.values());
|
||||
}
|
||||
}
|
||||
|
||||
static PendingIntent actionIntent(Context appContext, String action, long id) {
|
||||
Intent intent = new Intent(appContext, FaceclawAlarmService.class)
|
||||
.setAction(action)
|
||||
.putExtra(FaceclawAlarms.EXTRA_ID, id);
|
||||
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags |= PendingIntent.FLAG_IMMUTABLE;
|
||||
}
|
||||
int code = FaceclawAlarms.requestCode(id) ^ action.hashCode();
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
return PendingIntent.getForegroundService(appContext, code, intent, flags);
|
||||
}
|
||||
return PendingIntent.getService(appContext, code, intent, flags);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Service lifecycle
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
String action = intent == null ? null : intent.getAction();
|
||||
long id = intent == null ? 0 : intent.getLongExtra(FaceclawAlarms.EXTRA_ID, 0);
|
||||
if (action == null) {
|
||||
// Restarted by the system with nothing to do.
|
||||
finishIfIdle();
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
switch (action) {
|
||||
case ACTION_RING:
|
||||
startRinging(new Ringing(
|
||||
id,
|
||||
intent.getStringExtra(FaceclawAlarms.EXTRA_TITLE),
|
||||
intent.getStringExtra(FaceclawAlarms.EXTRA_TEXT),
|
||||
intent.getStringExtra(FaceclawAlarms.EXTRA_KIND),
|
||||
intent.getIntExtra(FaceclawAlarms.EXTRA_SNOOZE_MINUTES, 10)
|
||||
));
|
||||
break;
|
||||
case ACTION_DELIVERED:
|
||||
markDelivered(id);
|
||||
break;
|
||||
case ACTION_DISMISS:
|
||||
dismiss(id);
|
||||
break;
|
||||
case ACTION_SNOOZE:
|
||||
snooze(id);
|
||||
break;
|
||||
case ACTION_STOP_ITEM:
|
||||
stopItemQuietly(id, "acknowledged");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
finishIfIdle();
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
handler.removeCallbacksAndMessages(null);
|
||||
stopSound();
|
||||
releaseWakeLock();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Ringing
|
||||
|
||||
private void startRinging(Ringing item) {
|
||||
if (item.id == 0) {
|
||||
return;
|
||||
}
|
||||
ensureChannel();
|
||||
Ringing existing = ringing.get(item.id);
|
||||
if (existing != null) {
|
||||
// The engine's JS timeout and the AlarmManager alarm both fired: one ring.
|
||||
showNotification(existing);
|
||||
return;
|
||||
}
|
||||
if (takeEarlySignal(stoppedEarly, item.id)) {
|
||||
// Acknowledged or cancelled before this intent was processed.
|
||||
FaceclawAlarms.log(this, "ring " + item.id + " already acknowledged");
|
||||
return;
|
||||
}
|
||||
ringing.put(item.id, item);
|
||||
FaceclawAlarms.log(this, "ring " + item.kind + " " + item.id + " (" + FaceclawAlarms.glassesStatusDescription() + ")");
|
||||
acquireWakeLock();
|
||||
showNotification(item);
|
||||
if (!FaceclawAlarms.glassesCanCarryAlarm()) {
|
||||
escalate(item, FaceclawAlarms.glassesStatusDescription());
|
||||
return;
|
||||
}
|
||||
if (takeEarlySignal(deliveredEarly, item.id)) {
|
||||
markDelivered(item.id);
|
||||
return;
|
||||
}
|
||||
// The glasses could carry it: give the JS side a moment to confirm
|
||||
// they are actually showing it, then hold for the acknowledgement.
|
||||
handler.postDelayed(() -> {
|
||||
Ringing current = ringing.get(item.id);
|
||||
if (current != null && !current.escalated && current.deliveredAtMs == 0) {
|
||||
escalate(current, "not delivered to the glasses");
|
||||
}
|
||||
}, DELIVERY_WAIT_MS);
|
||||
}
|
||||
|
||||
/** Consume an early signal for the id; stale entries are dropped. */
|
||||
private static boolean takeEarlySignal(Map<Long, Long> signals, long id) {
|
||||
Long at = signals.remove(id);
|
||||
long now = System.currentTimeMillis();
|
||||
synchronized (signals) {
|
||||
signals.values().removeIf(stamp -> now - stamp > EARLY_SIGNAL_MAX_AGE_MS);
|
||||
}
|
||||
return at != null && now - at <= EARLY_SIGNAL_MAX_AGE_MS;
|
||||
}
|
||||
|
||||
private void markDelivered(long id) {
|
||||
Ringing item = ringing.get(id);
|
||||
if (item == null || item.deliveredAtMs != 0) {
|
||||
return;
|
||||
}
|
||||
item.deliveredAtMs = System.currentTimeMillis();
|
||||
FaceclawAlarms.log(this, "delivered " + id + " to glasses");
|
||||
handler.postDelayed(() -> {
|
||||
Ringing current = ringing.get(id);
|
||||
if (current != null && !current.escalated) {
|
||||
escalate(current, "not acknowledged on the glasses");
|
||||
}
|
||||
}, ACK_WAIT_MS);
|
||||
}
|
||||
|
||||
private void escalate(Ringing item, String reason) {
|
||||
if (item.escalated) {
|
||||
return;
|
||||
}
|
||||
item.escalated = true;
|
||||
FaceclawAlarms.log(this, "phone sound for " + item.id + ": " + reason);
|
||||
showNotification(item);
|
||||
startSound();
|
||||
handler.postDelayed(() -> {
|
||||
Ringing current = ringing.get(item.id);
|
||||
if (current != null && current.escalated && !current.silenced) {
|
||||
current.silenced = true;
|
||||
FaceclawAlarms.log(this, "auto-silenced " + current.id);
|
||||
showNotification(current);
|
||||
syncSound();
|
||||
}
|
||||
}, AUTO_SILENCE_MS);
|
||||
}
|
||||
|
||||
private void dismiss(long id) {
|
||||
Ringing item = ringing.get(id);
|
||||
if (item == null) {
|
||||
return;
|
||||
}
|
||||
FaceclawAlarms.recordPhoneAction(this, id, "dismiss", 0);
|
||||
removeItem(item);
|
||||
// Also drop the schedule entry (a one-off is over; the engine re-arms repeats).
|
||||
FaceclawAlarms.cancel(this, id);
|
||||
}
|
||||
|
||||
private void snooze(long id) {
|
||||
Ringing item = ringing.get(id);
|
||||
if (item == null) {
|
||||
return;
|
||||
}
|
||||
int minutes = item.snoozeMinutes;
|
||||
FaceclawAlarms.recordPhoneAction(this, id, "snooze", minutes);
|
||||
removeItem(item);
|
||||
// Re-arm on the phone directly so the snooze holds even with the JS
|
||||
// side gone; the engine replays the journal and lands on the same id.
|
||||
FaceclawAlarms.schedule(
|
||||
this,
|
||||
id,
|
||||
System.currentTimeMillis() + minutes * 60_000L,
|
||||
item.title,
|
||||
item.text,
|
||||
item.kind,
|
||||
minutes
|
||||
);
|
||||
}
|
||||
|
||||
private void stopItemQuietly(long id, String reason) {
|
||||
Ringing item = ringing.get(id);
|
||||
if (item == null) {
|
||||
return;
|
||||
}
|
||||
FaceclawAlarms.log(this, reason + " " + id);
|
||||
removeItem(item);
|
||||
}
|
||||
|
||||
private void removeItem(Ringing item) {
|
||||
ringing.remove(item.id);
|
||||
NotificationManager manager = getSystemService(NotificationManager.class);
|
||||
if (manager != null) {
|
||||
manager.cancel(notificationId(item.id));
|
||||
}
|
||||
syncSound();
|
||||
if (item.id == foregroundId) {
|
||||
promoteAnotherToForeground();
|
||||
}
|
||||
}
|
||||
|
||||
private void finishIfIdle() {
|
||||
if (!ringing.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
handler.removeCallbacksAndMessages(null);
|
||||
stopSound();
|
||||
releaseWakeLock();
|
||||
stopForeground(STOP_FOREGROUND_REMOVE);
|
||||
stopSelf();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Notification (the phone's silent display of the alarm)
|
||||
|
||||
private void showNotification(Ringing item) {
|
||||
Notification notification = buildNotification(item);
|
||||
if (foregroundId == 0 || foregroundId == item.id || !ringing.containsKey(foregroundId)) {
|
||||
foregroundId = item.id;
|
||||
startForegroundCompat(notificationId(item.id), notification);
|
||||
} else {
|
||||
NotificationManager manager = getSystemService(NotificationManager.class);
|
||||
if (manager != null) {
|
||||
manager.notify(notificationId(item.id), notification);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void promoteAnotherToForeground() {
|
||||
List<Ringing> items = snapshot();
|
||||
if (items.isEmpty()) {
|
||||
foregroundId = 0;
|
||||
return;
|
||||
}
|
||||
Ringing next = items.get(0);
|
||||
foregroundId = next.id;
|
||||
startForegroundCompat(notificationId(next.id), buildNotification(next));
|
||||
}
|
||||
|
||||
private void startForegroundCompat(int id, Notification notification) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(id, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);
|
||||
} else {
|
||||
startForeground(id, notification);
|
||||
}
|
||||
}
|
||||
|
||||
private Notification buildNotification(Ringing item) {
|
||||
Intent activity = new Intent(this, FaceclawAlarmActivity.class)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(FaceclawAlarms.EXTRA_ID, item.id);
|
||||
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags |= PendingIntent.FLAG_IMMUTABLE;
|
||||
}
|
||||
PendingIntent open = PendingIntent.getActivity(this, FaceclawAlarms.requestCode(item.id), activity, flags);
|
||||
|
||||
String status;
|
||||
if (item.silenced) {
|
||||
status = "Not answered";
|
||||
} else if (item.escalated) {
|
||||
status = "Ringing";
|
||||
} else {
|
||||
status = "Ringing on the glasses";
|
||||
}
|
||||
String text = item.text.isEmpty() ? status : item.text + " · " + status;
|
||||
|
||||
Notification.Builder builder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
|
||||
? new Notification.Builder(this, CHANNEL_ID)
|
||||
: new Notification.Builder(this).setPriority(Notification.PRIORITY_MAX);
|
||||
builder.setContentTitle(item.title)
|
||||
.setContentText(text)
|
||||
.setSmallIcon(getApplicationInfo().icon)
|
||||
.setContentIntent(open)
|
||||
.setFullScreenIntent(open, true)
|
||||
.setCategory(Notification.CATEGORY_ALARM)
|
||||
.setVisibility(Notification.VISIBILITY_PUBLIC)
|
||||
.setOngoing(true)
|
||||
.setAutoCancel(false)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setWhen(item.ringAtMs)
|
||||
.setShowWhen(true)
|
||||
.addAction(new Notification.Action.Builder(
|
||||
null,
|
||||
FaceclawAlarms.KIND_TIMER.equals(item.kind) ? "+" + item.snoozeMinutes + " min" : "Snooze " + item.snoozeMinutes + " min",
|
||||
actionIntent(this, ACTION_SNOOZE, item.id)).build())
|
||||
.addAction(new Notification.Action.Builder(
|
||||
null,
|
||||
"Dismiss",
|
||||
actionIntent(this, ACTION_DISMISS, item.id)).build());
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
// Pre-channel: the builder controls sound, and we want none.
|
||||
builder.setSound(null).setVibrate(null);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private void ensureChannel() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
return;
|
||||
}
|
||||
NotificationManager manager = getSystemService(NotificationManager.class);
|
||||
if (manager == null) {
|
||||
return;
|
||||
}
|
||||
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Alarms", NotificationManager.IMPORTANCE_HIGH);
|
||||
channel.setDescription("Timers and alarms going off. Silent here: the sound is played by the alarm itself.");
|
||||
// The service plays the sound itself (on the alarm stream) so the
|
||||
// notification stays silent and vibration-free on purpose.
|
||||
channel.setSound(null, null);
|
||||
channel.enableVibration(false);
|
||||
channel.setBypassDnd(true);
|
||||
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
|
||||
manager.createNotificationChannel(channel);
|
||||
}
|
||||
|
||||
private static int notificationId(long id) {
|
||||
return 0x41000000 | (FaceclawAlarms.requestCode(id) & 0x00ffffff);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Sound and vibration (only while some item is escalated and not yet silenced)
|
||||
|
||||
private void syncSound() {
|
||||
boolean wanted = false;
|
||||
for (Ringing item : snapshot()) {
|
||||
if (item.escalated && !item.silenced) {
|
||||
wanted = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (wanted) {
|
||||
startSound();
|
||||
} else {
|
||||
stopSound();
|
||||
}
|
||||
}
|
||||
|
||||
private void startSound() {
|
||||
if (player != null) {
|
||||
return;
|
||||
}
|
||||
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
|
||||
AudioAttributes attributes = new AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_ALARM)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
.build();
|
||||
raiseMutedAlarmVolume();
|
||||
requestAudioFocus(attributes);
|
||||
Uri tone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
|
||||
if (tone == null) {
|
||||
tone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
|
||||
}
|
||||
try {
|
||||
MediaPlayer created = new MediaPlayer();
|
||||
created.setAudioAttributes(attributes);
|
||||
created.setDataSource(this, tone);
|
||||
created.setLooping(true);
|
||||
created.prepare();
|
||||
created.start();
|
||||
player = created;
|
||||
} catch (Exception error) {
|
||||
FaceclawAlarms.log(this, "alarm sound failed: " + error.getMessage());
|
||||
player = null;
|
||||
}
|
||||
startVibration();
|
||||
}
|
||||
|
||||
private void stopSound() {
|
||||
if (player != null) {
|
||||
try {
|
||||
player.stop();
|
||||
} catch (RuntimeException ignored) {
|
||||
// Already stopped.
|
||||
}
|
||||
player.release();
|
||||
player = null;
|
||||
}
|
||||
if (vibrator != null) {
|
||||
vibrator.cancel();
|
||||
vibrator = null;
|
||||
}
|
||||
abandonAudioFocus();
|
||||
restoreAlarmVolume();
|
||||
}
|
||||
|
||||
/**
|
||||
* A muted alarm stream is the one thing that would keep an alarm clock
|
||||
* silent; raise it for the duration of the ring and put it back after.
|
||||
*/
|
||||
private void raiseMutedAlarmVolume() {
|
||||
if (audioManager == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
int current = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
|
||||
int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
|
||||
if (current == 0 && max > 0) {
|
||||
restoreAlarmVolume = current;
|
||||
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, Math.max(1, Math.round(max * MUTED_VOLUME_FRACTION)), 0);
|
||||
}
|
||||
} catch (RuntimeException error) {
|
||||
FaceclawAlarms.log(this, "alarm volume change failed: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreAlarmVolume() {
|
||||
if (audioManager == null || restoreAlarmVolume < 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, restoreAlarmVolume, 0);
|
||||
} catch (RuntimeException ignored) {
|
||||
// Best effort.
|
||||
}
|
||||
restoreAlarmVolume = -1;
|
||||
}
|
||||
|
||||
private void requestAudioFocus(AudioAttributes attributes) {
|
||||
if (audioManager == null) {
|
||||
return;
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
|
||||
.setAudioAttributes(attributes)
|
||||
.build();
|
||||
audioManager.requestAudioFocus(focusRequest);
|
||||
} else {
|
||||
audioManager.requestAudioFocus(null, AudioManager.STREAM_ALARM, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
|
||||
}
|
||||
}
|
||||
|
||||
private void abandonAudioFocus() {
|
||||
if (audioManager == null) {
|
||||
return;
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
if (focusRequest != null) {
|
||||
audioManager.abandonAudioFocusRequest(focusRequest);
|
||||
focusRequest = null;
|
||||
}
|
||||
} else {
|
||||
audioManager.abandonAudioFocus(null);
|
||||
}
|
||||
}
|
||||
|
||||
private void startVibration() {
|
||||
Vibrator device = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
|
||||
if (device == null || !device.hasVibrator()) {
|
||||
return;
|
||||
}
|
||||
vibrator = device;
|
||||
long[] pattern = {0, 600, 400, 600, 1200};
|
||||
AudioAttributes attributes = new AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_ALARM)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
.build();
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
device.vibrate(VibrationEffect.createWaveform(pattern, 0), attributes);
|
||||
} else {
|
||||
device.vibrate(pattern, 0, attributes);
|
||||
}
|
||||
} catch (RuntimeException error) {
|
||||
FaceclawAlarms.log(this, "vibration failed: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Wake lock
|
||||
|
||||
private void acquireWakeLock() {
|
||||
if (wakeLock != null && wakeLock.isHeld()) {
|
||||
return;
|
||||
}
|
||||
PowerManager power = (PowerManager) getSystemService(Context.POWER_SERVICE);
|
||||
if (power == null) {
|
||||
return;
|
||||
}
|
||||
wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "faceclaw:alarm");
|
||||
// Bounded: sound auto-silences at AUTO_SILENCE_MS, and a stuck lock
|
||||
// past that would only drain the battery.
|
||||
wakeLock.acquire(AUTO_SILENCE_MS + ACK_WAIT_MS + DELIVERY_WAIT_MS + 10_000L);
|
||||
}
|
||||
|
||||
private void releaseWakeLock() {
|
||||
if (wakeLock != null && wakeLock.isHeld()) {
|
||||
wakeLock.release();
|
||||
}
|
||||
wakeLock = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,620 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.app.ActivityManager;
|
||||
import android.app.AlarmManager;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.media.AudioManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.PowerManager;
|
||||
import android.provider.Settings;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.tns.NativeScriptActivity;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* The phone side of the Timers app's alarms and countdown timers, built to
|
||||
* ring without the JavaScript side: scheduling through AlarmManager's alarm
|
||||
* clock API, a persisted schedule (in device-protected storage) that the
|
||||
* reschedule receiver replays after reboots and time changes, the hand-off
|
||||
* to the ringing foreground service, and a journal of what the wearer did
|
||||
* on the phone (dismiss / snooze) for the JS engine to replay when it is
|
||||
* next awake. Also the reliability self-check the UI surfaces.
|
||||
*
|
||||
* Ids are the JS engine's item ids (a millisecond epoch times 100 plus a
|
||||
* serial), shared between timers and alarms; `kind` tells the two apart for
|
||||
* wording only.
|
||||
*/
|
||||
public final class FaceclawAlarms {
|
||||
public static final String ACTION_EXPIRE = "com.faceclaw.app.action.ALARM_EXPIRE";
|
||||
static final String EXTRA_ID = "id";
|
||||
static final String EXTRA_TITLE = "title";
|
||||
static final String EXTRA_TEXT = "text";
|
||||
static final String EXTRA_KIND = "kind";
|
||||
static final String EXTRA_SNOOZE_MINUTES = "snoozeMinutes";
|
||||
|
||||
public static final String KIND_TIMER = "timer";
|
||||
public static final String KIND_ALARM = "alarm";
|
||||
|
||||
private static final String PREFS_NAME = "faceclaw-alarms";
|
||||
private static final String KEY_SCHEDULED = "scheduled";
|
||||
private static final String KEY_JOURNAL = "journal";
|
||||
private static final String KEY_LOG = "log";
|
||||
private static final int LOG_LINES = 60;
|
||||
|
||||
/**
|
||||
* A schedule entry found already past due (after a reboot, or when the
|
||||
* process was asleep) rings if it is at most this late; older ones are
|
||||
* dropped as missed. Matches the JS engine's grace window.
|
||||
*/
|
||||
static final long LATE_GRACE_MS = 5 * 60_000L;
|
||||
/** A glasses status report older than this is not trusted (the JS side is probably gone). */
|
||||
static final long GLASSES_STATUS_MAX_AGE_MS = 3 * 60_000L;
|
||||
|
||||
private static volatile boolean glassesConnected;
|
||||
private static volatile boolean glassesWorn;
|
||||
private static volatile boolean glassesCharging;
|
||||
private static volatile long glassesStatusAtMs;
|
||||
|
||||
private static volatile FaceclawAlarmListener listener;
|
||||
private static final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private FaceclawAlarms() {}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Storage
|
||||
|
||||
/**
|
||||
* Device-protected storage, so the schedule is readable before the first
|
||||
* unlock after a reboot (the reschedule receiver may run then on some
|
||||
* devices) and survives credential-encrypted storage being unavailable.
|
||||
*/
|
||||
static SharedPreferences prefs(Context context) {
|
||||
Context base = context.getApplicationContext();
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
base = base.createDeviceProtectedStorageContext();
|
||||
}
|
||||
return base.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
private static synchronized JSONArray readArray(Context context, String key) {
|
||||
String raw = prefs(context).getString(key, "[]");
|
||||
try {
|
||||
return new JSONArray(raw);
|
||||
} catch (JSONException error) {
|
||||
return new JSONArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized void writeArray(Context context, String key, JSONArray array) {
|
||||
prefs(context).edit().putString(key, array.toString()).apply();
|
||||
}
|
||||
|
||||
static JSONObject findScheduled(Context context, long id) {
|
||||
JSONArray scheduled = readArray(context, KEY_SCHEDULED);
|
||||
for (int index = 0; index < scheduled.length(); index++) {
|
||||
JSONObject entry = scheduled.optJSONObject(index);
|
||||
if (entry != null && entry.optLong("id") == id) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static synchronized void putScheduled(Context context, JSONObject entry) {
|
||||
JSONArray scheduled = readArray(context, KEY_SCHEDULED);
|
||||
JSONArray next = new JSONArray();
|
||||
long id = entry.optLong("id");
|
||||
for (int index = 0; index < scheduled.length(); index++) {
|
||||
JSONObject existing = scheduled.optJSONObject(index);
|
||||
if (existing != null && existing.optLong("id") != id) {
|
||||
next.put(existing);
|
||||
}
|
||||
}
|
||||
next.put(entry);
|
||||
writeArray(context, KEY_SCHEDULED, next);
|
||||
}
|
||||
|
||||
private static synchronized void removeScheduled(Context context, long id) {
|
||||
JSONArray scheduled = readArray(context, KEY_SCHEDULED);
|
||||
JSONArray next = new JSONArray();
|
||||
for (int index = 0; index < scheduled.length(); index++) {
|
||||
JSONObject existing = scheduled.optJSONObject(index);
|
||||
if (existing != null && existing.optLong("id") != id) {
|
||||
next.put(existing);
|
||||
}
|
||||
}
|
||||
writeArray(context, KEY_SCHEDULED, next);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Scheduling
|
||||
|
||||
/**
|
||||
* Schedule (or move) the phone alarm for an item. Idempotent: the same id
|
||||
* always maps to the same PendingIntent, so a reschedule replaces rather
|
||||
* than duplicates. setAlarmClock is exact, fires through Doze and battery
|
||||
* savers, and shows the system's alarm indicator; the fallbacks only run
|
||||
* where it is unavailable.
|
||||
*/
|
||||
public static void schedule(
|
||||
Context context,
|
||||
long id,
|
||||
long triggerAtMs,
|
||||
String title,
|
||||
String text,
|
||||
String kind,
|
||||
int snoozeMinutes
|
||||
) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
JSONObject entry = new JSONObject();
|
||||
try {
|
||||
entry.put("id", id);
|
||||
entry.put("at", triggerAtMs);
|
||||
entry.put("title", title == null ? "" : title);
|
||||
entry.put("text", text == null ? "" : text);
|
||||
entry.put("kind", kind == null ? KIND_ALARM : kind);
|
||||
entry.put("snoozeMinutes", snoozeMinutes);
|
||||
} catch (JSONException ignored) {
|
||||
return;
|
||||
}
|
||||
putScheduled(appContext, entry);
|
||||
armAlarm(appContext, entry);
|
||||
}
|
||||
|
||||
private static void armAlarm(Context appContext, JSONObject entry) {
|
||||
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
|
||||
if (manager == null) {
|
||||
return;
|
||||
}
|
||||
long id = entry.optLong("id");
|
||||
long triggerAt = Math.max(System.currentTimeMillis(), entry.optLong("at"));
|
||||
PendingIntent fire = expiryPendingIntent(appContext, entry);
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
AlarmManager.AlarmClockInfo info = new AlarmManager.AlarmClockInfo(triggerAt, showIntent(appContext, id));
|
||||
manager.setAlarmClock(info, fire);
|
||||
} else {
|
||||
manager.setExact(AlarmManager.RTC_WAKEUP, triggerAt, fire);
|
||||
}
|
||||
} catch (SecurityException error) {
|
||||
// Exact-alarm access revoked (Android 12/13 without USE_EXACT_ALARM
|
||||
// honoured): the inexact alarm is still a wake-up, just a late one.
|
||||
log(appContext, "exact alarm refused for " + id + ": " + error.getMessage());
|
||||
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, fire);
|
||||
}
|
||||
}
|
||||
|
||||
/** Cancel the phone alarm for an item, stop it if ringing, and forget it. */
|
||||
public static void cancel(Context context, long id) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
|
||||
if (manager != null) {
|
||||
JSONObject entry = new JSONObject();
|
||||
try {
|
||||
entry.put("id", id);
|
||||
} catch (JSONException ignored) {
|
||||
// unreachable for a numeric put
|
||||
}
|
||||
manager.cancel(expiryPendingIntent(appContext, entry));
|
||||
}
|
||||
removeScheduled(appContext, id);
|
||||
FaceclawAlarmService.stopItem(appContext, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replay the persisted schedule into AlarmManager: after a reboot (alarms
|
||||
* are wiped), a package update, or a wall-clock / time-zone change. Entries
|
||||
* already due ring now if inside the grace window, else are dropped.
|
||||
*/
|
||||
public static void rescheduleAll(Context context, String reason) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
JSONArray scheduled = readArray(appContext, KEY_SCHEDULED);
|
||||
long now = System.currentTimeMillis();
|
||||
int armed = 0;
|
||||
for (int index = 0; index < scheduled.length(); index++) {
|
||||
JSONObject entry = scheduled.optJSONObject(index);
|
||||
if (entry == null) {
|
||||
continue;
|
||||
}
|
||||
long at = entry.optLong("at");
|
||||
if (at <= now) {
|
||||
if (now - at <= LATE_GRACE_MS) {
|
||||
ringEntry(appContext, entry);
|
||||
} else {
|
||||
log(appContext, "missed " + entry.optString("kind") + " " + entry.optLong("id") + " (" + reason + ")");
|
||||
removeScheduled(appContext, entry.optLong("id"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
armAlarm(appContext, entry);
|
||||
armed++;
|
||||
}
|
||||
log(appContext, "rescheduled " + armed + " (" + reason + ")");
|
||||
}
|
||||
|
||||
/**
|
||||
* The schedule and AlarmManager can disagree (a force-stop clears alarms
|
||||
* but not the file, an OEM killer drops them). True when the soonest
|
||||
* stored entry is not what the system reports as the next alarm clock.
|
||||
*/
|
||||
public static boolean scheduleLooksStale(Context context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
|
||||
return false;
|
||||
}
|
||||
Context appContext = context.getApplicationContext();
|
||||
JSONArray scheduled = readArray(appContext, KEY_SCHEDULED);
|
||||
long now = System.currentTimeMillis();
|
||||
long soonest = Long.MAX_VALUE;
|
||||
for (int index = 0; index < scheduled.length(); index++) {
|
||||
JSONObject entry = scheduled.optJSONObject(index);
|
||||
if (entry != null && entry.optLong("at") > now) {
|
||||
soonest = Math.min(soonest, entry.optLong("at"));
|
||||
}
|
||||
}
|
||||
if (soonest == Long.MAX_VALUE) {
|
||||
return false;
|
||||
}
|
||||
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
|
||||
if (manager == null) {
|
||||
return false;
|
||||
}
|
||||
AlarmManager.AlarmClockInfo next = manager.getNextAlarmClock();
|
||||
// Another app's alarm may legitimately be sooner; only a later (or
|
||||
// absent) system alarm proves ours is missing.
|
||||
return next == null || next.getTriggerTime() > soonest + 1000;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Ringing
|
||||
|
||||
/** An item came due: hand it to the ringing service (idempotent per id). */
|
||||
static void ringEntry(Context appContext, JSONObject entry) {
|
||||
FaceclawAlarmService.ring(
|
||||
appContext,
|
||||
entry.optLong("id"),
|
||||
entry.optString("title"),
|
||||
entry.optString("text"),
|
||||
entry.optString("kind", KIND_ALARM),
|
||||
entry.optInt("snoozeMinutes", 10)
|
||||
);
|
||||
}
|
||||
|
||||
/** The JS engine's own expiry path; the service deduplicates against the alarm's. */
|
||||
public static void ring(Context context, long id, String title, String text, String kind, int snoozeMinutes) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
|
||||
if (manager != null) {
|
||||
JSONObject probe = new JSONObject();
|
||||
try {
|
||||
probe.put("id", id);
|
||||
} catch (JSONException ignored) {
|
||||
// unreachable for a numeric put
|
||||
}
|
||||
manager.cancel(expiryPendingIntent(appContext, probe));
|
||||
}
|
||||
FaceclawAlarmService.ring(appContext, id, title, text, kind, snoozeMinutes);
|
||||
}
|
||||
|
||||
/** The glasses are showing the ringing item; the acknowledgement clock starts now. */
|
||||
public static void deliveredToGlasses(Context context, long id) {
|
||||
FaceclawAlarmService.delivered(context.getApplicationContext(), id);
|
||||
}
|
||||
|
||||
/** The wearer dismissed or snoozed it on the glasses: the phone side goes quiet. */
|
||||
public static void acknowledge(Context context, long id) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
removeScheduled(appContext, id);
|
||||
FaceclawAlarmService.stopItem(appContext, id);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Glasses status (pushed by the JS side; in-memory, so a dead process reads as "no glasses")
|
||||
|
||||
public static void setGlassesStatus(boolean connected, boolean worn, boolean charging) {
|
||||
glassesConnected = connected;
|
||||
glassesWorn = worn;
|
||||
glassesCharging = charging;
|
||||
glassesStatusAtMs = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
/** True only when a fresh report says the glasses are connected, on a head, and not charging. */
|
||||
static boolean glassesCanCarryAlarm() {
|
||||
long age = System.currentTimeMillis() - glassesStatusAtMs;
|
||||
if (glassesStatusAtMs == 0 || age > GLASSES_STATUS_MAX_AGE_MS) {
|
||||
return false;
|
||||
}
|
||||
return glassesConnected && glassesWorn && !glassesCharging;
|
||||
}
|
||||
|
||||
static String glassesStatusDescription() {
|
||||
if (glassesStatusAtMs == 0) {
|
||||
return "no glasses status";
|
||||
}
|
||||
long age = System.currentTimeMillis() - glassesStatusAtMs;
|
||||
if (age > GLASSES_STATUS_MAX_AGE_MS) {
|
||||
return "glasses status stale";
|
||||
}
|
||||
if (!glassesConnected) {
|
||||
return "glasses not connected";
|
||||
}
|
||||
if (glassesCharging) {
|
||||
return "glasses charging";
|
||||
}
|
||||
if (!glassesWorn) {
|
||||
return "glasses not worn";
|
||||
}
|
||||
return "glasses worn";
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Phone actions -> JS
|
||||
|
||||
public static void setListener(FaceclawAlarmListener newListener) {
|
||||
listener = newListener;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a dismiss / snooze done on the phone. Delivered live to the JS
|
||||
* listener when one is registered, and journaled regardless so a JS side
|
||||
* that was asleep or gone can catch up on its next boot.
|
||||
*/
|
||||
static void recordPhoneAction(Context context, long id, String action, int minutes) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
JSONObject event = new JSONObject();
|
||||
try {
|
||||
event.put("id", id);
|
||||
event.put("action", action);
|
||||
event.put("minutes", minutes);
|
||||
event.put("at", System.currentTimeMillis());
|
||||
} catch (JSONException ignored) {
|
||||
return;
|
||||
}
|
||||
synchronized (FaceclawAlarms.class) {
|
||||
JSONArray journal = readArray(appContext, KEY_JOURNAL);
|
||||
journal.put(event);
|
||||
writeArray(appContext, KEY_JOURNAL, journal);
|
||||
}
|
||||
log(appContext, "phone " + action + " " + id + (minutes > 0 ? " (" + minutes + " min)" : ""));
|
||||
final FaceclawAlarmListener current = listener;
|
||||
if (current != null) {
|
||||
mainHandler.post(() -> {
|
||||
try {
|
||||
current.onPhoneAction(id, action, minutes);
|
||||
} catch (RuntimeException error) {
|
||||
log(appContext, "listener failed: " + error.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Hand the journal to the JS side (as a JSON array) and clear it. */
|
||||
public static synchronized String drainJournal(Context context) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
JSONArray journal = readArray(appContext, KEY_JOURNAL);
|
||||
writeArray(appContext, KEY_JOURNAL, new JSONArray());
|
||||
return journal.toString();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Reliability self-check
|
||||
|
||||
/**
|
||||
* Conditions under which the phone may fail to ring, as a JSON array of
|
||||
* {code, message, fixable}, most serious first. Empty when everything is
|
||||
* in order. The UI shows these before the wearer relies on an alarm.
|
||||
*/
|
||||
public static String checkReliability(Context context) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
JSONArray issues = new JSONArray();
|
||||
NotificationManager notifications = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
AlarmManager alarms = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && alarms != null && !alarms.canScheduleExactAlarms()) {
|
||||
addIssue(issues, "exact-alarm", "Exact alarms are not allowed for Faceclaw, so alarms may ring late.", true);
|
||||
}
|
||||
if (notifications != null && !notifications.areNotificationsEnabled()) {
|
||||
addIssue(issues, "notifications", "Notifications are turned off for Faceclaw, so the phone cannot show or sound an alarm.", true);
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notifications != null) {
|
||||
NotificationChannel channel = notifications.getNotificationChannel(FaceclawAlarmService.CHANNEL_ID);
|
||||
if (channel != null && channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
|
||||
addIssue(issues, "alarm-channel", "The Alarms notification category is blocked, so the phone cannot show an alarm.", true);
|
||||
}
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && notifications != null && !notifications.canUseFullScreenIntent()) {
|
||||
addIssue(issues, "full-screen", "Full-screen alarms are not allowed, so a ringing alarm will not take over the lock screen.", true);
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notifications != null) {
|
||||
int filter = notifications.getCurrentInterruptionFilter();
|
||||
if (filter == NotificationManager.INTERRUPTION_FILTER_NONE) {
|
||||
addIssue(issues, "dnd-total", "Do Not Disturb is set to total silence, which silences alarms too.", true);
|
||||
} else if (filter == NotificationManager.INTERRUPTION_FILTER_PRIORITY) {
|
||||
try {
|
||||
NotificationManager.Policy policy = notifications.getNotificationPolicy();
|
||||
if (policy != null && (policy.priorityCategories & NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS) == 0) {
|
||||
addIssue(issues, "dnd-alarms", "Do Not Disturb does not allow alarms, so the phone will stay silent.", true);
|
||||
}
|
||||
} catch (SecurityException ignored) {
|
||||
// No notification-policy access: cannot inspect the exceptions.
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
|
||||
if (activityManager != null && activityManager.isBackgroundRestricted()) {
|
||||
addIssue(issues, "background-restricted", "Background usage is restricted for Faceclaw, which blocks alarms while the app is not open.", true);
|
||||
}
|
||||
}
|
||||
PowerManager power = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
|
||||
if (power != null && !power.isIgnoringBatteryOptimizations(appContext.getPackageName())) {
|
||||
addIssue(issues, "battery-optimized", "Battery optimization is on for Faceclaw; some phones delay alarms because of it.", true);
|
||||
}
|
||||
AudioManager audio = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
if (audio != null && audio.getStreamVolume(AudioManager.STREAM_ALARM) == 0) {
|
||||
addIssue(issues, "alarm-volume", "The phone's alarm volume is muted; Faceclaw raises it while ringing, but check it.", true);
|
||||
}
|
||||
String maker = Build.MANUFACTURER == null ? "" : Build.MANUFACTURER.toLowerCase(Locale.ROOT);
|
||||
if (maker.contains("xiaomi") || maker.contains("huawei") || maker.contains("oppo") || maker.contains("vivo")
|
||||
|| maker.contains("oneplus") || maker.contains("realme") || maker.contains("meizu") || maker.contains("asus")) {
|
||||
addIssue(issues, "oem-killer", "This phone maker is known to stop background apps; allow Faceclaw to auto-start and run unrestricted (see dontkillmyapp.com).", true);
|
||||
}
|
||||
if (scheduleLooksStale(appContext)) {
|
||||
addIssue(issues, "schedule-stale", "The system lost Faceclaw's next alarm (the app may have been force-stopped); it was re-armed.", false);
|
||||
rescheduleAll(appContext, "self-check");
|
||||
}
|
||||
return issues.toString();
|
||||
}
|
||||
|
||||
private static void addIssue(JSONArray issues, String code, String message, boolean fixable) {
|
||||
JSONObject issue = new JSONObject();
|
||||
try {
|
||||
issue.put("code", code);
|
||||
issue.put("message", message);
|
||||
issue.put("fixable", fixable);
|
||||
} catch (JSONException ignored) {
|
||||
return;
|
||||
}
|
||||
issues.put(issue);
|
||||
}
|
||||
|
||||
/** Open the system screen where the issue can be fixed. */
|
||||
public static void openReliabilityFix(Context context, String code) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
String pkg = appContext.getPackageName();
|
||||
Intent intent;
|
||||
switch (code == null ? "" : code) {
|
||||
case "exact-alarm":
|
||||
intent = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
? new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM, Uri.parse("package:" + pkg))
|
||||
: appDetails(pkg);
|
||||
break;
|
||||
case "notifications":
|
||||
case "alarm-channel":
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(Settings.EXTRA_APP_PACKAGE, pkg);
|
||||
if ("alarm-channel".equals(code)) {
|
||||
intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
|
||||
.putExtra(Settings.EXTRA_APP_PACKAGE, pkg)
|
||||
.putExtra(Settings.EXTRA_CHANNEL_ID, FaceclawAlarmService.CHANNEL_ID);
|
||||
}
|
||||
} else {
|
||||
intent = appDetails(pkg);
|
||||
}
|
||||
break;
|
||||
case "full-screen":
|
||||
intent = Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
|
||||
? new Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, Uri.parse("package:" + pkg))
|
||||
: appDetails(pkg);
|
||||
break;
|
||||
case "dnd-total":
|
||||
case "dnd-alarms":
|
||||
intent = new Intent(Settings.ACTION_SOUND_SETTINGS);
|
||||
break;
|
||||
case "battery-optimized":
|
||||
intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:" + pkg));
|
||||
break;
|
||||
case "alarm-volume":
|
||||
intent = new Intent(Settings.ACTION_SOUND_SETTINGS);
|
||||
break;
|
||||
default:
|
||||
intent = appDetails(pkg);
|
||||
break;
|
||||
}
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
try {
|
||||
appContext.startActivity(intent);
|
||||
} catch (RuntimeException error) {
|
||||
Intent fallback = appDetails(pkg).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
try {
|
||||
appContext.startActivity(fallback);
|
||||
} catch (RuntimeException ignored) {
|
||||
// No settings activity at all; nothing more to do.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Intent appDetails(String pkg) {
|
||||
return new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + pkg));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Diagnostics log
|
||||
|
||||
static synchronized void log(Context context, String line) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
JSONArray log = readArray(appContext, KEY_LOG);
|
||||
JSONArray next = new JSONArray();
|
||||
int start = Math.max(0, log.length() - (LOG_LINES - 1));
|
||||
for (int index = start; index < log.length(); index++) {
|
||||
next.put(log.optString(index));
|
||||
}
|
||||
next.put(System.currentTimeMillis() + " " + line);
|
||||
writeArray(appContext, KEY_LOG, next);
|
||||
}
|
||||
|
||||
/** The ring / miss / action log, newest last, one line per entry. */
|
||||
public static String readLog(Context context) {
|
||||
JSONArray log = readArray(context.getApplicationContext(), KEY_LOG);
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int index = 0; index < log.length(); index++) {
|
||||
if (index > 0) {
|
||||
out.append('\n');
|
||||
}
|
||||
out.append(log.optString(index));
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Intents
|
||||
|
||||
private static PendingIntent expiryPendingIntent(Context appContext, JSONObject entry) {
|
||||
Intent intent = new Intent(appContext, FaceclawAlarmReceiver.class);
|
||||
intent.setAction(ACTION_EXPIRE);
|
||||
long id = entry.optLong("id");
|
||||
intent.putExtra(EXTRA_ID, id);
|
||||
intent.putExtra(EXTRA_TITLE, entry.optString("title"));
|
||||
intent.putExtra(EXTRA_TEXT, entry.optString("text"));
|
||||
intent.putExtra(EXTRA_KIND, entry.optString("kind", KIND_ALARM));
|
||||
intent.putExtra(EXTRA_SNOOZE_MINUTES, entry.optInt("snoozeMinutes", 10));
|
||||
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags |= PendingIntent.FLAG_IMMUTABLE;
|
||||
}
|
||||
return PendingIntent.getBroadcast(appContext, requestCode(id), intent, flags);
|
||||
}
|
||||
|
||||
/** What the system's alarm indicator opens: the app. */
|
||||
private static PendingIntent showIntent(Context appContext, long id) {
|
||||
Intent intent = new Intent(appContext, NativeScriptActivity.class);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags |= PendingIntent.FLAG_IMMUTABLE;
|
||||
}
|
||||
return PendingIntent.getActivity(appContext, requestCode(id), intent, flags);
|
||||
}
|
||||
|
||||
static int requestCode(long id) {
|
||||
return (int) (id ^ (id >>> 32)) & 0x7fffffff;
|
||||
}
|
||||
|
||||
static void startServiceCompat(Context appContext, Intent intent) {
|
||||
ContextCompat.startForegroundService(appContext, intent);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
public interface FaceclawAmbientLightListener {
|
||||
/**
|
||||
* A CFW ambient-light report (settings-channel field 105) from the master
|
||||
* temple. body is the raw 24-byte ['A','L',ver,reason,...] record; it is
|
||||
* decoded on the TS side (app/native/ambient-light.ts).
|
||||
*/
|
||||
void onAmbientLight(byte[] body);
|
||||
}
|
||||
+230
-23
@@ -43,6 +43,8 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
private static final long FACECLAW_WAKE_LEASE_RENEW_MS = 45_000;
|
||||
private static final long FACECLAW_WAKE_CONTROL_WAIT_MS = 1_500;
|
||||
private static final long CFW_CLEANUP_WAIT_MS = 4_000;
|
||||
private static final int COMPASS_REPORT_INTERVAL_MS = 100;
|
||||
private static final int COMPASS_MIN_CHANGE_DEGREES = 0;
|
||||
|
||||
private final Context appContext;
|
||||
private final PowerManager powerManager;
|
||||
@@ -58,7 +60,20 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
private volatile FaceclawBleCommunicatorListener listener;
|
||||
private final java.util.List<FaceclawImuListener> imuListeners =
|
||||
new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||
private final java.util.List<FaceclawCompassListener> compassListeners =
|
||||
/** A compass subscriber plus the Looper it registered from (see addCompassListener). */
|
||||
private static final class CompassSubscription {
|
||||
final FaceclawCompassListener listener;
|
||||
final Handler handler;
|
||||
|
||||
CompassSubscription(FaceclawCompassListener listener, Handler handler) {
|
||||
this.listener = listener;
|
||||
this.handler = handler;
|
||||
}
|
||||
}
|
||||
|
||||
private final java.util.List<CompassSubscription> compassSubscriptions =
|
||||
new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||
private final java.util.List<FaceclawAmbientLightListener> ambientLightListeners =
|
||||
new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||
private final java.util.List<FaceclawMicStatusListener> micStatusListeners =
|
||||
new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||
@@ -88,7 +103,13 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
private int firmwareDebugFlagsLastSent = -1;
|
||||
// Desired CFW mode-10 compass state. It survives reconnects; lastSent is
|
||||
// reset with each session so an open Compass window is re-asserted.
|
||||
private boolean compassEnabled;
|
||||
/**
|
||||
* Who currently wants the stock compass running (the Compass window, the
|
||||
* Navigate worker, ...). The magnetometer is one shared resource, so it
|
||||
* stays on while any owner holds it and is released when the last lets go;
|
||||
* this keeps one app's release from silently switching off another's feed.
|
||||
*/
|
||||
private final java.util.Set<String> compassOwners = new java.util.HashSet<>();
|
||||
private int compassControlLastSent = -1;
|
||||
// Whether the glasses-side compass may still be running: set when an enable
|
||||
// is enqueued, cleared only when a disable is acked. Drives the forced
|
||||
@@ -141,6 +162,8 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
private long lastShutdownExitAtMs = 0;
|
||||
private int headsetBattery = -1;
|
||||
private int headsetCharging = -1;
|
||||
private int ringBattery = -1;
|
||||
private int ringCharging = -1;
|
||||
// Silent mode: 1 = on, 0 = off, -1 = not yet known. See updateSilentModeLocked.
|
||||
private int silentMode = -1;
|
||||
private int wearState = -1;
|
||||
@@ -508,12 +531,32 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
* stock sid-0x08 navigation notifications and FaceclawCompassListeners.
|
||||
*/
|
||||
public void setCompassEnabled(boolean enable) {
|
||||
setCompassEnabled("compass", enable);
|
||||
}
|
||||
|
||||
/**
|
||||
* As above, on behalf of a named owner. The compass runs while at least
|
||||
* one owner has enabled it; an owner disabling it only takes effect once
|
||||
* no other owner still wants it.
|
||||
*/
|
||||
public void setCompassEnabled(String owner, boolean enable) {
|
||||
synchronized (lock) {
|
||||
compassEnabled = enable;
|
||||
boolean before = !compassOwners.isEmpty();
|
||||
if (enable) {
|
||||
compassOwners.add(owner);
|
||||
} else {
|
||||
compassOwners.remove(owner);
|
||||
}
|
||||
boolean wanted = !compassOwners.isEmpty();
|
||||
if (wanted == before && compassControlLastSent == (wanted ? 1 : 0)) {
|
||||
logLine("compass " + (enable ? "enable" : "disable") + " by " + owner
|
||||
+ "; state unchanged (owners=" + compassOwners + ")");
|
||||
return;
|
||||
}
|
||||
compassControlLastSent = -1;
|
||||
clearMessagesOfKindLocked("compass-control");
|
||||
if (running && sessionReady && !shutdownRequested && fixedLayoutCreated) {
|
||||
enqueueCompassControlLocked(true, compassEnabled);
|
||||
enqueueCompassControlLocked(true, wanted);
|
||||
} else {
|
||||
logLine("defer compass " + (enable ? "enable" : "disable") + "; display path not ready");
|
||||
}
|
||||
@@ -764,6 +807,91 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
return lastFirmwareCapabilities;
|
||||
}
|
||||
|
||||
public void addAmbientLightListener(FaceclawAmbientLightListener listener) {
|
||||
if (listener != null) {
|
||||
ambientLightListeners.add(listener);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAmbientLightListener(FaceclawAmbientLightListener listener) {
|
||||
if (listener != null) {
|
||||
ambientLightListeners.remove(listener);
|
||||
}
|
||||
}
|
||||
|
||||
private void emitAmbientLight(byte[] body) {
|
||||
if (ambientLightListeners.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
byte[] copy = java.util.Arrays.copyOf(body, body.length);
|
||||
mainHandler.post(() -> {
|
||||
for (FaceclawAmbientLightListener alsListener : ambientLightListeners) {
|
||||
try {
|
||||
alsListener.onAmbientLight(copy);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "ambient light listener failed", t);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Request one CFW ambient-light report (image-handler mode 16 op 0). */
|
||||
public void queryAmbientLight() {
|
||||
synchronized (lock) {
|
||||
enqueueAmbientLightControlLocked(new byte[] { (byte) 16, (byte) 0 }, "als query", false);
|
||||
}
|
||||
interruptibleSleep.interrupt();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start or stop CFW passive light-sensor polling (image-handler mode 16
|
||||
* ops 1/2). While polling, the firmware reads its OPT3001 every intervalMs
|
||||
* (clamped 100..5000 by the firmware), never steps the panel brightness
|
||||
* itself, and pushes a field-105 report when the reading moved by at least
|
||||
* minDelta or heartbeatMs elapsed. bindToLease stops polling automatically
|
||||
* when the Faceclaw framebuffer lease is released or lapses. Starting is
|
||||
* idempotent and re-opens the sensor if the stock firmware closed it.
|
||||
*/
|
||||
public void setAmbientLightPolling(boolean enable, int intervalMs, int minDelta,
|
||||
int heartbeatMs, boolean bindToLease) {
|
||||
byte[] payload = enable
|
||||
? new byte[] {
|
||||
(byte) 16,
|
||||
(byte) 1,
|
||||
(byte) (bindToLease ? 1 : 0),
|
||||
(byte) (intervalMs & 0xff),
|
||||
(byte) ((intervalMs >> 8) & 0xff),
|
||||
(byte) (minDelta & 0xff),
|
||||
(byte) ((minDelta >> 8) & 0xff),
|
||||
(byte) (heartbeatMs & 0xff),
|
||||
(byte) ((heartbeatMs >> 8) & 0xff),
|
||||
}
|
||||
: new byte[] { (byte) 16, (byte) 2 };
|
||||
synchronized (lock) {
|
||||
clearMessagesOfKindLocked("als-control");
|
||||
enqueueAmbientLightControlLocked(payload, "als polling " + (enable ? "start" : "stop"), true);
|
||||
}
|
||||
interruptibleSleep.interrupt();
|
||||
}
|
||||
|
||||
private void enqueueAmbientLightControlLocked(byte[] payload, String label, boolean priority) {
|
||||
if (!running || !sessionReady || shutdownRequested || !fixedLayoutCreated) {
|
||||
logLine("skip " + label + "; display path not ready");
|
||||
return;
|
||||
}
|
||||
OutboundMessage message = messageBuilder.imagePayload(
|
||||
"als-control",
|
||||
DASHBOARD_TILE,
|
||||
nextMapSessionId(),
|
||||
payload,
|
||||
label,
|
||||
connectionOptions.sendImagesToLeft);
|
||||
message.onTimeout = () -> logLine(label + " ack timeout");
|
||||
if (priority) pendingMessages.addFirst(message);
|
||||
else pendingMessages.addLast(message);
|
||||
logLine("queue " + label);
|
||||
}
|
||||
|
||||
public void addMicStatusListener(FaceclawMicStatusListener listener) {
|
||||
if (listener != null) {
|
||||
micStatusListeners.add(listener);
|
||||
@@ -851,15 +979,28 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to compass events. Callbacks are delivered on the Looper of
|
||||
* the thread that registered (falling back to the main thread), so app
|
||||
* worker isolates can listen without a cross-thread hop into their JS.
|
||||
*/
|
||||
public void addCompassListener(FaceclawCompassListener listener) {
|
||||
if (listener != null) {
|
||||
compassListeners.add(listener);
|
||||
if (listener == null) {
|
||||
return;
|
||||
}
|
||||
Looper looper = Looper.myLooper();
|
||||
Handler handler = looper != null ? new Handler(looper) : mainHandler;
|
||||
compassSubscriptions.add(new CompassSubscription(listener, handler));
|
||||
}
|
||||
|
||||
public void removeCompassListener(FaceclawCompassListener listener) {
|
||||
if (listener != null) {
|
||||
compassListeners.remove(listener);
|
||||
if (listener == null) {
|
||||
return;
|
||||
}
|
||||
for (CompassSubscription subscription : compassSubscriptions) {
|
||||
if (subscription.listener == listener) {
|
||||
compassSubscriptions.remove(subscription);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1014,6 +1155,16 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
compositor.removeSurface(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dim every surface below zOrder belowZOrder to factor256/256 (see
|
||||
* SurfaceCompositor.setUnderlayDim). Takes effect with the next submitted
|
||||
* frame: the shell always submits its own surface right after changing
|
||||
* this, so no recomposite happens here.
|
||||
*/
|
||||
public void setUnderlayDim(int belowZOrder, int factor256) {
|
||||
compositor.setUnderlayDim(belowZOrder, factor256);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply an update to one compositor surface and submit the recomposited
|
||||
* screen as the desired frame. The update covers the rect (rectX, rectY,
|
||||
@@ -1549,6 +1700,17 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
if (!faceclawWakeNotification
|
||||
&& frame.ok
|
||||
&& frame.sid == BleProtocol.SID_UI_SETTING) {
|
||||
// Mode-17 query notifications; settings READs are handled by
|
||||
// createBatteryQueryMessageLocked so headset/ring update together.
|
||||
if (address.equalsIgnoreCase(rightAddress)
|
||||
&& (frame.flag == BleProtocol.FLAG_NOTIFY || frame.flag == BleProtocol.FLAG_NOTIFY_ALT)) {
|
||||
BleProtocol.RingBatterySnapshot ring = BleProtocol.parseRingBattery(frame.pb);
|
||||
if (ring != null) {
|
||||
ringBattery = ring.battery;
|
||||
ringCharging = ring.charging;
|
||||
emitBatteryState(headsetBattery, headsetCharging);
|
||||
}
|
||||
}
|
||||
// CFW mic status (field 104) rides both standalone pushes and
|
||||
// settings read acks, from each temple on its own link.
|
||||
byte[] micStatus = BleProtocol.parseFaceclawMicStatus(frame.pb);
|
||||
@@ -1556,6 +1718,15 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
emitMicStatus(micStatus, address);
|
||||
}
|
||||
}
|
||||
if (!faceclawWakeNotification
|
||||
&& frame.ok
|
||||
&& frame.sid == BleProtocol.SID_UI_SETTING) {
|
||||
// CFW ambient-light report (field 105) from the master temple.
|
||||
byte[] alsReport = BleProtocol.parseFaceclawAlsReport(frame.pb);
|
||||
if (alsReport != null) {
|
||||
emitAmbientLight(alsReport);
|
||||
}
|
||||
}
|
||||
if (!faceclawWakeNotification
|
||||
&& decodedWearState < 0
|
||||
&& frame.ok
|
||||
@@ -1617,7 +1788,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
emitWearState(decodedWearState > 0);
|
||||
}
|
||||
if (compassEvent != null) {
|
||||
emitCompassEvent(compassEvent.command, compassEvent.headingDegrees);
|
||||
emitCompassEvent(compassEvent);
|
||||
}
|
||||
if (event != null) {
|
||||
if (event.hasImu) {
|
||||
@@ -2093,10 +2264,11 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
}
|
||||
|
||||
if (messageToPrewrite == null && !shutdownRequested && fixedLayoutCreated
|
||||
&& (compassEnabled ? 1 : 0) != compassControlLastSent
|
||||
&& (compassOwners.isEmpty() ? 0 : 1) != compassControlLastSent
|
||||
&& pendingMessages.isEmpty() && inFlightMessages.isEmpty()) {
|
||||
Log.i(TAG, "enqueueing compass " + (compassEnabled ? "enable" : "disable"));
|
||||
enqueueCompassControlLocked(false, compassEnabled);
|
||||
boolean wanted = !compassOwners.isEmpty();
|
||||
Log.i(TAG, "enqueueing compass " + (wanted ? "enable" : "disable"));
|
||||
enqueueCompassControlLocked(false, wanted);
|
||||
}
|
||||
|
||||
if (benchmarkActive) {
|
||||
@@ -2435,6 +2607,12 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
message.onAck.run();
|
||||
}
|
||||
consecutiveAckTimeouts = 0;
|
||||
// onAck may have just satisfied a waiter blocked on lock.wait() (e.g.
|
||||
// awaitEvenHubSessionReady polling fixedLayoutCreated/displayedFingerprint
|
||||
// after a create-layout or image ack). Without this, that waiter only
|
||||
// notices on its own up-to-100ms poll tick, adding avoidable latency to
|
||||
// every EvenHub wake. Always called with lock held (see call site).
|
||||
lock.notifyAll();
|
||||
}
|
||||
|
||||
private void logImageUpdateSendLandmarkLocked(OutboundMessage message) {
|
||||
@@ -2462,6 +2640,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
return;
|
||||
}
|
||||
long ackedAtMs = SystemClock.elapsedRealtime();
|
||||
FaceclawBleManager.recordDisplayFrameSent();
|
||||
BleImageOptimizer.ImageUpdateStats stats = imageUpdateStats.remove(message.imageUpdateId);
|
||||
if (stats != null && stats.firstWriteStartedAtMs > 0) {
|
||||
emitFrameMetrics(stats.paintMs, (int) Math.max(0, ackedAtMs - stats.firstWriteStartedAtMs), stats.tileCount);
|
||||
@@ -2557,10 +2736,22 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
logLine("queue firmware debug flags " + (show ? "show" : "hide"));
|
||||
}
|
||||
|
||||
/** Send CFW image-handler mode 10: [10][1] start, [10][0] stop. */
|
||||
/**
|
||||
* Send CFW image-handler mode 10. Enable uses the configurable form
|
||||
* [10][2][interval-ms LE16][minimum-change-degrees LE16]; disable remains [10][0].
|
||||
*/
|
||||
private void enqueueCompassControlLocked(boolean priority, boolean enable) {
|
||||
int sentState = enable ? 1 : 0;
|
||||
byte[] payload = new byte[] { (byte) 10, (byte) sentState };
|
||||
byte[] payload = enable
|
||||
? new byte[] {
|
||||
(byte) 10,
|
||||
(byte) 2,
|
||||
(byte) (COMPASS_REPORT_INTERVAL_MS & 0xff),
|
||||
(byte) ((COMPASS_REPORT_INTERVAL_MS >> 8) & 0xff),
|
||||
(byte) (COMPASS_MIN_CHANGE_DEGREES & 0xff),
|
||||
(byte) ((COMPASS_MIN_CHANGE_DEGREES >> 8) & 0xff),
|
||||
}
|
||||
: new byte[] { (byte) 10, (byte) 0 };
|
||||
OutboundMessage message = messageBuilder.imagePayload(
|
||||
"compass-control",
|
||||
DASHBOARD_TILE,
|
||||
@@ -2824,6 +3015,10 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
private OutboundMessage createBatteryQueryMessageLocked() {
|
||||
OutboundMessage message = messageBuilder.batteryQuery();
|
||||
message.onAck = () -> {
|
||||
BleProtocol.RingBatterySnapshot ring = BleProtocol.parseRingBattery(message.ackPayload);
|
||||
// Old firmware and missing/malformed extensions must clear any prior reading.
|
||||
ringBattery = ring == null ? -1 : ring.battery;
|
||||
ringCharging = ring == null ? -1 : ring.charging;
|
||||
BleProtocol.BatterySnapshot snapshot = BleProtocol.parseSettingsBattery(message.ackPayload);
|
||||
if (snapshot != null) {
|
||||
headsetBattery = snapshot.battery;
|
||||
@@ -3409,6 +3604,8 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
}
|
||||
|
||||
private void resetSessionStateLocked() {
|
||||
ringBattery = -1;
|
||||
ringCharging = -1;
|
||||
sessionReady = false;
|
||||
shutdownRequested = false;
|
||||
fixedLayoutCreated = false;
|
||||
@@ -3504,19 +3701,27 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
});
|
||||
}
|
||||
|
||||
private void emitCompassEvent(int command, int headingDegrees) {
|
||||
if (compassListeners.isEmpty()) {
|
||||
return;
|
||||
private void emitCompassEvent(BleProtocol.CompassEvent event) {
|
||||
if (event.diagnosticFlags >= 0) {
|
||||
String[] sources = { "unknown", "GRV", "GMRV", "RV" };
|
||||
Log.i("FaceclawCompass", "heading=" + event.headingDegrees
|
||||
+ " magneticAccuracy=" + event.magneticAccuracy
|
||||
+ " magneticAnomalies=" + event.magneticAnomalies
|
||||
+ " orientationSource=" + sources[event.orientationSource]
|
||||
+ " flags=0x" + Integer.toHexString(event.diagnosticFlags)
|
||||
+ " sampleTimeMs=" + event.sampleTimeMs);
|
||||
}
|
||||
mainHandler.post(() -> {
|
||||
for (FaceclawCompassListener compassListener : compassListeners) {
|
||||
for (CompassSubscription subscription : compassSubscriptions) {
|
||||
subscription.handler.post(() -> {
|
||||
try {
|
||||
compassListener.onCompassEvent(command, headingDegrees);
|
||||
subscription.listener.onCompassEvent(event.command, event.headingDegrees,
|
||||
event.magneticAccuracy, event.magneticAnomalies, event.orientationSource,
|
||||
event.diagnosticFlags, event.sampleTimeMs);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "listener onCompassEvent failed", t);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void emitSilentMode(boolean silent) {
|
||||
@@ -3568,13 +3773,15 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
}
|
||||
|
||||
private void emitBatteryState(int headsetBattery, int headsetCharging) {
|
||||
final int reportedRingBattery = ringBattery;
|
||||
final int reportedRingCharging = ringCharging;
|
||||
final FaceclawBleCommunicatorListener current = listener;
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
mainHandler.post(() -> {
|
||||
try {
|
||||
current.onBatteryState(headsetBattery, headsetCharging);
|
||||
current.onBatteryState(headsetBattery, headsetCharging, reportedRingBattery, reportedRingCharging);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "listener onBatteryState failed", t);
|
||||
}
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ public interface FaceclawBleCommunicatorListener {
|
||||
void onLog(String line);
|
||||
void onStateChange(String phase, String status);
|
||||
void onRingEvent(String kind, String containerName, int eventType, int eventSource, int systemExitReasonCode, int frameId);
|
||||
void onBatteryState(int headsetBattery, int headsetCharging);
|
||||
void onBatteryState(int headsetBattery, int headsetCharging, int ringBattery, int ringCharging);
|
||||
void onSilentMode(boolean silent);
|
||||
void onWearState(boolean wearing);
|
||||
void onPhoneLockState(boolean locked);
|
||||
|
||||
@@ -21,6 +21,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
public class FaceclawBleManager {
|
||||
@@ -51,6 +52,23 @@ public class FaceclawBleManager {
|
||||
|
||||
private volatile FaceclawBleListener listener;
|
||||
|
||||
// Process-wide outbound-traffic totals, sampled by the phone UI's BLE
|
||||
// bandwidth indicator. Static so counts from every manager instance and
|
||||
// isolate land in the same totals.
|
||||
private static final AtomicLong outboundMessages = new AtomicLong();
|
||||
private static final AtomicLong outboundBytes = new AtomicLong();
|
||||
private static final AtomicLong displayFramesSent = new AtomicLong();
|
||||
|
||||
/** Called by the communicator when a display frame's last message is acked. */
|
||||
public static void recordDisplayFrameSent() {
|
||||
displayFramesSent.incrementAndGet();
|
||||
}
|
||||
|
||||
/** Running totals of outbound BLE traffic since process start: [messages, bytes, display frames]. */
|
||||
public static long[] sampleOutboundTraffic() {
|
||||
return new long[] { outboundMessages.get(), outboundBytes.get(), displayFramesSent.get() };
|
||||
}
|
||||
|
||||
public FaceclawBleManager(Context context) {
|
||||
this.context = context.getApplicationContext();
|
||||
BluetoothManager bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
@@ -250,8 +268,10 @@ public class FaceclawBleManager {
|
||||
if (!startWrite(gatt, characteristic, address, frame, writeType, timeoutMs)) {
|
||||
return false;
|
||||
}
|
||||
outboundBytes.addAndGet(frame != null ? frame.length : 0);
|
||||
}
|
||||
}
|
||||
outboundMessages.incrementAndGet();
|
||||
int totalSize = frames.stream().mapToInt(frame -> frame != null ? frame.length : 0).sum();
|
||||
Log.i(TAG, "writeFrames wrote " + frames.size() + " frames totaling " + totalSize + " bytes in " + (System.currentTimeMillis() - startMs) + "ms");
|
||||
return true;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
/** Receives stock compass heading and calibration notifications on the main thread. */
|
||||
/** Receives stock compass heading and calibration notifications on the thread that subscribed. */
|
||||
public interface FaceclawCompassListener {
|
||||
void onCompassEvent(int command, int headingDegrees);
|
||||
void onCompassEvent(int command, int headingDegrees, int magneticAccuracy, int magneticAnomalies,
|
||||
int orientationSource, int diagnosticFlags, long sampleTimeMs);
|
||||
}
|
||||
+159
-39
@@ -27,9 +27,18 @@ import java.util.concurrent.TimeUnit;
|
||||
* whole lifecycle on a single worker thread. It expects the main app to be
|
||||
* disconnected while it runs (onboarding, before flashing).
|
||||
*
|
||||
* Only the right arm is used: the lenses relay messages to each other, so
|
||||
* anything sent to the right arm reaches both, and acks/events only ever come
|
||||
* from the right arm anyway.
|
||||
* Both arms are connected and security-authenticated up front, even though the
|
||||
* prompt itself only needs the right arm (the lenses relay messages to each
|
||||
* other, and acks/events only ever come from the right arm): on an unbonded
|
||||
* phone the auth exchange is what raises the OS pairing prompt, and doing both
|
||||
* here means both prompts appear at the start rather than one popping up half
|
||||
* way through flashing the second lens. While connected, each arm's battery
|
||||
* level is read (they are independent batteries) so the caller can refuse to
|
||||
* flash on a low charge.
|
||||
*
|
||||
* With `skipPrompt` the on-glasses confirmation is not shown: the flow is just
|
||||
* connect + auth + battery read + result(approved). Used to re-check the
|
||||
* battery after the user has already confirmed once.
|
||||
*/
|
||||
public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
private static final String TAG = "FaceclawFlashPrompt";
|
||||
@@ -44,10 +53,13 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
private static final int HEARTBEAT_INTERVAL_MS = 4_000;
|
||||
private static final int SELECTION_TIMEOUT_MS = 120_000;
|
||||
private static final int CREATE_ACK_TIMEOUT_MS = 3_000;
|
||||
private static final int BATTERY_ACK_TIMEOUT_MS = 3_000;
|
||||
|
||||
private final Context context;
|
||||
private final String rightAddress;
|
||||
private final String leftAddress;
|
||||
private final String warningText;
|
||||
private final boolean skipPrompt;
|
||||
private final FaceclawBleManager bleManager;
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
@@ -61,6 +73,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
private volatile boolean cancelled = false;
|
||||
private volatile boolean finished = false;
|
||||
private volatile boolean rightConnected = false;
|
||||
private volatile boolean leftConnected = false;
|
||||
private volatile boolean rightLost = false;
|
||||
private volatile Boolean approved = null;
|
||||
private volatile ScheduledExecutorService heartbeatExecutor;
|
||||
@@ -68,10 +81,13 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
private int nextMagic = 100;
|
||||
private int nextSeq = 0x40;
|
||||
|
||||
public FaceclawFlashPromptCommunicator(Context context, String rightAddress, String warningText) {
|
||||
public FaceclawFlashPromptCommunicator(
|
||||
Context context, String rightAddress, String leftAddress, String warningText, boolean skipPrompt) {
|
||||
this.context = context.getApplicationContext();
|
||||
this.rightAddress = rightAddress == null ? "" : rightAddress;
|
||||
this.leftAddress = leftAddress == null ? "" : leftAddress;
|
||||
this.warningText = warningText == null ? "" : warningText;
|
||||
this.skipPrompt = skipPrompt;
|
||||
this.bleManager = new FaceclawBleManager(this.context);
|
||||
this.bleManager.setListener(this);
|
||||
}
|
||||
@@ -117,43 +133,85 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
}
|
||||
|
||||
emitState("connecting", "");
|
||||
connectArm(rightAddress);
|
||||
connectArm(rightAddress, "right");
|
||||
rightConnected = true;
|
||||
if (cancelled) {
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
if (!leftAddress.trim().isEmpty()) {
|
||||
connectArm(leftAddress, "left");
|
||||
leftConnected = true;
|
||||
if (cancelled) {
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
emitState("connected", "");
|
||||
bringUpArm(rightAddress);
|
||||
// Auth both arms now (pairing prompts, if any, happen here) before
|
||||
// anything else, so both bonds exist by the time flashing starts.
|
||||
authenticateArm(rightAddress, "right");
|
||||
if (leftConnected) {
|
||||
authenticateArm(leftAddress, "left");
|
||||
}
|
||||
if (cancelled) {
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
sendPrelude(rightAddress);
|
||||
|
||||
startHeartbeat();
|
||||
emitState("prompting", "");
|
||||
if (!skipPrompt) {
|
||||
showPrompt(rightAddress);
|
||||
startHeartbeat();
|
||||
emitState("prompting", "");
|
||||
|
||||
boolean signalled = selectionLatch.await(SELECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
|
||||
stopHeartbeat();
|
||||
selectionLatch.await(SELECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
|
||||
stopHeartbeat();
|
||||
|
||||
if (cancelled) {
|
||||
emitState("cancelled", "");
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
if (approved == null) {
|
||||
if (rightLost) {
|
||||
emitState("disconnected", "Lost connection to the glasses.");
|
||||
} else {
|
||||
emitState("timeout", "No response from the glasses.");
|
||||
}
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
sendShutdown();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
if (!Boolean.TRUE.equals(approved)) {
|
||||
emitResult(false);
|
||||
emitState("result", "declined");
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Approved (or prompt skipped): read each arm's battery while the
|
||||
// links are still up, then report the result.
|
||||
emitState("battery", "");
|
||||
readBatteries();
|
||||
if (cancelled) {
|
||||
emitState("cancelled", "");
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
if (approved != null) {
|
||||
boolean result = Boolean.TRUE.equals(approved);
|
||||
try {
|
||||
sendShutdown();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
emitResult(result);
|
||||
emitState("result", result ? "approved" : "declined");
|
||||
if (rightLost) {
|
||||
emitState("disconnected", "Lost connection to the glasses.");
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
if (rightLost) {
|
||||
emitState("disconnected", "Lost connection to the glasses.");
|
||||
} else {
|
||||
emitState("timeout", "No response from the glasses.");
|
||||
}
|
||||
finished = true;
|
||||
emitResult(true);
|
||||
emitState("result", "approved");
|
||||
teardown();
|
||||
} catch (Exception e) {
|
||||
stopHeartbeat();
|
||||
@@ -165,26 +223,28 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
}
|
||||
}
|
||||
|
||||
private void connectArm(String address) {
|
||||
private void connectArm(String address, String arm) {
|
||||
if (!bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) {
|
||||
throw new IllegalStateException("connect failed: " + address);
|
||||
throw new IllegalStateException("could not connect to the " + arm + " arm (" + address + ")");
|
||||
}
|
||||
bleManager.requestConnectionPriority(address, BluetoothGatt.CONNECTION_PRIORITY_HIGH);
|
||||
bleManager.requestMtu(address, ConnectionOptions.DESIRED_MTU, ConnectionOptions.CONNECT_TIMEOUT_MS);
|
||||
if (!bleManager.discoverServices(address, ConnectionOptions.SERVICES_TIMEOUT_MS)) {
|
||||
throw new IllegalStateException("discoverServices failed: " + address);
|
||||
throw new IllegalStateException("discoverServices failed: " + arm + " arm (" + address + ")");
|
||||
}
|
||||
if (!bleManager.enableNotifications(address, BleProtocol.NOTIFY_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)) {
|
||||
throw new IllegalStateException("enableNotifications failed: " + address);
|
||||
throw new IllegalStateException("enableNotifications failed: " + arm + " arm (" + address + ")");
|
||||
}
|
||||
emitLog("connected right arm");
|
||||
emitLog("connected " + arm + " arm");
|
||||
}
|
||||
|
||||
private void bringUpArm(String address) throws InterruptedException {
|
||||
// 1. Security-auth exchange on sid=0x80: firmware 2.2.9 will not run a
|
||||
// session (and closes the link after ~30 s) without it, and on an
|
||||
// unbonded phone this is what triggers SMP pairing, so it may sit
|
||||
// waiting on an OS pairing prompt.
|
||||
/**
|
||||
* Security-auth exchange on sid=0x80: firmware 2.2.9 will not run a
|
||||
* session (and closes the link after ~30 s) without it, and on an
|
||||
* unbonded phone this is what triggers SMP pairing, so it may sit
|
||||
* waiting on an OS pairing prompt.
|
||||
*/
|
||||
private void authenticateArm(String address, String arm) throws InterruptedException {
|
||||
int authMagic = allocMagic();
|
||||
byte[] authAck = writeAndAwaitAck(
|
||||
address,
|
||||
@@ -195,10 +255,14 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
ConnectionOptions.SECURITY_AUTH_TIMEOUT_MS);
|
||||
if (authAck == null || !BleProtocol.isAuthenticationSuccess(authAck, authMagic)) {
|
||||
throw new IllegalStateException(
|
||||
"could not authenticate with the glasses (" + address
|
||||
"could not authenticate with the " + arm + " arm (" + address
|
||||
+ ") — if Android shows a Bluetooth pairing request, accept it and try again");
|
||||
}
|
||||
// 2. Mandatory session prelude on sid=0x01 (app-launch).
|
||||
emitLog("security auth complete: " + arm + " arm");
|
||||
}
|
||||
|
||||
/** Mandatory session prelude on sid=0x01 (app-launch). Right arm only; it relays. */
|
||||
private void sendPrelude(String address) throws InterruptedException {
|
||||
if (writeAndAwaitAck(
|
||||
address,
|
||||
BleProtocol.PRELUDE_ACK_SID,
|
||||
@@ -208,10 +272,13 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
ConnectionOptions.PRELUDE_TIMEOUT_MS) == null) {
|
||||
throw new IllegalStateException("session prelude not acked: " + address);
|
||||
}
|
||||
// 3. Create the prompt page (warning text + No/Yes list) on sid=0xe0 Cmd=0.
|
||||
// Two attempts: on 2.2.9 the first request sent right after the
|
||||
// prelude can be dropped while the lens emits its own sid-0x80
|
||||
// notifications (observed with the device-info settings read).
|
||||
}
|
||||
|
||||
private void showPrompt(String address) throws InterruptedException {
|
||||
// Create the prompt page (warning text + No/Yes list) on sid=0xe0 Cmd=0.
|
||||
// Two attempts: on 2.2.9 the first request sent right after the
|
||||
// prelude can be dropped while the lens emits its own sid-0x80
|
||||
// notifications (observed with the device-info settings read).
|
||||
byte[] pageAck = null;
|
||||
for (int attempt = 0; attempt < 2 && pageAck == null && !cancelled; attempt++) {
|
||||
int magic = allocMagic();
|
||||
@@ -228,6 +295,42 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
emitLog("prompt page shown on " + address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read each arm's battery via a sid-0x09 settings read on that arm's own
|
||||
* link (the arms have independent batteries and each answers with its
|
||||
* own). An arm that does not answer reports -1; the caller decides what
|
||||
* to do with a partial reading.
|
||||
*/
|
||||
private void readBatteries() throws InterruptedException {
|
||||
int right = rightConnected ? readBattery(rightAddress, "right") : -1;
|
||||
int left = leftConnected ? readBattery(leftAddress, "left") : -1;
|
||||
emitLog("battery R=" + (right < 0 ? "?" : right + "%") + " L=" + (left < 0 ? "?" : left + "%"));
|
||||
emitBattery(right, left);
|
||||
}
|
||||
|
||||
private int readBattery(String address, String arm) throws InterruptedException {
|
||||
for (int attempt = 0; attempt < 2 && !cancelled; attempt++) {
|
||||
int magic = allocMagic();
|
||||
byte[] ack = writeAndAwaitAck(
|
||||
address,
|
||||
BleProtocol.SID_UI_SETTING,
|
||||
BleProtocol.FLAG_REQUEST,
|
||||
magic,
|
||||
BleProtocol.buildSettingsQuery(magic),
|
||||
BATTERY_ACK_TIMEOUT_MS);
|
||||
if (ack == null) {
|
||||
emitLog("battery read attempt " + (attempt + 1) + " unacked: " + arm + " arm");
|
||||
continue;
|
||||
}
|
||||
BleProtocol.BatterySnapshot snapshot = BleProtocol.parseSettingsBattery(ack);
|
||||
if (snapshot != null) {
|
||||
return snapshot.battery;
|
||||
}
|
||||
emitLog("battery read ack had no battery field: " + arm + " arm");
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Write and wait for the matching ack; returns the ack's protobuf (may be empty), or null on timeout/write failure. */
|
||||
private byte[] writeAndAwaitAck(String address, int sid, int flag, int magic, byte[] payload, int timeoutMs)
|
||||
throws InterruptedException {
|
||||
@@ -312,6 +415,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
rightConnected = false;
|
||||
leftConnected = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -371,6 +475,13 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
if (connected) {
|
||||
return;
|
||||
}
|
||||
if (address.equalsIgnoreCase(leftAddress)) {
|
||||
// The prompt itself only needs the right arm; a dropped left link
|
||||
// just means no left battery reading.
|
||||
leftConnected = false;
|
||||
emitLog("left arm disconnected");
|
||||
return;
|
||||
}
|
||||
if (address.equalsIgnoreCase(rightAddress)) {
|
||||
rightConnected = false;
|
||||
synchronized (lock) {
|
||||
@@ -415,6 +526,15 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener {
|
||||
});
|
||||
}
|
||||
|
||||
private void emitBattery(int rightPercent, int leftPercent) {
|
||||
mainHandler.post(() -> {
|
||||
FaceclawFlashPromptListener current = listener;
|
||||
if (current != null) {
|
||||
current.onBattery(rightPercent, leftPercent);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void emitResult(boolean approvedResult) {
|
||||
mainHandler.post(() -> {
|
||||
FaceclawFlashPromptListener current = listener;
|
||||
|
||||
+9
-2
@@ -6,11 +6,18 @@ public interface FaceclawFlashPromptListener {
|
||||
|
||||
/**
|
||||
* Lifecycle updates. `state` is one of: connecting, connected, prompting,
|
||||
* result, cancelled, timeout, disconnected, error. `detail` carries the
|
||||
* battery, result, cancelled, timeout, disconnected, error. `detail` carries the
|
||||
* "approved"/"declined" text for result, or an error/explanation message.
|
||||
*/
|
||||
void onState(String state, String detail);
|
||||
|
||||
/** Fires once the user picks a menu row: true = flash, false = cancel. */
|
||||
/**
|
||||
* Battery percent of each arm, read after the user approved (or right
|
||||
* after auth when the prompt is skipped); -1 when an arm didn't answer.
|
||||
* Always fires before onResult(true).
|
||||
*/
|
||||
void onBattery(int rightPercent, int leftPercent);
|
||||
|
||||
/** Fires once the user picks a menu row (or, with skipPrompt, once the battery is read): true = flash, false = cancel. */
|
||||
void onResult(boolean approved);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import android.location.LocationManager;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
@@ -26,6 +27,14 @@ public final class FaceclawLocationTracker implements LocationListener {
|
||||
private final LocationManager locationManager;
|
||||
private final Handler callbackHandler;
|
||||
|
||||
/**
|
||||
* Only seed from the platform's cached fix when it is this fresh. An older
|
||||
* one is likely wherever the phone was last used (for example the previous
|
||||
* navigation's destination), and guidance built on it is wrong from the
|
||||
* first frame: the route starts there and arrival fires immediately.
|
||||
*/
|
||||
private static final long MAX_SEED_AGE_MS = 60L * 1000L;
|
||||
|
||||
private FaceclawLocationTrackerListener listener;
|
||||
private boolean running;
|
||||
|
||||
@@ -83,11 +92,9 @@ public final class FaceclawLocationTracker implements LocationListener {
|
||||
locationManager.requestLocationUpdates(provider, Math.max(500L, intervalMs), 0f, this,
|
||||
callbackHandler.getLooper());
|
||||
// Seed with the freshest cached fix so the UI has a position
|
||||
// before the first live fix (GPS cold starts can take a while).
|
||||
Location cached = locationManager.getLastKnownLocation(provider);
|
||||
if (cached == null) {
|
||||
cached = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
|
||||
}
|
||||
// before the first live fix (GPS cold starts can take a while),
|
||||
// but only if it's recent enough to still be where the user is.
|
||||
Location cached = freshestCachedLocation(provider);
|
||||
if (cached != null) {
|
||||
deliverLocation(cached);
|
||||
}
|
||||
@@ -100,6 +107,32 @@ public final class FaceclawLocationTracker implements LocationListener {
|
||||
}
|
||||
}
|
||||
|
||||
private Location freshestCachedLocation(String primaryProvider) {
|
||||
Location best = null;
|
||||
for (String provider : new String[] {primaryProvider, LocationManager.NETWORK_PROVIDER,
|
||||
LocationManager.GPS_PROVIDER}) {
|
||||
Location candidate;
|
||||
try {
|
||||
candidate = locationManager.getLastKnownLocation(provider);
|
||||
} catch (Throwable ignored) {
|
||||
continue;
|
||||
}
|
||||
if (candidate == null || ageMs(candidate) > MAX_SEED_AGE_MS) {
|
||||
continue;
|
||||
}
|
||||
if (best == null || candidate.getElapsedRealtimeNanos() > best.getElapsedRealtimeNanos()) {
|
||||
best = candidate;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Age via the monotonic clock, so a wall-clock change can't make an old fix look fresh. */
|
||||
private static long ageMs(Location location) {
|
||||
long ageNanos = SystemClock.elapsedRealtimeNanos() - location.getElapsedRealtimeNanos();
|
||||
return ageNanos / 1_000_000L;
|
||||
}
|
||||
|
||||
private String chooseProvider() {
|
||||
try {
|
||||
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
|
||||
|
||||
@@ -23,6 +23,8 @@ import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class FaceclawMediaController {
|
||||
private final Context appContext;
|
||||
@@ -71,6 +73,7 @@ public class FaceclawMediaController {
|
||||
private volatile FaceclawMediaControllerListener listener;
|
||||
private MediaController activeController;
|
||||
private boolean started;
|
||||
private Set<String> ignoredPackages = new HashSet<>();
|
||||
|
||||
public FaceclawMediaController(Context context) {
|
||||
this.appContext = context.getApplicationContext();
|
||||
@@ -113,6 +116,23 @@ public class FaceclawMediaController {
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply the complete preference set and immediately choose an allowed session. */
|
||||
public void setIgnoredPackagesJson(String packagesJson) {
|
||||
Set<String> packages = new HashSet<>();
|
||||
try {
|
||||
JSONArray array = new JSONArray(packagesJson);
|
||||
for (int i = 0; i < array.length(); i++) packages.add(array.getString(i));
|
||||
} catch (Exception e) {
|
||||
Log.w("FaceclawMedia", "invalid ignored packages", e);
|
||||
return;
|
||||
}
|
||||
synchronized (lock) {
|
||||
if (ignoredPackages.equals(packages)) return;
|
||||
ignoredPackages = packages;
|
||||
refreshActiveControllerLocked(null);
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
synchronized (lock) {
|
||||
if (!started) {
|
||||
@@ -205,11 +225,11 @@ public class FaceclawMediaController {
|
||||
* Album art for the active session's current item, grayscale, scaled to
|
||||
* fit within maxSize x maxSize preserving aspect. Returns a gray packet
|
||||
* (see ImageFileLoader.bitmapToGrayPacket) or an empty array when no art
|
||||
* is available. Cover art is continuous-tone, so it is tone-mapped by
|
||||
* gamma and dithered onto the display's 16 levels rather than rounded
|
||||
* per pixel.
|
||||
* is available. gamma and dither are the photographic tone handling
|
||||
* described on ImageFileLoader.bitmapToGrayPacket; the TS side passes
|
||||
* its shared photo preset.
|
||||
*/
|
||||
public byte[] getAlbumArtGray(int maxSize, float gamma) {
|
||||
public byte[] getAlbumArtGray(int maxSize, float gamma, boolean dither) {
|
||||
Bitmap art;
|
||||
synchronized (lock) {
|
||||
if (activeController == null) {
|
||||
@@ -227,7 +247,7 @@ public class FaceclawMediaController {
|
||||
art = metadata.getBitmap(MediaMetadata.METADATA_KEY_DISPLAY_ICON);
|
||||
}
|
||||
}
|
||||
return ImageFileLoader.bitmapToGrayPacket(art, maxSize, maxSize, gamma, true);
|
||||
return ImageFileLoader.bitmapToGrayPacket(art, maxSize, maxSize, gamma, dither);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -289,6 +309,7 @@ public class FaceclawMediaController {
|
||||
controllers = null;
|
||||
}
|
||||
}
|
||||
emitSessionAppsLocked(controllers);
|
||||
setActiveControllerLocked(chooseController(controllers));
|
||||
emitStateLocked();
|
||||
}
|
||||
@@ -297,8 +318,10 @@ public class FaceclawMediaController {
|
||||
if (controllers == null || controllers.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
MediaController first = controllers.get(0);
|
||||
MediaController first = null;
|
||||
for (MediaController controller : controllers) {
|
||||
if (ignoredPackages.contains(controller.getPackageName())) continue;
|
||||
if (first == null) first = controller;
|
||||
PlaybackState playbackState = controller.getPlaybackState();
|
||||
if (playbackState != null && playbackState.getState() == PlaybackState.STATE_PLAYING) {
|
||||
return controller;
|
||||
@@ -307,6 +330,27 @@ public class FaceclawMediaController {
|
||||
return first;
|
||||
}
|
||||
|
||||
private void emitSessionAppsLocked(List<MediaController> controllers) {
|
||||
FaceclawMediaControllerListener currentListener = listener;
|
||||
if (currentListener == null || controllers == null) return;
|
||||
JSONArray apps = new JSONArray();
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (MediaController controller : controllers) {
|
||||
String packageName = safe(controller.getPackageName());
|
||||
if (packageName.isEmpty() || !seen.add(packageName)) continue;
|
||||
try {
|
||||
JSONObject app = new JSONObject();
|
||||
app.put("packageName", packageName);
|
||||
app.put("appName", getApplicationLabel(packageName));
|
||||
apps.put(app);
|
||||
} catch (Exception e) {
|
||||
Log.w("FaceclawMedia", "session app serialization failed", e);
|
||||
}
|
||||
}
|
||||
String json = apps.toString();
|
||||
mainHandler.post(() -> currentListener.onSessionAppsChanged(json));
|
||||
}
|
||||
|
||||
private void setActiveControllerLocked(MediaController controller) {
|
||||
if (sameController(activeController, controller)) {
|
||||
return;
|
||||
|
||||
+3
@@ -1,6 +1,9 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
public interface FaceclawMediaControllerListener {
|
||||
/** All observed session owners, before filtering or choosing the active player. */
|
||||
void onSessionAppsChanged(String appsJson);
|
||||
|
||||
void onStateChange(
|
||||
String playbackState,
|
||||
String packageName,
|
||||
|
||||
+6
-6
@@ -210,7 +210,7 @@ public class FaceclawMediaNotificationListenerService extends NotificationListen
|
||||
|
||||
public static String getActiveNotificationsJson(int maxNotifications) {
|
||||
FaceclawMediaNotificationListenerService service = activeService;
|
||||
int limit = Math.max(0, Math.min(100, maxNotifications));
|
||||
int limit = Math.max(0, maxNotifications);
|
||||
if (service == null || limit == 0) {
|
||||
return "[]";
|
||||
}
|
||||
@@ -388,11 +388,11 @@ public class FaceclawMediaNotificationListenerService extends NotificationListen
|
||||
if (statusBarNotification == null || statusBarNotification.getNotification() == null) {
|
||||
return false;
|
||||
}
|
||||
// The dashboard's own persistent foreground notification is noise, but
|
||||
// Timer expiry notifications deliberately flow through the same mirror
|
||||
// and modal path as notifications from other Android apps.
|
||||
if (service.getPackageName().equals(statusBarNotification.getPackageName())
|
||||
&& !FaceclawTimerNotifications.isTimerNotification(statusBarNotification)) {
|
||||
// Our own notifications stay out of the mirror: the foreground-service
|
||||
// one is noise, and the Timers app rings on the glasses itself (its
|
||||
// phone notification is for the phone), so mirroring it would stack a
|
||||
// notification modal over the ringing screen.
|
||||
if (service.getPackageName().equals(statusBarNotification.getPackageName())) {
|
||||
return false;
|
||||
}
|
||||
Notification notification = statusBarNotification.getNotification();
|
||||
|
||||
@@ -72,6 +72,11 @@ public final class FaceclawPreviewCompositor {
|
||||
compositor.removeSurface(id);
|
||||
}
|
||||
|
||||
/** Dim every surface below zOrder belowZOrder to factor256/256 (see SurfaceCompositor). */
|
||||
public void setUnderlayDim(int belowZOrder, int factor256) {
|
||||
compositor.setUnderlayDim(belowZOrder, factor256);
|
||||
}
|
||||
|
||||
public void setSurfaceVisible(String id, boolean visible) {
|
||||
compositor.setSurfaceVisible(id, visible);
|
||||
}
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Build;
|
||||
|
||||
import com.tns.NativeScriptActivity;
|
||||
|
||||
/** Android alarm + notification bridge used by the on-glasses Timer app. */
|
||||
public final class FaceclawTimerNotifications {
|
||||
public static final String CHANNEL_ID = "faceclaw-timers";
|
||||
static final String ACTION_EXPIRE = "com.faceclaw.app.action.TIMER_EXPIRE";
|
||||
static final String EXTRA_TIMER_ID = "timerId";
|
||||
static final String EXTRA_DURATION_LABEL = "durationLabel";
|
||||
|
||||
private static final String TIMER_TAG_PREFIX = "faceclaw-timer:";
|
||||
private static final String PREFS_NAME = "faceclaw-timer-notifications";
|
||||
private static final String FIRED_KEY_PREFIX = "fired:";
|
||||
|
||||
private FaceclawTimerNotifications() {}
|
||||
|
||||
/**
|
||||
* Schedule an Android alarm as the durable path. The worker also keeps a
|
||||
* normal JS timeout for prompt delivery while the process is awake.
|
||||
*/
|
||||
public static void schedule(Context context, long timerId, long triggerAtMs, String durationLabel) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
preferences(appContext).edit().putBoolean(firedKey(timerId), false).apply();
|
||||
|
||||
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
|
||||
if (manager == null) {
|
||||
return;
|
||||
}
|
||||
PendingIntent pendingIntent = expiryPendingIntent(appContext, timerId, durationLabel);
|
||||
long triggerAt = Math.max(System.currentTimeMillis(), triggerAtMs);
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !manager.canScheduleExactAlarms()) {
|
||||
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent);
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent);
|
||||
} else {
|
||||
manager.setExact(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent);
|
||||
}
|
||||
} catch (SecurityException ignored) {
|
||||
// Exact-alarm access can be disabled by the user on recent Android.
|
||||
// The inexact alarm remains a durable backup to the worker timeout.
|
||||
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent);
|
||||
}
|
||||
}
|
||||
|
||||
public static void cancel(Context context, long timerId) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
|
||||
if (alarmManager != null) {
|
||||
alarmManager.cancel(expiryPendingIntent(appContext, timerId, ""));
|
||||
}
|
||||
NotificationManager notificationManager =
|
||||
(NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
if (notificationManager != null) {
|
||||
notificationManager.cancel(notificationTag(timerId), notificationId(timerId));
|
||||
}
|
||||
preferences(appContext).edit().remove(firedKey(timerId)).apply();
|
||||
}
|
||||
|
||||
/** Worker-timeout path. Cancels the backup alarm and posts at most once. */
|
||||
public static void fireNow(Context context, long timerId, String durationLabel) {
|
||||
Context appContext = context.getApplicationContext();
|
||||
AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
|
||||
if (alarmManager != null) {
|
||||
alarmManager.cancel(expiryPendingIntent(appContext, timerId, durationLabel));
|
||||
}
|
||||
showExpiredOnce(appContext, timerId, durationLabel);
|
||||
}
|
||||
|
||||
static synchronized void showExpiredOnce(Context context, long timerId, String durationLabel) {
|
||||
SharedPreferences preferences = preferences(context);
|
||||
String firedKey = firedKey(timerId);
|
||||
if (preferences.getBoolean(firedKey, false)) {
|
||||
return;
|
||||
}
|
||||
preferences.edit().putBoolean(firedKey, true).apply();
|
||||
ensureChannel(context);
|
||||
|
||||
Intent launchIntent = new Intent(context, NativeScriptActivity.class);
|
||||
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
int contentFlags = PendingIntent.FLAG_UPDATE_CURRENT;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
contentFlags |= PendingIntent.FLAG_IMMUTABLE;
|
||||
}
|
||||
PendingIntent contentIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
notificationId(timerId),
|
||||
launchIntent,
|
||||
contentFlags
|
||||
);
|
||||
|
||||
Notification.Builder builder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
|
||||
? new Notification.Builder(context, CHANNEL_ID)
|
||||
: new Notification.Builder(context);
|
||||
String label = durationLabel == null || durationLabel.trim().isEmpty() ? "Timer" : durationLabel + " timer";
|
||||
Notification notification = builder
|
||||
.setContentTitle("Timer finished")
|
||||
.setContentText(label + " is up")
|
||||
.setSmallIcon(context.getApplicationInfo().icon)
|
||||
.setContentIntent(contentIntent)
|
||||
.setCategory(Notification.CATEGORY_ALARM)
|
||||
.setAutoCancel(true)
|
||||
.setWhen(System.currentTimeMillis())
|
||||
.setShowWhen(true)
|
||||
.build();
|
||||
|
||||
NotificationManager manager =
|
||||
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
if (manager != null) {
|
||||
manager.notify(notificationTag(timerId), notificationId(timerId), notification);
|
||||
}
|
||||
}
|
||||
|
||||
/** Only Timer notifications from our own package should enter the mirror. */
|
||||
public static boolean isTimerNotification(android.service.notification.StatusBarNotification item) {
|
||||
if (item == null || item.getNotification() == null) {
|
||||
return false;
|
||||
}
|
||||
String tag = item.getTag();
|
||||
if (tag != null && tag.startsWith(TIMER_TAG_PREFIX)) {
|
||||
return true;
|
||||
}
|
||||
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
|
||||
&& CHANNEL_ID.equals(item.getNotification().getChannelId());
|
||||
}
|
||||
|
||||
private static void ensureChannel(Context context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
return;
|
||||
}
|
||||
NotificationChannel channel = new NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Timers",
|
||||
NotificationManager.IMPORTANCE_HIGH
|
||||
);
|
||||
channel.setDescription("Alerts when a Faceclaw timer finishes.");
|
||||
channel.enableVibration(true);
|
||||
NotificationManager manager =
|
||||
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
if (manager != null) {
|
||||
manager.createNotificationChannel(channel);
|
||||
}
|
||||
}
|
||||
|
||||
private static PendingIntent expiryPendingIntent(
|
||||
Context context,
|
||||
long timerId,
|
||||
String durationLabel
|
||||
) {
|
||||
Intent intent = new Intent(context, FaceclawTimerReceiver.class);
|
||||
intent.setAction(ACTION_EXPIRE);
|
||||
intent.putExtra(EXTRA_TIMER_ID, timerId);
|
||||
intent.putExtra(EXTRA_DURATION_LABEL, durationLabel == null ? "" : durationLabel);
|
||||
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags |= PendingIntent.FLAG_IMMUTABLE;
|
||||
}
|
||||
return PendingIntent.getBroadcast(context, notificationId(timerId), intent, flags);
|
||||
}
|
||||
|
||||
private static SharedPreferences preferences(Context context) {
|
||||
return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
private static String firedKey(long timerId) {
|
||||
return FIRED_KEY_PREFIX + timerId;
|
||||
}
|
||||
|
||||
private static String notificationTag(long timerId) {
|
||||
return TIMER_TAG_PREFIX + timerId;
|
||||
}
|
||||
|
||||
private static int notificationId(long timerId) {
|
||||
return (int) (timerId ^ (timerId >>> 32)) & 0x7fffffff;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
/** Receives durable timer alarms even if the NativeScript worker is asleep. */
|
||||
public class FaceclawTimerReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (intent == null || !FaceclawTimerNotifications.ACTION_EXPIRE.equals(intent.getAction())) {
|
||||
return;
|
||||
}
|
||||
long timerId = intent.getLongExtra(FaceclawTimerNotifications.EXTRA_TIMER_ID, 0);
|
||||
if (timerId == 0) {
|
||||
return;
|
||||
}
|
||||
String durationLabel = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_DURATION_LABEL);
|
||||
FaceclawTimerNotifications.showExpiredOnce(context, timerId, durationLabel);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,9 @@ import android.util.Log;
|
||||
* Decodes image files (and bitmaps generally) to the grayscale packet format
|
||||
* used across the TS bridge: [widthLo, widthHi, heightLo, heightHi,
|
||||
* pixels...] with one byte per pixel, row-major, or an empty array on
|
||||
* failure. FaceclawMediaController's album art shares bitmapToGrayPacket.
|
||||
* failure. FaceclawMediaController's album art shares bitmapToGrayPacket;
|
||||
* the TS side (app/native/image-files.ts) owns the shared photo-tone preset
|
||||
* passed as (gamma, dither).
|
||||
*/
|
||||
public final class ImageFileLoader {
|
||||
private static final String TAG = "ImageFileLoader";
|
||||
@@ -17,9 +19,21 @@ public final class ImageFileLoader {
|
||||
|
||||
/**
|
||||
* Decode an image file and downscale it to fit within maxWidth x
|
||||
* maxHeight, preserving aspect ratio and never upscaling.
|
||||
* maxHeight, preserving aspect ratio and never upscaling. Flat
|
||||
* conversion (no tone curve, per-pixel rounding): right for UI raster
|
||||
* such as icons.
|
||||
*/
|
||||
public static byte[] loadGray(String path, int maxWidth, int maxHeight) {
|
||||
return loadGray(path, maxWidth, maxHeight, 1f, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* As above, with the photographic tone handling described on
|
||||
* bitmapToGrayPacket(Bitmap, int, int, float, boolean): use for
|
||||
* continuous-tone images (photos) viewed on the glasses.
|
||||
*/
|
||||
public static byte[] loadGray(
|
||||
String path, int maxWidth, int maxHeight, float gamma, boolean dither) {
|
||||
if (path == null || maxWidth <= 0 || maxHeight <= 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
@@ -43,7 +57,7 @@ public final class ImageFileLoader {
|
||||
if (bitmap == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
return bitmapToGrayPacket(bitmap, maxWidth, maxHeight);
|
||||
return bitmapToGrayPacket(bitmap, maxWidth, maxHeight, gamma, dither);
|
||||
} catch (Exception | OutOfMemoryError e) {
|
||||
Log.w(TAG, "image decode failed: " + path, e);
|
||||
return new byte[0];
|
||||
@@ -56,6 +70,12 @@ public final class ImageFileLoader {
|
||||
* ByteBuffer because NativeScript marshals a JS ArrayBuffer to one.
|
||||
*/
|
||||
public static byte[] loadGrayFromBytes(java.nio.ByteBuffer buffer, int maxWidth, int maxHeight) {
|
||||
return loadGrayFromBytes(buffer, maxWidth, maxHeight, 1f, false);
|
||||
}
|
||||
|
||||
/** As above, with photographic tone handling (see bitmapToGrayPacket). */
|
||||
public static byte[] loadGrayFromBytes(
|
||||
java.nio.ByteBuffer buffer, int maxWidth, int maxHeight, float gamma, boolean dither) {
|
||||
if (buffer == null || maxWidth <= 0 || maxHeight <= 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
@@ -71,7 +91,7 @@ public final class ImageFileLoader {
|
||||
if (bitmap == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
return bitmapToGrayPacket(bitmap, maxWidth, maxHeight);
|
||||
return bitmapToGrayPacket(bitmap, maxWidth, maxHeight, gamma, dither);
|
||||
} catch (Exception | OutOfMemoryError e) {
|
||||
Log.w(TAG, "byte-array image decode failed", e);
|
||||
return new byte[0];
|
||||
|
||||
@@ -161,6 +161,9 @@ public final class SurfaceCompositor {
|
||||
private int screenWidth;
|
||||
private int screenHeight;
|
||||
private boolean blanked;
|
||||
/** See setUnderlayDim: surfaces with zOrder below this are dimmed by underlayDim/256. */
|
||||
private int underlayDimBelowZOrder = Integer.MIN_VALUE;
|
||||
private int underlayDim = 256;
|
||||
private final Map<String, Surface> surfaces = new HashMap<>();
|
||||
private long nextCompositeSeq = 1;
|
||||
|
||||
@@ -216,6 +219,33 @@ public final class SurfaceCompositor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dim every surface whose zOrder is below belowZOrder to factor256/256 of
|
||||
* its brightness (256 = no dimming): how a shell overlay that dims what it
|
||||
* covers (the TS Layer.dimUnderneath) reaches the window surfaces beneath
|
||||
* the shell surface, which the shell's own layer stack cannot paint.
|
||||
* Visible pixels stay at least 1 (the color-key black); glyph and
|
||||
* firmware-text draws keep their cached-draw form with a dimmed value;
|
||||
* image draws leave the composite's draw list (their pixels, already
|
||||
* baked into the surface, dim as raster). Takes effect when the next
|
||||
* frame composites.
|
||||
*/
|
||||
public void setUnderlayDim(int belowZOrder, int factor256) {
|
||||
synchronized (lock) {
|
||||
underlayDimBelowZOrder = belowZOrder;
|
||||
underlayDim = Math.max(0, Math.min(256, factor256));
|
||||
}
|
||||
}
|
||||
|
||||
/** The dim factor (256 = none) that applies to a surface. */
|
||||
private int dimForLocked(Surface surface) {
|
||||
return surface.zOrder < underlayDimBelowZOrder ? underlayDim : 256;
|
||||
}
|
||||
|
||||
private static int dimValue(int value, int dim) {
|
||||
return Math.max(1, (value * dim + 128) >> 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hidden surfaces keep their retained pixels and accept updates, but are
|
||||
* excluded from the composite and its fingerprint (used for background
|
||||
@@ -410,9 +440,12 @@ public final class SurfaceCompositor {
|
||||
for (Surface surface : ordered) {
|
||||
if (!surface.visible) continue;
|
||||
blendLocked(gray, surface);
|
||||
int dim = dimForLocked(surface);
|
||||
for (ScreenDraw draw : surface.draws) {
|
||||
if (dim < 256 && draw.kind == ScreenDraw.KIND_IMAGE) continue;
|
||||
int value = dim < 256 ? dimValue(draw.value, dim) : draw.value;
|
||||
draws.add(new ScreenDraw(draw.kind, draw.fontId, draw.encoding, draw.imageId,
|
||||
draw.x + surface.x, draw.y + surface.y, draw.value,
|
||||
draw.x + surface.x, draw.y + surface.y, value,
|
||||
draw.fwCps, draw.fwDx, draw.fwInk));
|
||||
}
|
||||
fingerprint.append('|').append(surface.id)
|
||||
@@ -421,6 +454,9 @@ public final class SurfaceCompositor {
|
||||
.append('#').append(surface.zOrder)
|
||||
.append(':').append(surface.transparency)
|
||||
.append(':').append(surface.fingerprint);
|
||||
if (dim < 256) {
|
||||
fingerprint.append(":dim").append(dim);
|
||||
}
|
||||
}
|
||||
return new Composite(gray, screenWidth, screenHeight, fingerprint.toString(), nextCompositeSeq++,
|
||||
draws.toArray(new ScreenDraw[0]));
|
||||
@@ -437,10 +473,22 @@ public final class SurfaceCompositor {
|
||||
if (copyWidth <= 0 || copyHeight <= 0) {
|
||||
return;
|
||||
}
|
||||
int dim = dimForLocked(surface);
|
||||
for (int row = 0; row < copyHeight; row++) {
|
||||
int srcOffset = (srcY + row) * surface.width + srcX;
|
||||
int dstOffset = (dstY + row) * screenWidth + dstX;
|
||||
if (surface.transparency == TRANSPARENCY_OPAQUE) {
|
||||
if (dim < 256) {
|
||||
// Dimmed: opaque or color-keyed, 0 stays 0 (black / transparent)
|
||||
// and everything visible scales, never below 1.
|
||||
for (int col = 0; col < copyWidth; col++) {
|
||||
int value = surface.pixels[srcOffset + col] & 0xff;
|
||||
if (value != 0) {
|
||||
gray[dstOffset + col] = (byte) dimValue(value, dim);
|
||||
} else if (surface.transparency == TRANSPARENCY_OPAQUE) {
|
||||
gray[dstOffset + col] = 0;
|
||||
}
|
||||
}
|
||||
} else if (surface.transparency == TRANSPARENCY_OPAQUE) {
|
||||
System.arraycopy(surface.pixels, srcOffset, gray, dstOffset, copyWidth);
|
||||
} else {
|
||||
for (int col = 0; col < copyWidth; col++) {
|
||||
|
||||
@@ -57,6 +57,12 @@ public class BleProtocol {
|
||||
*/
|
||||
public static final int FACECLAW_MIC_CONTROL_FIELD = 103;
|
||||
public static final int FACECLAW_MIC_STATUS_FIELD = 104;
|
||||
/**
|
||||
* CFW als_sensor (EVENCFW/18, caps token als16): ambient-light reports on
|
||||
* settings-channel field 105, 24-byte ['A','L',ver,reason,...] records from
|
||||
* the master temple (decoded in app/native/ambient-light.ts).
|
||||
*/
|
||||
public static final int FACECLAW_ALS_REPORT_FIELD = 105;
|
||||
public static final int FACECLAW_WAKE_OP_ACQUIRE = 1;
|
||||
public static final int FACECLAW_WAKE_OP_RELEASE = 2;
|
||||
public static final int FACECLAW_WAKE_OP_CLAIM = 3;
|
||||
@@ -104,6 +110,8 @@ public class BleProtocol {
|
||||
public static final int EVENT_IMU_DATA_REPORT = 8;
|
||||
public static final int EVENT_RING_LONG_PRESS = 9;
|
||||
public static final int EVENT_RING_LONG_PRESS_RELEASE = 10;
|
||||
// CFW extension: G2 2.2.9 tap-then-hold gesture forwarded to the phone.
|
||||
public static final int EVENT_SHORT_THEN_LONG_PRESS = 11;
|
||||
|
||||
public static final int EVENT_SOURCE_GLASSES_R = 1;
|
||||
public static final int EVENT_SOURCE_RING = 2;
|
||||
@@ -447,6 +455,52 @@ public class BleProtocol {
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the raw CFW ambient-light report from a sid-0x09 frame, or null
|
||||
* when this is an ordinary settings frame. Only the 'A','L',version prelude
|
||||
* is validated here; the fields are decoded on the TS side.
|
||||
*/
|
||||
public static byte[] parseFaceclawAlsReport(byte[] pb) {
|
||||
if (pb == null) {
|
||||
return null;
|
||||
}
|
||||
byte[] body = readFieldBytes(stripTrailingCrc(pb), FACECLAW_ALS_REPORT_FIELD);
|
||||
if (body == null
|
||||
|| body.length < 24
|
||||
|| body[0] != 'A'
|
||||
|| body[1] != 'L'
|
||||
|| (body[2] & 0xff) != 1) {
|
||||
return null;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/** Field 106: RB/version 1/flags/percentage, from CFW ringbat17. */
|
||||
public static RingBatterySnapshot parseRingBattery(byte[] pb) {
|
||||
if (pb == null) return null;
|
||||
byte[] body = readFieldBytes(stripTrailingCrc(pb), 106);
|
||||
if (body == null || body.length != 5 || body[0] != 'R' || body[1] != 'B'
|
||||
|| body[2] != 1) return null;
|
||||
int flags = body[3] & 0xff;
|
||||
int level = body[4] & 0xff;
|
||||
if ((flags & ~7) != 0) return null;
|
||||
if ((flags & 2) != 0) {
|
||||
if ((flags & 1) == 0 || level > 100) return null;
|
||||
return new RingBatterySnapshot(level, (flags & 4) != 0 ? 1 : 0);
|
||||
}
|
||||
if (level != 255 || (flags & 4) != 0) return null;
|
||||
return new RingBatterySnapshot(-1, -1);
|
||||
}
|
||||
|
||||
public static final class RingBatterySnapshot {
|
||||
final int battery;
|
||||
final int charging;
|
||||
RingBatterySnapshot(int battery, int charging) {
|
||||
this.battery = battery;
|
||||
this.charging = charging;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the uint16 wake nonce from a CFW field-102 notification, or -1
|
||||
* when this is an ordinary settings frame.
|
||||
@@ -744,7 +798,23 @@ public class BleProtocol {
|
||||
byte[] compass = readFieldBytes(root, 10);
|
||||
if (compass == null) return null;
|
||||
int heading = readVarintFieldValue(compass, 1, -1);
|
||||
return heading >= 0 ? new CompassEvent(command, heading) : null;
|
||||
if (heading < 0 || heading >= 360) return null;
|
||||
byte[] diagnostic = readFieldBytes(root, 100);
|
||||
if (diagnostic != null && diagnostic.length == 12
|
||||
&& diagnostic[0] == 'C' && diagnostic[1] == 'M' && diagnostic[2] == 1
|
||||
&& diagnostic[7] == 0
|
||||
&& ((diagnostic[3] & 0xff) <= 3 || diagnostic[3] == (byte) 255)
|
||||
&& ((diagnostic[4] & 0xff) <= 2 || diagnostic[4] == (byte) 255)
|
||||
&& (diagnostic[5] & 0xff) <= 3) {
|
||||
long sampleTimeMs = 0;
|
||||
for (int i = 0; i < 4; i++) sampleTimeMs |= (long) (diagnostic[8 + i] & 0xff) << (8 * i);
|
||||
return new CompassEvent(command, heading,
|
||||
diagnostic[3] == (byte) 255 ? -1 : diagnostic[3] & 0xff,
|
||||
diagnostic[4] == (byte) 255 ? -1 : diagnostic[4] & 0xff,
|
||||
diagnostic[5] & 0xff, diagnostic[6] & 0xff, sampleTimeMs);
|
||||
}
|
||||
// Stock/older CFW and unknown extensions still supply usable headings.
|
||||
return new CompassEvent(command, heading);
|
||||
}
|
||||
if (command == NAV_CMD_COMPASS_CALIBRATION_STARTED
|
||||
|| command == NAV_CMD_COMPASS_CALIBRATION_COMPLETE) {
|
||||
@@ -986,10 +1056,23 @@ public class BleProtocol {
|
||||
public static final class CompassEvent {
|
||||
public final int command;
|
||||
public final int headingDegrees;
|
||||
/** -1 means unavailable; source: 0 unknown, 1 GRV, 2 GMRV, 3 RV. */
|
||||
public final int magneticAccuracy, magneticAnomalies, orientationSource, diagnosticFlags;
|
||||
public final long sampleTimeMs;
|
||||
|
||||
CompassEvent(int command, int headingDegrees) {
|
||||
this(command, headingDegrees, -1, -1, -1, -1, -1);
|
||||
}
|
||||
|
||||
CompassEvent(int command, int headingDegrees, int magneticAccuracy, int magneticAnomalies,
|
||||
int orientationSource, int diagnosticFlags, long sampleTimeMs) {
|
||||
this.command = command;
|
||||
this.headingDegrees = headingDegrees;
|
||||
this.magneticAccuracy = magneticAccuracy;
|
||||
this.magneticAnomalies = magneticAnomalies;
|
||||
this.orientationSource = orientationSource;
|
||||
this.diagnosticFlags = diagnosticFlags;
|
||||
this.sampleTimeMs = sampleTimeMs;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user