Initial publishable release
No files matched your search
@@ -0,0 +1,65 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="__PACKAGE__">
|
||||
|
||||
<supports-screens
|
||||
android:smallScreens="true"
|
||||
android:normalScreens="true"
|
||||
android:largeScreens="true"
|
||||
android:xlargeScreens="true"/>
|
||||
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE"/>
|
||||
|
||||
<application
|
||||
android:name="com.tns.NativeScriptApplication"
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme"
|
||||
android:hardwareAccelerated="true">
|
||||
|
||||
<activity
|
||||
android:name="com.tns.NativeScriptActivity"
|
||||
android:label="@string/title_activity_kimera"
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|locale|uiMode"
|
||||
android:theme="@style/LaunchScreenTheme"
|
||||
android:hardwareAccelerated="true"
|
||||
android:launchMode="singleTask"
|
||||
android:exported="true">
|
||||
|
||||
<meta-data android:name="SET_THEME_ON_LAUNCH" android:resource="@style/AppTheme" />
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name="com.tns.ErrorReportActivity"/>
|
||||
<service
|
||||
android:name="com.faceclaw.app.FaceclawForegroundService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="connectedDevice" />
|
||||
<service
|
||||
android:name="com.faceclaw.app.FaceclawMediaNotificationListenerService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.notification.NotificationListenerService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import android.util.Log;
|
||||
|
||||
public final class BleImageOptimizer {
|
||||
private BleImageOptimizer() {}
|
||||
private static final String TAG = "BleImageOptimizer";
|
||||
|
||||
/**
|
||||
* Split an image into fragments (packets), taking advantage of the fact that each packet can declare
|
||||
* a logical size longer than its byte payload to get free trailing zero-padding.
|
||||
*
|
||||
* Each fragment's logical size stays within maxFragmentSize, while trailing zeros inside that span can
|
||||
* be omitted from the payload.
|
||||
*/
|
||||
public static List<BleProtocol.ImageFragment> planImageFragments(byte[] bmp, int maxFragmentSize) {
|
||||
return planImageFragments(bmp, maxFragmentSize, false);
|
||||
}
|
||||
|
||||
public static List<BleProtocol.ImageFragment> planImageFragments(
|
||||
byte[] bmp,
|
||||
int maxFragmentSize,
|
||||
boolean reserveFinalByte
|
||||
) {
|
||||
if (bmp == null || bmp.length == 0) {
|
||||
return Collections.singletonList(new BleProtocol.ImageFragment(0, new byte[0], 0));
|
||||
}
|
||||
if (maxFragmentSize <= 0) {
|
||||
throw new IllegalArgumentException("maxFragmentSize must be positive");
|
||||
}
|
||||
|
||||
final int bulkLength = reserveFinalByte ? bmp.length - 1 : bmp.length;
|
||||
final int fragmentCount = ((bulkLength + maxFragmentSize - 1) / maxFragmentSize)
|
||||
+ (bulkLength < bmp.length ? 1 : 0);
|
||||
final List<BleProtocol.ImageFragment> fragments = new ArrayList<>(fragmentCount);
|
||||
for (int index = 0; index * maxFragmentSize < bulkLength; index++) {
|
||||
int start = index * maxFragmentSize;
|
||||
int end = Math.min(start + maxFragmentSize, bulkLength);
|
||||
fragments.add(buildFragment(index, bmp, start, end));
|
||||
}
|
||||
if (bulkLength < bmp.length) {
|
||||
fragments.add(new BleProtocol.ImageFragment(
|
||||
fragments.size(),
|
||||
Arrays.copyOfRange(bmp, bulkLength, bmp.length),
|
||||
bmp.length - bulkLength
|
||||
));
|
||||
}
|
||||
Log.i(TAG, "planImageFragments: fragments=" + fragments.size() + ", bmp.length=" + bmp.length + ", maxFragmentSize=" + maxFragmentSize);
|
||||
return fragments;
|
||||
}
|
||||
|
||||
private static BleProtocol.ImageFragment buildFragment(int index, byte[] bmp, int start, int end) {
|
||||
int dataEnd = end;
|
||||
while (dataEnd > start && bmp[dataEnd - 1] == 0) {
|
||||
dataEnd -= 1;
|
||||
}
|
||||
if (dataEnd == start) {
|
||||
return new BleProtocol.ImageFragment(index, new byte[0], end - start);
|
||||
}
|
||||
return new BleProtocol.ImageFragment(
|
||||
index,
|
||||
Arrays.copyOfRange(bmp, start, dataEnd),
|
||||
end - start
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* BleProtocol: Functions for generating and parsing messages when speaking to
|
||||
* the Even Realities G2. Does _not_ include code for actually sending anything;
|
||||
* for that, see FaceclawBleCommunicator.
|
||||
*
|
||||
* Most message formats are protobufs. For schemas, check g2-kit-unofficial.
|
||||
*/
|
||||
public class BleProtocol {
|
||||
public static final String WRITE_CHAR_UUID = "00002760-08c2-11e1-9073-0e8ac72e5401";
|
||||
public static final String NOTIFY_CHAR_UUID = "00002760-08c2-11e1-9073-0e8ac72e5402";
|
||||
public static final String RENDER_NOTIFY_UUID = "00002760-08c2-11e1-9073-0e8ac72e6402";
|
||||
|
||||
public static final byte[] PRELUDE_F5872 = new byte[] {
|
||||
(byte) 0xaa, 0x21, (byte) 0x92, 0x13, 0x01, 0x01, 0x01, 0x20,
|
||||
0x08, 0x02, 0x10, (byte) 0x9c, 0x01, 0x22, 0x0a, 0x1a,
|
||||
0x08, 0x12, 0x06, 0x12, 0x04, 0x08, 0x00, 0x10, 0x00,
|
||||
(byte) 0xa1, 0x42
|
||||
};
|
||||
|
||||
public static final int PRELUDE_ACK_SID = 0x01;
|
||||
public static final int PRELUDE_ACK_MAGIC = 156;
|
||||
public static final int SID_EVENHUB = 0xe0;
|
||||
public static final int SID_UI_SETTING = 0x09;
|
||||
public static final int FLAG_REQUEST = 0x20;
|
||||
public static final int FLAG_NOTIFY = 0x01;
|
||||
public static final int FLAG_NOTIFY_ALT = 0x06;
|
||||
|
||||
public static final int EVENT_CLICK = 0;
|
||||
public static final int EVENT_SCROLL_TOP = 1;
|
||||
public static final int EVENT_SCROLL_BOTTOM = 2;
|
||||
public static final int EVENT_DOUBLE_CLICK = 3;
|
||||
public static final int EVENT_FOREGROUND_ENTER = 4;
|
||||
public static final int EVENT_FOREGROUND_EXIT = 5;
|
||||
public static final int EVENT_ABNORMAL_EXIT = 6;
|
||||
public static final int EVENT_SYSTEM_EXIT = 7;
|
||||
|
||||
public static final UUID CCCD_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
|
||||
|
||||
public static List<byte[]> framePb(byte[] pb, int sid, int flag, int seq) {
|
||||
int chunkSize = 232;
|
||||
byte[] crc = crcBytesLe(pb);
|
||||
int totalWithCrc = pb.length + 2;
|
||||
int totalFrags = Math.max(1, (int) Math.ceil(totalWithCrc / (double) chunkSize));
|
||||
List<byte[]> frames = new ArrayList<>(totalFrags);
|
||||
int offset = 0;
|
||||
for (int i = 0; i < totalFrags; i++) {
|
||||
boolean isLast = i == totalFrags - 1;
|
||||
byte[] chunk;
|
||||
if (isLast) {
|
||||
int remaining = pb.length - offset;
|
||||
chunk = new byte[remaining + 2];
|
||||
System.arraycopy(pb, offset, chunk, 0, remaining);
|
||||
System.arraycopy(crc, 0, chunk, remaining, 2);
|
||||
} else {
|
||||
chunk = Arrays.copyOfRange(pb, offset, offset + chunkSize);
|
||||
offset += chunkSize;
|
||||
}
|
||||
if (isLast) {
|
||||
offset = pb.length;
|
||||
}
|
||||
byte[] frame = new byte[8 + chunk.length];
|
||||
frame[0] = (byte) 0xaa;
|
||||
frame[1] = 0x21;
|
||||
frame[2] = (byte) (seq & 0xff);
|
||||
frame[3] = (byte) (chunk.length & 0xff);
|
||||
frame[4] = (byte) (totalFrags & 0xff);
|
||||
frame[5] = (byte) ((i + 1) & 0xff);
|
||||
frame[6] = (byte) (sid & 0xff);
|
||||
frame[7] = (byte) (flag & 0xff);
|
||||
System.arraycopy(chunk, 0, frame, 8, chunk.length);
|
||||
frames.add(frame);
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
|
||||
public static byte[] buildCreateMixedImagePage(int magic, ImageTileOptions[] tiles) {
|
||||
List<byte[]> innerParts = new ArrayList<>();
|
||||
innerParts.add(encodeVarintField(1, 1 + tiles.length));
|
||||
innerParts.add(encodeMessageField(3, encodeTextObject("dashboard", 1, 0, 0, 576, 288, " ", true)));
|
||||
for (ImageTileOptions tile : tiles) {
|
||||
innerParts.add(encodeMessageField(4, encodeImageObject(tile)));
|
||||
}
|
||||
innerParts.add(encodeVarintField(5, 10000));
|
||||
byte[] inner = concat(innerParts);
|
||||
return wrapEvenHub(0, magic, 3, inner);
|
||||
}
|
||||
|
||||
public static byte[] buildDashboardTextUpgrade(int magic) {
|
||||
List<byte[]> inner = new ArrayList<>();
|
||||
inner.add(encodeVarintField(1, 1));
|
||||
inner.add(encodeStringField(2, "dashboard"));
|
||||
inner.add(encodeVarintField(3, 0));
|
||||
inner.add(encodeVarintField(4, 1));
|
||||
inner.add(encodeStringField(5, " "));
|
||||
return wrapEvenHub(5, magic, 9, concat(inner));
|
||||
}
|
||||
|
||||
public static byte[] buildImageRawData(ImageTileOptions tile, int sessionId, int totalSize, ImageFragment fragment, int magic) {
|
||||
List<byte[]> inner = new ArrayList<>();
|
||||
inner.add(encodeVarintField(1, tile.containerId));
|
||||
inner.add(encodeStringField(2, tile.name));
|
||||
inner.add(encodeVarintField(3, sessionId));
|
||||
inner.add(encodeVarintField(4, totalSize));
|
||||
inner.add(encodeVarintField(5, 0));
|
||||
inner.add(encodeVarintField(6, fragment.index));
|
||||
inner.add(encodeVarintField(7, fragment.size));
|
||||
inner.add(encodeBytesField(8, fragment.data));
|
||||
return wrapEvenHub(3, magic, 5, concat(inner));
|
||||
}
|
||||
|
||||
public static byte[] buildHeartbeat(int magic) {
|
||||
return wrapEvenHub(12, magic, 14, encodeVarintField(1, 0));
|
||||
}
|
||||
|
||||
public static byte[] buildShutdown(int magic, int exitMode) {
|
||||
return wrapEvenHub(9, magic, 11, encodeVarintField(1, exitMode));
|
||||
}
|
||||
|
||||
public static byte[] buildSettingsQuery(int magic) {
|
||||
byte[] request = encodeVarintField(1, 1);
|
||||
return concat(CollectionUtils.listOf(
|
||||
encodeVarintField(1, 2),
|
||||
encodeVarintField(2, magic),
|
||||
encodeMessageField(4, request)
|
||||
));
|
||||
}
|
||||
|
||||
public static BatterySnapshot parseSettingsBattery(byte[] pb) {
|
||||
byte[] root = stripTrailingCrc(pb);
|
||||
byte[] request = readFieldBytes(root, 4);
|
||||
if (request == null) {
|
||||
return null;
|
||||
}
|
||||
int battery = readVarintFieldValue(request, 12, -1);
|
||||
int charging = readVarintFieldValue(request, 13, -1);
|
||||
if (battery < 0) {
|
||||
return null;
|
||||
}
|
||||
return new BatterySnapshot(battery, charging);
|
||||
}
|
||||
|
||||
public static byte[] wrapEvenHub(int cmd, int magic, int innerFieldNumber, byte[] inner) {
|
||||
List<byte[]> parts = new ArrayList<>();
|
||||
parts.add(encodeVarintField(1, cmd));
|
||||
parts.add(encodeVarintField(2, magic));
|
||||
parts.add(encodeMessageField(innerFieldNumber, inner));
|
||||
return concat(parts);
|
||||
}
|
||||
|
||||
public static byte[] encodeTextObject(String name, int containerId, int x, int y, int width, int height, String text, boolean captureEvents) {
|
||||
List<byte[]> parts = new ArrayList<>();
|
||||
parts.add(encodeVarintField(1, x));
|
||||
parts.add(encodeVarintField(2, y));
|
||||
parts.add(encodeVarintField(3, width));
|
||||
parts.add(encodeVarintField(4, height));
|
||||
parts.add(encodeVarintField(9, containerId));
|
||||
parts.add(encodeStringField(10, name));
|
||||
if (captureEvents) {
|
||||
parts.add(encodeVarintField(11, 1));
|
||||
}
|
||||
parts.add(encodeStringField(12, text));
|
||||
return concat(parts);
|
||||
}
|
||||
|
||||
public static byte[] encodeImageObject(ImageTileOptions tile) {
|
||||
List<byte[]> parts = new ArrayList<>();
|
||||
parts.add(encodeVarintField(1, tile.x));
|
||||
parts.add(encodeVarintField(2, tile.y));
|
||||
parts.add(encodeVarintField(3, tile.width));
|
||||
parts.add(encodeVarintField(4, tile.height));
|
||||
parts.add(encodeVarintField(5, tile.containerId));
|
||||
parts.add(encodeStringField(6, tile.name));
|
||||
return concat(parts);
|
||||
}
|
||||
|
||||
private static byte[] concat(List<byte[]> parts) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
for (byte[] part : parts) {
|
||||
if (part != null && part.length > 0) {
|
||||
out.write(part, 0, part.length);
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] encodeVarintField(int fieldNumber, int value) {
|
||||
return concat(CollectionUtils.listOf(encodeKey(fieldNumber, 0), encodeVarint(value)));
|
||||
}
|
||||
|
||||
private static byte[] encodeStringField(int fieldNumber, String value) {
|
||||
byte[] bytes = value == null ? new byte[0] : value.getBytes(StandardCharsets.UTF_8);
|
||||
return concat(CollectionUtils.listOf(encodeKey(fieldNumber, 2), encodeVarint(bytes.length), bytes));
|
||||
}
|
||||
|
||||
private static byte[] encodeBytesField(int fieldNumber, byte[] value) {
|
||||
byte[] bytes = value == null ? new byte[0] : value;
|
||||
return concat(CollectionUtils.listOf(encodeKey(fieldNumber, 2), encodeVarint(bytes.length), bytes));
|
||||
}
|
||||
|
||||
private static byte[] encodeMessageField(int fieldNumber, byte[] value) {
|
||||
byte[] bytes = value == null ? new byte[0] : value;
|
||||
return concat(CollectionUtils.listOf(encodeKey(fieldNumber, 2), encodeVarint(bytes.length), bytes));
|
||||
}
|
||||
|
||||
private static byte[] encodeKey(int fieldNumber, int wireType) {
|
||||
return encodeVarint((fieldNumber << 3) | wireType);
|
||||
}
|
||||
|
||||
private static byte[] encodeVarint(int value) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
int v = value >>> 0;
|
||||
while (v >= 0x80) {
|
||||
out.write((v & 0x7f) | 0x80);
|
||||
v >>>= 7;
|
||||
}
|
||||
out.write(v);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] crcBytesLe(byte[] data) {
|
||||
int crc = 0xffff;
|
||||
for (byte b : data) {
|
||||
crc ^= (b & 0xff) << 8;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
if ((crc & 0x8000) != 0) {
|
||||
crc = ((crc << 1) ^ 0x1021) & 0xffff;
|
||||
} else {
|
||||
crc = (crc << 1) & 0xffff;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new byte[] {(byte) (crc & 0xff), (byte) ((crc >>> 8) & 0xff)};
|
||||
}
|
||||
|
||||
|
||||
public static ParsedFrame parseFrame(byte[] buf) {
|
||||
if (buf == null || buf.length < 10 || buf[0] != (byte) 0xaa || (buf[1] != 0x21 && buf[1] != 0x12)) {
|
||||
return new ParsedFrame(false, 0, 0, new byte[0], -1, -1);
|
||||
}
|
||||
int sid = buf[6] & 0xff;
|
||||
int flag = buf[7] & 0xff;
|
||||
int len = buf[3] & 0xff;
|
||||
int end = Math.min(buf.length, 8 + len);
|
||||
byte[] pb = Arrays.copyOfRange(buf, 8, end);
|
||||
|
||||
int msgType = -1;
|
||||
int msgSeq = -1;
|
||||
int offset = 0;
|
||||
for (int i = 0; i < 8 && offset < pb.length; i++) {
|
||||
VarintResult key = readVarint(pb, offset);
|
||||
if (key == null) {
|
||||
break;
|
||||
}
|
||||
offset = key.next;
|
||||
int tag = key.value >> 3;
|
||||
int wire = key.value & 7;
|
||||
if (wire == 0) {
|
||||
VarintResult value = readVarint(pb, offset);
|
||||
if (value == null) {
|
||||
break;
|
||||
}
|
||||
if (tag == 1) {
|
||||
msgType = value.value;
|
||||
} else if (tag == 2) {
|
||||
msgSeq = value.value;
|
||||
}
|
||||
offset = value.next;
|
||||
} else if (wire == 2) {
|
||||
VarintResult length = readVarint(pb, offset);
|
||||
if (length == null) {
|
||||
break;
|
||||
}
|
||||
offset = length.next + length.value;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
if (msgType >= 0 && msgSeq >= 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new ParsedFrame(true, sid, flag, pb, msgType, msgSeq);
|
||||
}
|
||||
|
||||
public static byte[] stripTrailingCrc(byte[] pb) {
|
||||
if (pb == null || pb.length < 2) {
|
||||
return pb == null ? new byte[0] : pb;
|
||||
}
|
||||
return Arrays.copyOf(pb, pb.length - 2);
|
||||
}
|
||||
|
||||
public static byte[] readFieldBytes(byte[] pb, int fieldNumber) {
|
||||
int offset = 0;
|
||||
while (offset < pb.length) {
|
||||
VarintResult key = readVarint(pb, offset);
|
||||
if (key == null) {
|
||||
return null;
|
||||
}
|
||||
offset = key.next;
|
||||
int field = key.value >> 3;
|
||||
int wire = key.value & 0x07;
|
||||
if (wire == 0) {
|
||||
VarintResult value = readVarint(pb, offset);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
offset = value.next;
|
||||
continue;
|
||||
}
|
||||
if (wire == 1) {
|
||||
offset += 8;
|
||||
continue;
|
||||
}
|
||||
if (wire == 5) {
|
||||
offset += 4;
|
||||
continue;
|
||||
}
|
||||
if (wire != 2) {
|
||||
return null;
|
||||
}
|
||||
VarintResult length = readVarint(pb, offset);
|
||||
if (length == null) {
|
||||
return null;
|
||||
}
|
||||
offset = length.next;
|
||||
int end = offset + length.value;
|
||||
if (end > pb.length) {
|
||||
return null;
|
||||
}
|
||||
byte[] bytes = Arrays.copyOfRange(pb, offset, end);
|
||||
offset = end;
|
||||
if (field == fieldNumber) {
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int readVarintFieldValue(byte[] pb, int fieldNumber, int defaultValue) {
|
||||
int offset = 0;
|
||||
while (offset < pb.length) {
|
||||
VarintResult key = readVarint(pb, offset);
|
||||
if (key == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
offset = key.next;
|
||||
int field = key.value >> 3;
|
||||
int wire = key.value & 0x07;
|
||||
if (wire == 0) {
|
||||
VarintResult value = readVarint(pb, offset);
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
offset = value.next;
|
||||
if (field == fieldNumber) {
|
||||
return value.value;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (wire == 1) {
|
||||
offset += 8;
|
||||
continue;
|
||||
}
|
||||
if (wire == 5) {
|
||||
offset += 4;
|
||||
continue;
|
||||
}
|
||||
if (wire != 2) {
|
||||
return defaultValue;
|
||||
}
|
||||
VarintResult length = readVarint(pb, offset);
|
||||
if (length == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
offset = length.next + length.value;
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
public static String readStringFieldValue(byte[] pb, int fieldNumber) {
|
||||
byte[] bytes = readFieldBytes(pb, fieldNumber);
|
||||
if (bytes == null) {
|
||||
return "";
|
||||
}
|
||||
return new String(bytes, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public static VarintResult readVarint(byte[] pb, int offset) {
|
||||
int value = 0;
|
||||
int shift = 0;
|
||||
int cursor = offset;
|
||||
while (cursor < pb.length) {
|
||||
int b = pb[cursor++] & 0xff;
|
||||
value |= (b & 0x7f) << shift;
|
||||
if ((b & 0x80) == 0) {
|
||||
return new VarintResult(value, cursor);
|
||||
}
|
||||
shift += 7;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static final class ParsedFrame {
|
||||
final boolean ok;
|
||||
final int sid;
|
||||
final int flag;
|
||||
final byte[] pb;
|
||||
final int msgType;
|
||||
final int msgSeq;
|
||||
|
||||
ParsedFrame(boolean ok, int sid, int flag, byte[] pb, int msgType, int msgSeq) {
|
||||
this.ok = ok;
|
||||
this.sid = sid;
|
||||
this.flag = flag;
|
||||
this.pb = pb;
|
||||
this.msgType = msgType;
|
||||
this.msgSeq = msgSeq;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class VarintResult {
|
||||
final int value;
|
||||
final int next;
|
||||
|
||||
VarintResult(int value, int next) {
|
||||
this.value = value;
|
||||
this.next = next;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class ImageTileOptions {
|
||||
final String name;
|
||||
final int containerId;
|
||||
final int x;
|
||||
final int y;
|
||||
final int width;
|
||||
final int height;
|
||||
|
||||
ImageTileOptions(String name, int containerId, int x, int y, int width, int height) {
|
||||
this.name = name;
|
||||
this.containerId = containerId;
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class ImageFragment {
|
||||
final int index;
|
||||
final byte[] data;
|
||||
final int size;
|
||||
|
||||
ImageFragment(int index, byte[] data, int size) {
|
||||
this.index = index;
|
||||
this.data = data;
|
||||
this.size = size;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class BatterySnapshot {
|
||||
final int battery;
|
||||
final int charging;
|
||||
|
||||
BatterySnapshot(int battery, int charging) {
|
||||
this.battery = battery;
|
||||
this.charging = charging;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.faceclaw.app;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CollectionUtils {
|
||||
public static List<byte[]> singletonList(byte[] value) {
|
||||
List<byte[]> list = new ArrayList<>(1);
|
||||
list.add(value);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<byte[]> listOf(byte[] a, byte[] b) {
|
||||
List<byte[]> list = new ArrayList<>(2);
|
||||
list.add(a);
|
||||
list.add(b);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<byte[]> listOf(byte[] a, byte[] b, byte[] c) {
|
||||
List<byte[]> list = new ArrayList<>(3);
|
||||
list.add(a);
|
||||
list.add(b);
|
||||
list.add(c);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
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);
|
||||
void onBatteryState(int headsetBattery, int headsetCharging);
|
||||
void onEvenAppConflict(String message);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
public interface FaceclawBleListener {
|
||||
void onNotification(String address, String characteristicUuid, byte[] data);
|
||||
void onConnectionStateChange(String address, boolean connected);
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothGatt;
|
||||
import android.bluetooth.BluetoothGattCallback;
|
||||
import android.bluetooth.BluetoothGattCharacteristic;
|
||||
import android.bluetooth.BluetoothGattDescriptor;
|
||||
import android.bluetooth.BluetoothGattService;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.BluetoothProfile;
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
public class FaceclawBleManager {
|
||||
private static final String TAG = "FaceclawBle";
|
||||
private static final int[] WRITE_RETRY_DELAYS_MS = new int[] {4, 8, 12, 20, 35, 100, 200};
|
||||
|
||||
private final Context context;
|
||||
private final BluetoothAdapter bluetoothAdapter;
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private final ConcurrentHashMap<String, BluetoothGatt> gattClients = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object> writeLocks = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> connectLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Boolean> connectResults = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> servicesLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Integer> servicesStatuses = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> mtuLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Integer> mtuStatuses = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> descriptorLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Integer> descriptorStatuses = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> writeLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Integer> writeStatuses = new ConcurrentHashMap<>();
|
||||
|
||||
private volatile FaceclawBleListener listener;
|
||||
|
||||
public FaceclawBleManager(Context context) {
|
||||
this.context = context.getApplicationContext();
|
||||
BluetoothManager bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (bluetoothManager == null || bluetoothManager.getAdapter() == null) {
|
||||
throw new IllegalStateException("Bluetooth adapter unavailable");
|
||||
}
|
||||
this.bluetoothAdapter = bluetoothManager.getAdapter();
|
||||
}
|
||||
|
||||
public void setListener(FaceclawBleListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
public boolean connect(String address, int timeoutMs) {
|
||||
if (address == null || address.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("address is required");
|
||||
}
|
||||
BluetoothGatt existing = gattClients.get(address);
|
||||
if (existing != null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
|
||||
if (device == null) {
|
||||
throw new IllegalArgumentException("remote device not found: " + address);
|
||||
}
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
connectLatches.put(address, latch);
|
||||
connectResults.remove(address);
|
||||
|
||||
BluetoothGatt gatt = runOnMainSync(() -> device.connectGatt(
|
||||
context,
|
||||
false,
|
||||
gattCallback,
|
||||
BluetoothDevice.TRANSPORT_LE,
|
||||
BluetoothDevice.PHY_LE_2M|BluetoothDevice.PHY_LE_1M
|
||||
));
|
||||
if (gatt == null) {
|
||||
connectLatches.remove(address);
|
||||
return false;
|
||||
}
|
||||
gattClients.put(address, gatt);
|
||||
|
||||
if (!awaitLatch(latch, timeoutMs)) {
|
||||
connectLatches.remove(address);
|
||||
connectResults.remove(address);
|
||||
return false;
|
||||
}
|
||||
|
||||
gatt.readPhy();
|
||||
Boolean connected = connectResults.remove(address);
|
||||
connectLatches.remove(address);
|
||||
return Boolean.TRUE.equals(connected);
|
||||
}
|
||||
|
||||
public boolean requestConnectionPriority(String address, int priority) {
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
return runOnMainSync(() -> gatt.requestConnectionPriority(priority));
|
||||
}
|
||||
|
||||
public boolean requestMtu(String address, int mtu, int timeoutMs) {
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
mtuLatches.put(address, latch);
|
||||
mtuStatuses.remove(address);
|
||||
|
||||
boolean started = runOnMainSync(() -> gatt.requestMtu(mtu));
|
||||
if (!started) {
|
||||
mtuLatches.remove(address);
|
||||
return false;
|
||||
}
|
||||
if (!awaitLatch(latch, timeoutMs)) {
|
||||
mtuLatches.remove(address);
|
||||
mtuStatuses.remove(address);
|
||||
return false;
|
||||
}
|
||||
Integer status = mtuStatuses.remove(address);
|
||||
mtuLatches.remove(address);
|
||||
return status != null && status == BluetoothGatt.GATT_SUCCESS;
|
||||
}
|
||||
|
||||
public boolean discoverServices(String address, int timeoutMs) {
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
servicesLatches.put(address, latch);
|
||||
servicesStatuses.remove(address);
|
||||
|
||||
boolean started = runOnMainSync(gatt::discoverServices);
|
||||
if (!started) {
|
||||
servicesLatches.remove(address);
|
||||
return false;
|
||||
}
|
||||
if (!awaitLatch(latch, timeoutMs)) {
|
||||
servicesLatches.remove(address);
|
||||
servicesStatuses.remove(address);
|
||||
return false;
|
||||
}
|
||||
Integer status = servicesStatuses.remove(address);
|
||||
servicesLatches.remove(address);
|
||||
return status != null && status == BluetoothGatt.GATT_SUCCESS;
|
||||
}
|
||||
|
||||
public boolean enableNotifications(String address, String characteristicUuid, boolean enable, int timeoutMs) {
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid);
|
||||
|
||||
boolean notificationSet = runOnMainSync(() -> gatt.setCharacteristicNotification(characteristic, enable));
|
||||
if (!notificationSet) {
|
||||
return false;
|
||||
}
|
||||
|
||||
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(BleProtocol.CCCD_UUID);
|
||||
if (descriptor == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
descriptorLatches.put(address, latch);
|
||||
descriptorStatuses.remove(address);
|
||||
|
||||
descriptor.setValue(enable
|
||||
? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
|
||||
: BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
|
||||
boolean started = runOnMainSync(() -> gatt.writeDescriptor(descriptor));
|
||||
if (!started) {
|
||||
descriptorLatches.remove(address);
|
||||
return false;
|
||||
}
|
||||
if (!awaitLatch(latch, timeoutMs)) {
|
||||
descriptorLatches.remove(address);
|
||||
descriptorStatuses.remove(address);
|
||||
return false;
|
||||
}
|
||||
Integer status = descriptorStatuses.remove(address);
|
||||
descriptorLatches.remove(address);
|
||||
return status != null && status == BluetoothGatt.GATT_SUCCESS;
|
||||
}
|
||||
|
||||
public boolean writeFrames(
|
||||
String address,
|
||||
String characteristicUuid,
|
||||
List<byte[]> frames,
|
||||
int writeType,
|
||||
int timeoutMs
|
||||
) {
|
||||
if (frames == null || frames.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
Log.i(TAG, "Called writeFrames with writeType=" + writeType + ", " + frames.size() + " frames totaling " + frames.stream().mapToInt(frame -> frame != null ? frame.length : 0).sum() + " bytes");
|
||||
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid);
|
||||
|
||||
for (int i = 0; i < frames.size(); i++) {
|
||||
Log.i(TAG, "writeFrames starting frame " + i);
|
||||
byte[] frame = frames.get(i);
|
||||
if (!startWrite(gatt, characteristic, address, frame, writeType, timeoutMs)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean startWrite(
|
||||
BluetoothGatt gatt,
|
||||
BluetoothGattCharacteristic characteristic,
|
||||
String address,
|
||||
byte[] data,
|
||||
int writeType,
|
||||
int timeoutMs
|
||||
) {
|
||||
boolean retry = false;
|
||||
int retryCount = 0;
|
||||
while (true) {
|
||||
long currentTime = System.currentTimeMillis();
|
||||
int result = gatt.writeCharacteristic(characteristic, data, writeType);
|
||||
long timeAsleep = System.currentTimeMillis() - currentTime;
|
||||
//Log.i(TAG, "writeCharacteristic: spent " + timeAsleep + "ms");
|
||||
|
||||
if (result == android.bluetooth.BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY) {
|
||||
if (++retryCount < 25) {
|
||||
try {
|
||||
long currentTime2 = System.currentTimeMillis();
|
||||
Thread.sleep(1);
|
||||
long timeAsleep2 = System.currentTimeMillis() - currentTime2;
|
||||
//Log.i(TAG, "writeCharacteristic: slept for " + timeAsleep2 + "ms");
|
||||
} catch (InterruptedException e) {}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
//Log.i(TAG, "writeCharacteristic with writeType=" + writeType + " result=" + result + " retryCount=" + retryCount);
|
||||
return result == android.bluetooth.BluetoothStatusCodes.SUCCESS;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect(String address) {
|
||||
BluetoothGatt gatt = gattClients.remove(address);
|
||||
if (gatt == null) {
|
||||
return;
|
||||
}
|
||||
runOnMainAsync(() -> {
|
||||
gatt.disconnect();
|
||||
gatt.close();
|
||||
});
|
||||
}
|
||||
|
||||
public void close() {
|
||||
for (String address : gattClients.keySet()) {
|
||||
disconnect(address);
|
||||
}
|
||||
}
|
||||
|
||||
private BluetoothGatt requireGatt(String address) {
|
||||
BluetoothGatt gatt = gattClients.get(address);
|
||||
if (gatt == null) {
|
||||
throw new IllegalStateException("Not connected: " + address);
|
||||
}
|
||||
return gatt;
|
||||
}
|
||||
|
||||
private BluetoothGattCharacteristic requireCharacteristic(BluetoothGatt gatt, String characteristicUuid) {
|
||||
UUID target = UUID.fromString(characteristicUuid);
|
||||
for (BluetoothGattService service : gatt.getServices()) {
|
||||
BluetoothGattCharacteristic characteristic = service.getCharacteristic(target);
|
||||
if (characteristic != null) {
|
||||
return characteristic;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Characteristic not found: " + characteristicUuid);
|
||||
}
|
||||
|
||||
private boolean awaitLatch(CountDownLatch latch, int timeoutMs) {
|
||||
try {
|
||||
return latch.await(timeoutMs, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void runOnMainAsync(Runnable runnable) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
runnable.run();
|
||||
} else {
|
||||
mainHandler.post(runnable);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T runOnMainSync(Callable<T> callable) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
try {
|
||||
return callable.call();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
AtomicReference<T> result = new AtomicReference<>();
|
||||
AtomicReference<RuntimeException> error = new AtomicReference<>();
|
||||
|
||||
mainHandler.post(() -> {
|
||||
try {
|
||||
result.set(callable.call());
|
||||
} catch (Exception e) {
|
||||
error.set(new RuntimeException(e));
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
awaitLatch(latch, 10_000);
|
||||
if (error.get() != null) {
|
||||
throw error.get();
|
||||
}
|
||||
return result.get();
|
||||
}
|
||||
|
||||
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
|
||||
@Override
|
||||
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
|
||||
if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) {
|
||||
connectResults.put(address, true);
|
||||
CountDownLatch latch = connectLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
dispatchConnectionState(address, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
|
||||
connectResults.put(address, false);
|
||||
CountDownLatch latch = connectLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
gattClients.remove(address);
|
||||
writeLocks.remove(address);
|
||||
runOnMainAsync(gatt::close);
|
||||
dispatchConnectionState(address, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
servicesStatuses.put(address, status);
|
||||
CountDownLatch latch = servicesLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
mtuStatuses.put(address, status);
|
||||
CountDownLatch latch = mtuLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
|
||||
Log.i(TAG, "onPhyRead: txPhy=" + txPhy + " rxPhy=" + rxPhy + " status=" + status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
descriptorStatuses.put(address, status);
|
||||
CountDownLatch latch = descriptorLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
writeStatuses.put(address, status);
|
||||
CountDownLatch latch = writeLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value) {
|
||||
Log.i(TAG, "onCharacteristicChanged");
|
||||
dispatchNotification(gatt.getDevice().getAddress(), characteristic.getUuid().toString(), value);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
|
||||
dispatchNotification(gatt.getDevice().getAddress(), characteristic.getUuid().toString(), characteristic.getValue());
|
||||
}
|
||||
};
|
||||
|
||||
private void dispatchConnectionState(String address, boolean connected) {
|
||||
FaceclawBleListener current = listener;
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
runOnMainAsync(() -> current.onConnectionStateChange(address, connected));
|
||||
}
|
||||
|
||||
private void dispatchNotification(String address, String characteristicUuid, byte[] data) {
|
||||
Log.i(TAG, "dispatchNotification");
|
||||
FaceclawBleListener current = listener;
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
byte[] copy = data != null ? data.clone() : new byte[0];
|
||||
runOnMainAsync(() -> current.onNotification(address, characteristicUuid, copy));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.os.Looper;
|
||||
|
||||
public class FaceclawBridge {
|
||||
public static String ping(String value) {
|
||||
return "java-ping:" + value;
|
||||
}
|
||||
|
||||
public static String currentThreadName() {
|
||||
return Thread.currentThread().getName();
|
||||
}
|
||||
|
||||
public static boolean isMainThread() {
|
||||
return Looper.getMainLooper().isCurrentThread();
|
||||
}
|
||||
|
||||
public int add(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
public String describeEnvironment() {
|
||||
return "thread=" + currentThreadName() + " main=" + isMainThread();
|
||||
}
|
||||
|
||||
public String runCallback(String label, Runnable callback) {
|
||||
callback.run();
|
||||
return "java-callback-complete:" + label;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.le.BluetoothLeScanner;
|
||||
import android.bluetooth.le.ScanCallback;
|
||||
import android.bluetooth.le.ScanResult;
|
||||
import android.bluetooth.le.ScanSettings;
|
||||
import android.content.Context;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
public class FaceclawDeviceDiscovery {
|
||||
private static final Pattern RING_NAME = Pattern.compile("^EVEN R1_[0-9A-F]{6}$");
|
||||
private static final Pattern RIGHT_NAME = Pattern.compile("^Even G2_32_R_[0-9A-F]{6}$");
|
||||
private static final Pattern LEFT_NAME = Pattern.compile("^Even G2_32_L_[0-9A-F]{6}$");
|
||||
|
||||
private final Context appContext;
|
||||
private final BluetoothAdapter bluetoothAdapter;
|
||||
|
||||
public FaceclawDeviceDiscovery(Context context) {
|
||||
this.appContext = context.getApplicationContext();
|
||||
BluetoothManager bluetoothManager =
|
||||
(BluetoothManager) this.appContext.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (bluetoothManager == null || bluetoothManager.getAdapter() == null) {
|
||||
throw new IllegalStateException("Bluetooth adapter unavailable");
|
||||
}
|
||||
this.bluetoothAdapter = bluetoothManager.getAdapter();
|
||||
}
|
||||
|
||||
public String getBondedCandidatesJson() {
|
||||
LinkedHashMap<String, CandidateDevice> matches = new LinkedHashMap<>();
|
||||
Set<BluetoothDevice> bonded = bluetoothAdapter.getBondedDevices();
|
||||
if (bonded != null) {
|
||||
for (BluetoothDevice device : bonded) {
|
||||
maybeAddCandidate(matches, device, "paired");
|
||||
}
|
||||
}
|
||||
return encodeCandidates(matches);
|
||||
}
|
||||
|
||||
public String scanCandidatesJson(int timeoutMs) throws InterruptedException {
|
||||
LinkedHashMap<String, CandidateDevice> matches = new LinkedHashMap<>();
|
||||
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
|
||||
if (scanner == null) {
|
||||
return encodeCandidates(matches);
|
||||
}
|
||||
final ScanCallback callback = new ScanCallback() {
|
||||
@Override
|
||||
public void onScanResult(int callbackType, ScanResult result) {
|
||||
if (result == null) {
|
||||
return;
|
||||
}
|
||||
maybeAddCandidate(matches, result.getDevice(), "scan");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBatchScanResults(java.util.List<ScanResult> results) {
|
||||
if (results == null) {
|
||||
return;
|
||||
}
|
||||
for (ScanResult result : results) {
|
||||
if (result != null) {
|
||||
maybeAddCandidate(matches, result.getDevice(), "scan");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
scanner.startScan(
|
||||
null,
|
||||
new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(),
|
||||
callback
|
||||
);
|
||||
try {
|
||||
Thread.sleep(Math.max(500, timeoutMs));
|
||||
} finally {
|
||||
try {
|
||||
scanner.stopScan(callback);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
return encodeCandidates(matches);
|
||||
}
|
||||
|
||||
private void maybeAddCandidate(Map<String, CandidateDevice> matches, BluetoothDevice device, String source) {
|
||||
if (device == null) {
|
||||
return;
|
||||
}
|
||||
String name = device.getName();
|
||||
String role = classifyRole(name);
|
||||
if (role == null) {
|
||||
return;
|
||||
}
|
||||
String address = device.getAddress();
|
||||
if (address == null || address.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
matches.put(address, new CandidateDevice(address, name == null ? "" : name, role, source));
|
||||
}
|
||||
|
||||
private String classifyRole(String name) {
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
if (RIGHT_NAME.matcher(name).matches()) {
|
||||
return "right";
|
||||
}
|
||||
if (LEFT_NAME.matcher(name).matches()) {
|
||||
return "left";
|
||||
}
|
||||
if (RING_NAME.matcher(name).matches()) {
|
||||
return "ring";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String encodeCandidates(Map<String, CandidateDevice> matches) {
|
||||
JSONArray array = new JSONArray();
|
||||
for (CandidateDevice candidate : matches.values()) {
|
||||
JSONObject object = new JSONObject();
|
||||
try {
|
||||
object.put("address", candidate.address);
|
||||
object.put("name", candidate.name);
|
||||
object.put("role", candidate.role);
|
||||
object.put("source", candidate.source);
|
||||
array.put(object);
|
||||
} catch (JSONException ignored) {
|
||||
}
|
||||
}
|
||||
return array.toString();
|
||||
}
|
||||
|
||||
private static final class CandidateDevice {
|
||||
final String address;
|
||||
final String name;
|
||||
final String role;
|
||||
final String source;
|
||||
|
||||
CandidateDevice(String address, String name, String role, String source) {
|
||||
this.address = address;
|
||||
this.name = name;
|
||||
this.role = role;
|
||||
this.source = source;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.provider.Settings;
|
||||
import android.util.Log;
|
||||
|
||||
public final class FaceclawEvenAppDetector {
|
||||
private static final String TAG = "FaceclawEvenApp";
|
||||
|
||||
public static final String EVEN_PACKAGE_NAME = "com.even.sg";
|
||||
public static final String EVEN_NOTIFICATION_TITLE = "Even Notification Service";
|
||||
|
||||
private FaceclawEvenAppDetector() {
|
||||
}
|
||||
|
||||
public static boolean isNotificationAccessEnabled(Context context) {
|
||||
if (context == null) {
|
||||
return false;
|
||||
}
|
||||
Context appContext = context.getApplicationContext();
|
||||
ComponentName listenerComponent = new ComponentName(appContext, FaceclawMediaNotificationListenerService.class);
|
||||
String enabledListeners = Settings.Secure.getString(
|
||||
appContext.getContentResolver(),
|
||||
"enabled_notification_listeners"
|
||||
);
|
||||
if (enabledListeners == null || enabledListeners.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String fullName = listenerComponent.flattenToString();
|
||||
String shortName = listenerComponent.flattenToShortString();
|
||||
return enabledListeners.contains(fullName)
|
||||
|| enabledListeners.contains(shortName)
|
||||
|| enabledListeners.contains(appContext.getPackageName());
|
||||
}
|
||||
|
||||
public static boolean isEvenNotificationActive(Context context) {
|
||||
boolean hasAccess = isNotificationAccessEnabled(context);
|
||||
if (!hasAccess) {
|
||||
Log.i(TAG, "Can't check for Even Realities app notification, permission is not enabled");
|
||||
return false;
|
||||
}
|
||||
boolean hasNotfication = FaceclawMediaNotificationListenerService.hasActiveNotificationTitle(EVEN_NOTIFICATION_TITLE);
|
||||
Log.i(TAG, "isEvenNotificationActive: " + hasNotfication);
|
||||
return hasNotfication;
|
||||
}
|
||||
|
||||
public static void openEvenAppSettings(Context context) {
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
Context appContext = context.getApplicationContext();
|
||||
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
|
||||
intent.setData(Uri.parse("package:" + EVEN_PACKAGE_NAME));
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
try {
|
||||
appContext.startActivity(intent);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to open Even app settings", t);
|
||||
openNotificationAccessSettings(appContext);
|
||||
}
|
||||
}
|
||||
|
||||
public static void openNotificationAccessSettings(Context context) {
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
Context appContext = context.getApplicationContext();
|
||||
Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
try {
|
||||
appContext.startActivity(intent);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to open notification access settings", t);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.IBinder;
|
||||
|
||||
import com.tns.NativeScriptActivity;
|
||||
|
||||
public class FaceclawForegroundService extends Service {
|
||||
public static final String ACTION_START = "com.faceclaw.app.action.START";
|
||||
public static final String ACTION_UPDATE = "com.faceclaw.app.action.UPDATE";
|
||||
public static final String ACTION_STOP = "com.faceclaw.app.action.STOP";
|
||||
public static final String EXTRA_TEXT = "text";
|
||||
|
||||
private static final String CHANNEL_ID = "faceclaw-dashboard";
|
||||
private static final int NOTIFICATION_ID = 4201;
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
String action = intent != null ? intent.getAction() : ACTION_START;
|
||||
String text = intent != null ? intent.getStringExtra(EXTRA_TEXT) : null;
|
||||
|
||||
if (ACTION_STOP.equals(action)) {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE);
|
||||
stopSelf();
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
ensureNotificationChannel();
|
||||
Notification notification = buildNotification(
|
||||
text != null && !text.trim().isEmpty() ? text : "Keeping the dashboard connected"
|
||||
);
|
||||
|
||||
startForeground(NOTIFICATION_ID, notification);
|
||||
|
||||
if (ACTION_UPDATE.equals(action)) {
|
||||
NotificationManager manager = getSystemService(NotificationManager.class);
|
||||
if (manager != null) {
|
||||
manager.notify(NOTIFICATION_ID, notification);
|
||||
}
|
||||
}
|
||||
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
private void ensureNotificationChannel() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
return;
|
||||
}
|
||||
|
||||
NotificationChannel channel = new NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Faceclaw dashboard",
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
);
|
||||
channel.setDescription("Keeps the Faceclaw dashboard connected to the glasses.");
|
||||
|
||||
NotificationManager manager = getSystemService(NotificationManager.class);
|
||||
if (manager != null) {
|
||||
manager.createNotificationChannel(channel);
|
||||
}
|
||||
}
|
||||
|
||||
private Notification buildNotification(String text) {
|
||||
Intent launchIntent = new Intent(this, NativeScriptActivity.class);
|
||||
launchIntent.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;
|
||||
}
|
||||
|
||||
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, launchIntent, flags);
|
||||
|
||||
Notification.Builder builder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
|
||||
? new Notification.Builder(this, CHANNEL_ID)
|
||||
: new Notification.Builder(this);
|
||||
|
||||
return builder
|
||||
.setContentTitle("faceclaw dashboard")
|
||||
.setContentText(text)
|
||||
.setSmallIcon(getApplicationInfo().icon)
|
||||
.setContentIntent(contentIntent)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.media.MediaMetadata;
|
||||
import android.media.session.MediaController;
|
||||
import android.media.session.MediaSessionManager;
|
||||
import android.media.session.PlaybackState;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.provider.Settings;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class FaceclawMediaController {
|
||||
private final Context appContext;
|
||||
private final Object lock = new Object();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private final ComponentName listenerComponent;
|
||||
private final MediaSessionManager sessionManager;
|
||||
|
||||
private final MediaController.Callback controllerCallback = new MediaController.Callback() {
|
||||
@Override
|
||||
public void onPlaybackStateChanged(PlaybackState state) {
|
||||
synchronized (lock) {
|
||||
emitStateLocked();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMetadataChanged(MediaMetadata metadata) {
|
||||
synchronized (lock) {
|
||||
emitStateLocked();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSessionDestroyed() {
|
||||
synchronized (lock) {
|
||||
refreshActiveControllerLocked(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private final MediaSessionManager.OnActiveSessionsChangedListener sessionsChangedListener = controllers -> {
|
||||
synchronized (lock) {
|
||||
refreshActiveControllerLocked(controllers);
|
||||
}
|
||||
};
|
||||
|
||||
private volatile FaceclawMediaControllerListener listener;
|
||||
private MediaController activeController;
|
||||
private boolean started;
|
||||
|
||||
public FaceclawMediaController(Context context) {
|
||||
this.appContext = context.getApplicationContext();
|
||||
this.listenerComponent = new ComponentName(appContext, FaceclawMediaNotificationListenerService.class);
|
||||
this.sessionManager = (MediaSessionManager) appContext.getSystemService(Context.MEDIA_SESSION_SERVICE);
|
||||
}
|
||||
|
||||
public void setListener(FaceclawMediaControllerListener listener) {
|
||||
synchronized (lock) {
|
||||
this.listener = listener;
|
||||
emitStateLocked();
|
||||
}
|
||||
}
|
||||
|
||||
public void start() {
|
||||
synchronized (lock) {
|
||||
if (started) {
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
started = true;
|
||||
if (!isNotificationAccessEnabled()) {
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
if (sessionManager != null) {
|
||||
try {
|
||||
sessionManager.addOnActiveSessionsChangedListener(
|
||||
sessionsChangedListener,
|
||||
listenerComponent,
|
||||
mainHandler
|
||||
);
|
||||
} catch (SecurityException ignored) {
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
}
|
||||
refreshActiveControllerLocked(null);
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
synchronized (lock) {
|
||||
if (!started) {
|
||||
return;
|
||||
}
|
||||
started = false;
|
||||
if (sessionManager != null) {
|
||||
try {
|
||||
sessionManager.removeOnActiveSessionsChangedListener(sessionsChangedListener);
|
||||
} catch (SecurityException ignored) {
|
||||
}
|
||||
}
|
||||
setActiveControllerLocked(null);
|
||||
emitStateLocked();
|
||||
}
|
||||
}
|
||||
|
||||
public void playPause() {
|
||||
synchronized (lock) {
|
||||
if (activeController == null) {
|
||||
return;
|
||||
}
|
||||
PlaybackState playbackState = activeController.getPlaybackState();
|
||||
MediaController.TransportControls controls = activeController.getTransportControls();
|
||||
if (playbackState == null) {
|
||||
controls.play();
|
||||
return;
|
||||
}
|
||||
switch (playbackState.getState()) {
|
||||
case PlaybackState.STATE_PLAYING:
|
||||
case PlaybackState.STATE_BUFFERING:
|
||||
case PlaybackState.STATE_CONNECTING:
|
||||
controls.pause();
|
||||
return;
|
||||
default:
|
||||
controls.play();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void skipNext() {
|
||||
synchronized (lock) {
|
||||
if (activeController != null) {
|
||||
activeController.getTransportControls().skipToNext();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void skipPrevious() {
|
||||
synchronized (lock) {
|
||||
if (activeController != null) {
|
||||
activeController.getTransportControls().skipToPrevious();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void openNotificationAccessSettings() {
|
||||
Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
appContext.startActivity(intent);
|
||||
}
|
||||
|
||||
private void refreshActiveControllerLocked(List<MediaController> controllers) {
|
||||
if (!started) {
|
||||
setActiveControllerLocked(null);
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
if (!isNotificationAccessEnabled()) {
|
||||
setActiveControllerLocked(null);
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
if (controllers == null && sessionManager != null) {
|
||||
try {
|
||||
controllers = sessionManager.getActiveSessions(listenerComponent);
|
||||
} catch (SecurityException ignored) {
|
||||
controllers = null;
|
||||
}
|
||||
}
|
||||
setActiveControllerLocked(chooseController(controllers));
|
||||
emitStateLocked();
|
||||
}
|
||||
|
||||
private MediaController chooseController(List<MediaController> controllers) {
|
||||
if (controllers == null || controllers.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
MediaController first = controllers.get(0);
|
||||
for (MediaController controller : controllers) {
|
||||
PlaybackState playbackState = controller.getPlaybackState();
|
||||
if (playbackState != null && playbackState.getState() == PlaybackState.STATE_PLAYING) {
|
||||
return controller;
|
||||
}
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
private void setActiveControllerLocked(MediaController controller) {
|
||||
if (sameController(activeController, controller)) {
|
||||
return;
|
||||
}
|
||||
if (activeController != null) {
|
||||
activeController.unregisterCallback(controllerCallback);
|
||||
}
|
||||
activeController = controller;
|
||||
if (activeController != null) {
|
||||
activeController.registerCallback(controllerCallback, mainHandler);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean sameController(MediaController a, MediaController b) {
|
||||
if (a == b) {
|
||||
return true;
|
||||
}
|
||||
if (a == null || b == null) {
|
||||
return false;
|
||||
}
|
||||
return a.getSessionToken().equals(b.getSessionToken());
|
||||
}
|
||||
|
||||
private boolean isNotificationAccessEnabled() {
|
||||
String enabledListeners = Settings.Secure.getString(
|
||||
appContext.getContentResolver(),
|
||||
"enabled_notification_listeners"
|
||||
);
|
||||
if (enabledListeners == null || enabledListeners.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String fullName = listenerComponent.flattenToString();
|
||||
String shortName = listenerComponent.flattenToShortString();
|
||||
return enabledListeners.contains(fullName)
|
||||
|| enabledListeners.contains(shortName)
|
||||
|| enabledListeners.contains(appContext.getPackageName());
|
||||
}
|
||||
|
||||
private void emitStateLocked() {
|
||||
FaceclawMediaControllerListener currentListener = listener;
|
||||
if (currentListener == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String playbackState = started ? "idle" : "stopped";
|
||||
String packageName = "";
|
||||
String title = "";
|
||||
String artist = "";
|
||||
String album = "";
|
||||
boolean canPlayPause = false;
|
||||
boolean canSkipNext = false;
|
||||
boolean canSkipPrevious = false;
|
||||
boolean accessEnabled = isNotificationAccessEnabled();
|
||||
String status;
|
||||
|
||||
if (!accessEnabled) {
|
||||
playbackState = "notification-access-required";
|
||||
status = "Notification access required.";
|
||||
} else if (activeController == null) {
|
||||
status = "No active media session.";
|
||||
} else {
|
||||
packageName = safe(activeController.getPackageName());
|
||||
PlaybackState state = activeController.getPlaybackState();
|
||||
MediaMetadata metadata = activeController.getMetadata();
|
||||
playbackState = playbackStateName(state);
|
||||
if (metadata != null) {
|
||||
title = safe(metadata.getString(MediaMetadata.METADATA_KEY_TITLE));
|
||||
artist = safe(metadata.getString(MediaMetadata.METADATA_KEY_ARTIST));
|
||||
album = safe(metadata.getString(MediaMetadata.METADATA_KEY_ALBUM));
|
||||
}
|
||||
long actions = state == null ? 0L : state.getActions();
|
||||
canPlayPause = (actions & PlaybackState.ACTION_PLAY_PAUSE) != 0
|
||||
|| (actions & PlaybackState.ACTION_PLAY) != 0
|
||||
|| (actions & PlaybackState.ACTION_PAUSE) != 0;
|
||||
canSkipNext = (actions & PlaybackState.ACTION_SKIP_TO_NEXT) != 0;
|
||||
canSkipPrevious = (actions & PlaybackState.ACTION_SKIP_TO_PREVIOUS) != 0;
|
||||
status = packageName.isEmpty() ? "Active media session." : "Active session: " + packageName;
|
||||
}
|
||||
|
||||
final String finalPlaybackState = playbackState;
|
||||
final String finalPackageName = packageName;
|
||||
final String finalTitle = title;
|
||||
final String finalArtist = artist;
|
||||
final String finalAlbum = album;
|
||||
final boolean finalCanPlayPause = canPlayPause;
|
||||
final boolean finalCanSkipNext = canSkipNext;
|
||||
final boolean finalCanSkipPrevious = canSkipPrevious;
|
||||
final boolean finalAccessEnabled = accessEnabled;
|
||||
final String finalStatus = status;
|
||||
|
||||
mainHandler.post(() -> currentListener.onStateChange(
|
||||
finalPlaybackState,
|
||||
finalPackageName,
|
||||
finalTitle,
|
||||
finalArtist,
|
||||
finalAlbum,
|
||||
finalCanPlayPause,
|
||||
finalCanSkipNext,
|
||||
finalCanSkipPrevious,
|
||||
finalAccessEnabled,
|
||||
finalStatus
|
||||
));
|
||||
}
|
||||
|
||||
private String playbackStateName(PlaybackState state) {
|
||||
if (state == null) {
|
||||
return "idle";
|
||||
}
|
||||
switch (state.getState()) {
|
||||
case PlaybackState.STATE_PLAYING:
|
||||
return "playing";
|
||||
case PlaybackState.STATE_PAUSED:
|
||||
return "paused";
|
||||
case PlaybackState.STATE_BUFFERING:
|
||||
case PlaybackState.STATE_CONNECTING:
|
||||
return "buffering";
|
||||
case PlaybackState.STATE_STOPPED:
|
||||
return "stopped";
|
||||
default:
|
||||
return "idle";
|
||||
}
|
||||
}
|
||||
|
||||
private String safe(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
public interface FaceclawMediaControllerListener {
|
||||
void onStateChange(
|
||||
String playbackState,
|
||||
String packageName,
|
||||
String title,
|
||||
String artist,
|
||||
String album,
|
||||
boolean canPlayPause,
|
||||
boolean canSkipNext,
|
||||
boolean canSkipPrevious,
|
||||
boolean accessEnabled,
|
||||
String status
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationManager;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.Icon;
|
||||
import android.os.Bundle;
|
||||
import android.service.notification.NotificationListenerService;
|
||||
import android.service.notification.StatusBarNotification;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
public class FaceclawMediaNotificationListenerService extends NotificationListenerService {
|
||||
private static final String TAG = "FaceclawNotify";
|
||||
private static final double NOTIFICATION_ICON_GAMMA = 1.6;
|
||||
|
||||
private static volatile FaceclawMediaNotificationListenerService activeService;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
activeService = this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
if (activeService == this) {
|
||||
activeService = null;
|
||||
}
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onListenerConnected() {
|
||||
activeService = this;
|
||||
super.onListenerConnected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onListenerDisconnected() {
|
||||
if (activeService == this) {
|
||||
activeService = null;
|
||||
}
|
||||
super.onListenerDisconnected();
|
||||
}
|
||||
|
||||
public static boolean hasActiveNotificationTitle(String expectedTitle) {
|
||||
FaceclawMediaNotificationListenerService service = activeService;
|
||||
if (service == null || expectedTitle == null || expectedTitle.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
StatusBarNotification[] notifications;
|
||||
try {
|
||||
notifications = service.getActiveNotifications();
|
||||
} catch (SecurityException e) {
|
||||
Log.w(TAG, "notification access denied while checking active notifications", e);
|
||||
return false;
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to check active notifications", t);
|
||||
return false;
|
||||
}
|
||||
if (notifications == null || notifications.length == 0) {
|
||||
return false;
|
||||
}
|
||||
for (StatusBarNotification notification : notifications) {
|
||||
if (notification == null || notification.getNotification() == null) {
|
||||
continue;
|
||||
}
|
||||
Bundle extras = notification.getNotification().extras;
|
||||
if (extras == null) {
|
||||
continue;
|
||||
}
|
||||
CharSequence title = extras.getCharSequence(Notification.EXTRA_TITLE);
|
||||
if (expectedTitle.contentEquals(title)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static byte[] getActiveNotificationIconGrays(int iconSize, int maxIcons) {
|
||||
FaceclawMediaNotificationListenerService service = activeService;
|
||||
int size = Math.max(1, Math.min(96, iconSize));
|
||||
int limit = Math.max(0, maxIcons);
|
||||
if (service == null || limit == 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
StatusBarNotification[] notifications;
|
||||
try {
|
||||
notifications = service.getActiveNotifications();
|
||||
} catch (SecurityException e) {
|
||||
Log.w(TAG, "notification access denied while reading icons", e);
|
||||
return new byte[0];
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to read notification icons", t);
|
||||
return new byte[0];
|
||||
}
|
||||
if (notifications == null || notifications.length == 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(size * size * Math.min(limit, notifications.length));
|
||||
int emitted = 0;
|
||||
for (StatusBarNotification statusBarNotification : notifications) {
|
||||
if (!shouldShowNotificationIcon(service, statusBarNotification)) {
|
||||
continue;
|
||||
}
|
||||
Drawable drawable = loadNotificationIcon(service, statusBarNotification.getNotification());
|
||||
if (drawable == null) {
|
||||
continue;
|
||||
}
|
||||
appendIconGrayBytes(drawable, size, out);
|
||||
emitted += 1;
|
||||
if (emitted >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static boolean shouldShowNotificationIcon(FaceclawMediaNotificationListenerService service, StatusBarNotification statusBarNotification) {
|
||||
if (statusBarNotification == null || statusBarNotification.getNotification() == null) {
|
||||
return false;
|
||||
}
|
||||
if (service.getPackageName().equals(statusBarNotification.getPackageName())) {
|
||||
return false;
|
||||
}
|
||||
Notification notification = statusBarNotification.getNotification();
|
||||
if ((notification.flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
|
||||
return false;
|
||||
}
|
||||
if (Notification.CATEGORY_TRANSPORT.equals(notification.category)) {
|
||||
return false;
|
||||
}
|
||||
Bundle extras = notification.extras;
|
||||
if (extras != null && extras.containsKey("android.mediaSession")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
NotificationListenerService.RankingMap rankingMap = service.getCurrentRanking();
|
||||
if (rankingMap == null) {
|
||||
return true;
|
||||
}
|
||||
NotificationListenerService.Ranking ranking = new NotificationListenerService.Ranking();
|
||||
if (!rankingMap.getRanking(statusBarNotification.getKey(), ranking)) {
|
||||
return true;
|
||||
}
|
||||
int importance = ranking.getImportance();
|
||||
return importance > NotificationManager.IMPORTANCE_MIN;
|
||||
}
|
||||
|
||||
private static Drawable loadNotificationIcon(FaceclawMediaNotificationListenerService service, Notification notification) {
|
||||
try {
|
||||
Icon smallIcon = notification.getSmallIcon();
|
||||
if (smallIcon != null) {
|
||||
Drawable drawable = smallIcon.loadDrawable(service);
|
||||
if (drawable != null) {
|
||||
return drawable;
|
||||
}
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to load small notification icon", t);
|
||||
}
|
||||
try {
|
||||
Icon largeIcon = notification.getLargeIcon();
|
||||
if (largeIcon != null) {
|
||||
return largeIcon.loadDrawable(service);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to load large notification icon", t);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void appendIconGrayBytes(Drawable drawable, int size, ByteArrayOutputStream out) {
|
||||
Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
|
||||
Canvas canvas = new Canvas(bitmap);
|
||||
drawable.setBounds(0, 0, size, size);
|
||||
drawable.draw(canvas);
|
||||
for (int y = 0; y < size; y++) {
|
||||
for (int x = 0; x < size; x++) {
|
||||
int color = bitmap.getPixel(x, y);
|
||||
int alpha = Color.alpha(color);
|
||||
double grayLinear = (0.2126 * Color.red(color) + 0.7152 * Color.green(color) + 0.0722 * Color.blue(color)) * alpha / (255.0 * 255.0);
|
||||
int gray = (int) Math.round(255.0 * Math.pow(Math.max(0.0, Math.min(1.0, grayLinear)), NOTIFICATION_ICON_GAMMA));
|
||||
out.write(gray & 0xff);
|
||||
}
|
||||
}
|
||||
bitmap.recycle();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.os.SystemClock;
|
||||
|
||||
final class InterruptibleSleep {
|
||||
private final Object lock = new Object();
|
||||
private boolean interrupted;
|
||||
|
||||
boolean sleep(long ms) {
|
||||
long delayMs = Math.max(1, ms);
|
||||
long deadline = SystemClock.elapsedRealtime() + delayMs;
|
||||
synchronized (lock) {
|
||||
interrupted = false;
|
||||
while (!interrupted) {
|
||||
long remaining = deadline - SystemClock.elapsedRealtime();
|
||||
if (remaining <= 0) {
|
||||
interrupted = false;
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
lock.wait(remaining);
|
||||
} catch (InterruptedException ignored) {
|
||||
interrupted = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
interrupted = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void interrupt() {
|
||||
synchronized (lock) {
|
||||
interrupted = true;
|
||||
lock.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 5.0 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
@@ -0,0 +1,8 @@
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:gravity="fill">
|
||||
<item>
|
||||
<bitmap android:gravity="fill" android:src="@drawable/background" />
|
||||
</item>
|
||||
<item>
|
||||
<bitmap android:gravity="center" android:src="@drawable/logo" />
|
||||
</item>
|
||||
</layer-list>
|
||||
|
After Width: | Height: | Size: 5.3 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 9.7 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,15 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<group android:scaleX="0.07382812"
|
||||
android:scaleY="0.07382812"
|
||||
android:translateX="16.2"
|
||||
android:translateY="16.2">
|
||||
<path
|
||||
android:pathData="M843,511.86L843,512.96C843,513.22 842.8,513.43 842.55,513.46C809.18,516.58 783.07,543.69 783.07,577.86L783.07,714.8C783.07,724.37 781.06,733.6 777.43,742.03C767.08,766.1 743.59,783.6 716.27,783.6L647.07,783.6L646.59,783L377.41,445.68L377.41,783.6L307.73,783.6C270.84,783.6 240.93,753.7 240.93,716.8L240.93,577.86C240.93,543.69 214.82,516.58 181.45,513.46C181.2,513.43 181,513.22 181,512.96L181,511.86C181,511.61 181.19,511.4 181.45,511.37C214.69,508.14 240.67,480.35 240.67,446.26L240.67,307.2C240.67,297.91 242.57,289.05 246,281.01C256.18,257.14 279.87,240.39 307.47,240.39L377.13,240.39L377.41,240.74L646.59,578.07L646.59,240.39L716.53,240.39C753.42,240.39 783.33,270.3 783.33,307.2L783.33,446.26C783.33,480.35 809.31,508.14 842.55,511.37C842.81,511.4 843,511.61 843,511.86"
|
||||
android:fillColor="#65ADF1"
|
||||
android:fillType="nonZero"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 3.0 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<resources>
|
||||
<!-- You can override base colors from values/colors.xml here, for example: -->
|
||||
<!-- <color name="ns_accent">#65ADF1</color> -->
|
||||
</resources>
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<resources xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- Application theme -->
|
||||
<style name="AppThemeBase21" parent="AppThemeBase">
|
||||
<!-- Uncomment this to make the app show underneat the status bar -->
|
||||
<!-- <item name="android:windowTranslucentStatus">true</item> -->
|
||||
|
||||
<item name="android:datePickerStyle">@style/SpinnerDatePicker</item>
|
||||
<item name="android:timePickerStyle">@style/SpinnerTimePicker</item>
|
||||
</style>
|
||||
|
||||
<style name="AppTheme" parent="AppThemeBase21">
|
||||
</style>
|
||||
|
||||
<!-- Default style for DatePicker - in spinner mode -->
|
||||
<style name="SpinnerDatePicker" parent="android:Widget.Material.Light.DatePicker">
|
||||
<!-- set the default mode for the date picker (supported values: spinner, calendar) -->
|
||||
<item name="android:datePickerMode">spinner</item>
|
||||
</style>
|
||||
|
||||
<!-- Default style for TimePicker - in spinner mode -->
|
||||
<style name="SpinnerTimePicker" parent="android:Widget.Material.Light.TimePicker">
|
||||
<!-- set the default mode for the time picker (supported values: spinner, clock) -->
|
||||
<item name="android:timePickerMode">spinner</item>
|
||||
</style>
|
||||
|
||||
<style name="NativeScriptToolbarStyle" parent="NativeScriptToolbarStyleBase">
|
||||
<item name="android:elevation">4dp</item>
|
||||
|
||||
<!-- Add padding to the ActionBar - useful when android:windowTranslucentStatus is set to true -->
|
||||
<!-- <item name="android:paddingTop">24dp</item> -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- Application theme -->
|
||||
<style name="AppThemeBase29" parent="AppThemeBase21">
|
||||
|
||||
<!--
|
||||
Disable forced dark mode on newer devices.
|
||||
Enabling this will make your app appear in dark-mode,
|
||||
but the way the app is converted may lead to visual issues
|
||||
-->
|
||||
<item name="android:forceDarkAllowed">false</item>
|
||||
</style>
|
||||
|
||||
<style name="AppTheme" parent="AppThemeBase29">
|
||||
</style>
|
||||
|
||||
</resources>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<resources>
|
||||
<!-- The default color of the ActionBar -->
|
||||
<color name="ns_primary">#F5F5F5</color>
|
||||
|
||||
<!-- (API21+) The color of the status bar and contextual app bars; this is normally a dark version of colorPrimary. -->
|
||||
<color name="ns_primaryDark">#757575</color>
|
||||
|
||||
<!-- The color of UI controls such as check boxes, radio buttons, and edit text boxes. -->
|
||||
<color name="ns_accent">#65ADF1</color>
|
||||
|
||||
<!-- this is unused in the default themes, so we might want to remove it? -->
|
||||
<!-- <color name="ns_blue">#272734</color> -->
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#FFFFFF</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- theme to use FOR launch screen-->
|
||||
<style name="LaunchScreenThemeBase" parent="Theme.AppCompat.Light.NoActionBar">
|
||||
<item name="toolbarStyle">@style/NativeScriptToolbarStyle</item>
|
||||
|
||||
<item name="colorPrimary">@color/ns_primary</item>
|
||||
<item name="colorPrimaryDark">@color/ns_primaryDark</item>
|
||||
<item name="colorAccent">@color/ns_accent</item>
|
||||
|
||||
<item name="android:windowBackground">@drawable/splash_screen</item>
|
||||
|
||||
<item name="android:windowActionBarOverlay">true</item>
|
||||
<item name="android:windowTranslucentStatus">true</item>
|
||||
</style>
|
||||
|
||||
<style name="LaunchScreenTheme" parent="LaunchScreenThemeBase">
|
||||
</style>
|
||||
|
||||
<!-- theme to use AFTER launch screen is loaded-->
|
||||
<style name="AppThemeBase" parent="Theme.AppCompat.Light.NoActionBar">
|
||||
<item name="toolbarStyle">@style/NativeScriptToolbarStyle</item>
|
||||
|
||||
<item name="colorPrimary">@color/ns_primary</item>
|
||||
<item name="colorPrimaryDark">@color/ns_primaryDark</item>
|
||||
<item name="colorAccent">@color/ns_accent</item>
|
||||
</style>
|
||||
|
||||
<style name="AppTheme" parent="AppThemeBase">
|
||||
</style>
|
||||
|
||||
<!-- theme for action-bar -->
|
||||
<style name="NativeScriptToolbarStyleBase" parent="Widget.AppCompat.Toolbar">
|
||||
<item name="android:background">@color/ns_primary</item>
|
||||
<item name="theme">@style/ThemeOverlay.AppCompat.ActionBar</item>
|
||||
<item name="popupTheme">@style/ThemeOverlay.AppCompat</item>
|
||||
</style>
|
||||
|
||||
<style name="NativeScriptToolbarStyle" parent="NativeScriptToolbarStyleBase">
|
||||
</style>
|
||||
</resources>
|
||||