commit 6e442e7faab09bf86aa1ec363e42de81ade989fa Author: James Babcock Date: Sun Apr 26 23:07:54 2026 -0700 Initial publishable release diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..84ba4fa6 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,19 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +charset = utf-8 + +[*.json] +indent_style = space +indent_size = 2 + +[*.js] +indent_style = space +indent_size = 2 + +[*.ts] +indent_style = space +indent_size = 2 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..7b398a03 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# NativeScript +hooks/ +node_modules/ +platforms/ + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# General +.DS_Store +.AppleDouble +.LSOverride +.idea +.cloud +.project +tmp/ +typings/ +.gradle-cursor + +# Visual Studio Code +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000..2a163b84 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["nativescript.nativescript"] +} diff --git a/App_Resources/Android/app.gradle b/App_Resources/Android/app.gradle new file mode 100644 index 00000000..9f60d1a5 --- /dev/null +++ b/App_Resources/Android/app.gradle @@ -0,0 +1,25 @@ +// You can add your native dependencies here +dependencies { +// implementation 'androidx.multidex:multidex:2.0.1' +} + +android { + compileSdkVersion 35 + buildToolsVersion "35" + // ndkVersion "" + + defaultConfig { + minSdkVersion 24 + targetSdkVersion 35 + + // Version Information + versionCode 1 + versionName "1.0.0" + + generatedDensities = [] + } + + aaptOptions { + additionalParameters "--no-version-vectors" + } +} diff --git a/App_Resources/Android/before-plugins.gradle b/App_Resources/Android/before-plugins.gradle new file mode 100644 index 00000000..9faffb81 --- /dev/null +++ b/App_Resources/Android/before-plugins.gradle @@ -0,0 +1,15 @@ +// this configurations is loaded before building plugins, as well as before building +// the app - this is where you can apply global settings and overrides + +project.ext { + // androidXAppCompat = "1.4.1" + // androidXExifInterface = "1.3.3" + // androidXFragment = "1.4.1" + // androidXMaterial = "1.5.0" + // androidXMultidex = "2.0.1" + // androidXTransition = "1.4.1" + // androidXViewPager = "1.0.0" + + // useKotlin = true + // kotlinVersion = "1.6.0" +} diff --git a/App_Resources/Android/src/main/AndroidManifest.xml b/App_Resources/Android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..a3ba9ac0 --- /dev/null +++ b/App_Resources/Android/src/main/AndroidManifest.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/BleImageOptimizer.java b/App_Resources/Android/src/main/java/com/faceclaw/app/BleImageOptimizer.java new file mode 100644 index 00000000..722ea35c --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/BleImageOptimizer.java @@ -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 planImageFragments(byte[] bmp, int maxFragmentSize) { + return planImageFragments(bmp, maxFragmentSize, false); + } + + public static List 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 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 + ); + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/BleProtocol.java b/App_Resources/Android/src/main/java/com/faceclaw/app/BleProtocol.java new file mode 100644 index 00000000..56ad7131 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/BleProtocol.java @@ -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 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 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 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 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 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 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 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 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 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; + } + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/CollectionUtils.java b/App_Resources/Android/src/main/java/com/faceclaw/app/CollectionUtils.java new file mode 100644 index 00000000..c99e29ea --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/CollectionUtils.java @@ -0,0 +1,26 @@ +package com.faceclaw.app; +import java.util.ArrayList; +import java.util.List; + +public class CollectionUtils { + public static List singletonList(byte[] value) { + List list = new ArrayList<>(1); + list.add(value); + return list; + } + + public static List listOf(byte[] a, byte[] b) { + List list = new ArrayList<>(2); + list.add(a); + list.add(b); + return list; + } + + public static List listOf(byte[] a, byte[] b, byte[] c) { + List list = new ArrayList<>(3); + list.add(a); + list.add(b); + list.add(c); + return list; + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java new file mode 100644 index 00000000..b4904b77 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java @@ -0,0 +1,1438 @@ +package com.faceclaw.app; + +import android.annotation.SuppressLint; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.content.Context; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.util.Log; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +@SuppressLint("MissingPermission") +public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { + private static final String TAG = "FaceclawComm"; + + private static final int WRITE_TYPE = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE; + private static final int IMAGE_WRITE_TYPE = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT; + private static final int DESIRED_MTU = 247; + private static final int CONNECTION_PRIORITY_HIGH = BluetoothGatt.CONNECTION_PRIORITY_HIGH; + + private static final int CONNECT_TIMEOUT_MS = 5_000; + private static final int SERVICES_TIMEOUT_MS = 5_000; + private static final int DESCRIPTOR_TIMEOUT_MS = 5_000; + private static final int WRITE_TIMEOUT_MS = 2_000; + private static final int PRELUDE_TIMEOUT_MS = 2_000; + private static final int ACK_TIMEOUT_MS = 2_000; + private static final int HEARTBEAT_INTERVAL_MS = 5_000; + private static final int BATTERY_REFRESH_INTERVAL_MS = 5 * 60_000; + private static final int BATTERY_INPUT_QUIET_MS = 5_000; + private static final int WINDOW_SIZE = 1; + private static final int IMAGE_FRAGMENT_SIZE = 4000; + private static final int IMAGE_RETRY_DELAY_MS = 10_000; + private static final boolean IMAGE_FRAGMENT_NO_ACK = false; + private static final int WARMUP_FRAGMENT_TIMEOUT_MS = 3_000; + private static final int MAX_CONSECUTIVE_ACK_TIMEOUTS = 8; + private static final int EVEN_APP_WRITE_FAILURE_WINDOW_MS = 15_000; + private static final int IDLE_SLEEP_MS = 100; + private static final int RECONNECT_DELAY_MS = 5_000; + + private static final BleProtocol.ImageTileOptions[] DASHBOARD_TILES = new BleProtocol.ImageTileOptions[] { + new BleProtocol.ImageTileOptions("img00", 10, 0, 0, 288, 144), + new BleProtocol.ImageTileOptions("img10", 11, 288, 0, 288, 144), + new BleProtocol.ImageTileOptions("img01", 12, 0, 144, 288, 144), + new BleProtocol.ImageTileOptions("img11", 13, 288, 144, 288, 144) + }; + + private final Context appContext; + private final FaceclawBleManager bleManager; + private final InterruptibleSleep interruptibleSleep = new InterruptibleSleep(); + private final Object lock = new Object(); + private final Handler mainHandler = new Handler(Looper.getMainLooper()); + private final String rightAddress; + private final String leftAddress; + private final String ringAddress; + + private volatile FaceclawBleCommunicatorListener listener; + private volatile Thread workerThread; + private volatile boolean running; + private volatile boolean userDisconnectRequested; + + private String phase = "disconnected"; + private String status = "Disconnected."; + + private boolean rightConnected; + private boolean leftConnected; + private boolean sessionReady; + private boolean fixedLayoutCreated; + private boolean warmedUp; + private boolean shutdownRequested; + private boolean startupProbePending; + + private long reconnectAfterMs; + private long lastAckAtMs; + private long lastIncomingAtMs; + private long lastHeartbeatQueuedAtMs; + private long lastConnectionOrInputAtMs; + private long lastBatteryRefreshAtMs; + private long imageRetryAfterMs; + private long lastSessionReadyAtMs; + private long lastEvenAppConflictAtMs; + private int consecutiveAckTimeouts; + + private final BleMagicPool magicPool = new BleMagicPool(); + private int nextTransportSeq = 0x40; + private int nextMapSessionId = 0; + private int nextImageUpdateId = 1; + private int lastShutdownAckMagic = 0; + private long lastShutdownExitAtMs = 0; + private int headsetBattery = -1; + private int headsetCharging = -1; + + private String displayedFingerprint = ""; + private byte[][] displayedTileBmps = emptyTileSet(); + + private final Object desiredTilesLock = new Object(); + private String desiredFingerprint = ""; + private byte[][] desiredTileBmps = emptyTileSet(); + + private final ArrayDeque pendingMessages = new ArrayDeque<>(); + private final ArrayDeque inFlightMessages = new ArrayDeque<>(); + + public FaceclawBleCommunicator(Context context, String rightAddress, String leftAddress, String ringAddress) { + this.appContext = context.getApplicationContext(); + this.bleManager = new FaceclawBleManager(appContext); + this.bleManager.setListener(this); + this.rightAddress = requireAddress("rightAddress", rightAddress); + this.leftAddress = requireAddress("leftAddress", leftAddress); + this.ringAddress = ringAddress == null ? "" : ringAddress.trim(); + } + + + public void setListener(FaceclawBleCommunicatorListener listener) { + this.listener = listener; + emitState(); + } + + public void start() { + synchronized (lock) { + if (running) { + return; + } + running = true; + userDisconnectRequested = false; + shutdownRequested = false; + workerThread = new Thread(this, "FaceclawBleCommunicator"); + workerThread.start(); + } + } + + public void disconnect() { + Thread threadToJoin; + synchronized (lock) { + userDisconnectRequested = true; + running = false; + phase = "disconnecting"; + status = "Disconnecting..."; + lock.notifyAll(); + threadToJoin = workerThread; + } + interruptibleSleep.interrupt(); + emitState(); + if (threadToJoin != null) { + threadToJoin.interrupt(); + try { + threadToJoin.join(5_000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + synchronized (lock) { + workerThread = null; + phase = "disconnected"; + status = "Disconnected."; + resetSessionStateLocked(); + clearAllMessagesLocked("disconnect"); + } + bleManager.disconnect(rightAddress); + bleManager.disconnect(leftAddress); + bleManager.close(); + emitState(); + } + + public void close() { + disconnect(); + } + + + public void submitDashboardImage(List tileBmps, String fingerprint) { + if (tileBmps == null || tileBmps.size() != DASHBOARD_TILES.length) { + throw new IllegalArgumentException("exactly 4 tile bitmaps are required"); + } + synchronized (desiredTilesLock) { + desiredTileBmps = emptyTileSet(); + for (int i = 0; i < DASHBOARD_TILES.length; i++) { + byte[] bmp = tileBmps.get(i); + desiredTileBmps[i] = bmp == null ? new byte[0] : Arrays.copyOf(bmp, bmp.length); + } + desiredFingerprint = fingerprint == null ? "" : fingerprint; + } + interruptibleSleep.interrupt(); + } + + public void submitDashboardImage4( + byte[] tile0Bmp, + byte[] tile1Bmp, + byte[] tile2Bmp, + byte[] tile3Bmp, + String fingerprint + ) { + synchronized (desiredTilesLock) { + desiredTileBmps = emptyTileSet(); + desiredTileBmps[0] = tile0Bmp == null ? new byte[0] : Arrays.copyOf(tile0Bmp, tile0Bmp.length); + desiredTileBmps[1] = tile1Bmp == null ? new byte[0] : Arrays.copyOf(tile1Bmp, tile1Bmp.length); + desiredTileBmps[2] = tile2Bmp == null ? new byte[0] : Arrays.copyOf(tile2Bmp, tile2Bmp.length); + desiredTileBmps[3] = tile3Bmp == null ? new byte[0] : Arrays.copyOf(tile3Bmp, tile3Bmp.length); + desiredFingerprint = fingerprint == null ? "" : fingerprint; + } + interruptibleSleep.interrupt(); + } + + public boolean sendShutdown(int exitMode) { + int magic; + long startedAtMs = SystemClock.elapsedRealtime(); + synchronized (lock) { + if (!running || !sessionReady) { + logLine("skip shutdown; session not ready"); + return false; + } + shutdownRequested = true; + clearPendingMessagesLocked("shutdown requested"); + magic = nextMagic(); + pendingMessages.addFirst(new OutboundMessage( + "shutdown", + "shutdown mode=" + exitMode, + BleProtocol.SID_EVENHUB, + magic, + BleProtocol.framePb( + BleProtocol.buildShutdown(magic, exitMode), + BleProtocol.SID_EVENHUB, + BleProtocol.FLAG_REQUEST, + nextTransportSeq++ + ), + ACK_TIMEOUT_MS, + displayedFingerprint, + -1, + null + )); + logLine("queue shutdown"); + lock.notifyAll(); + } + interruptibleSleep.interrupt(); + + long ackDeadline = SystemClock.elapsedRealtime() + ACK_TIMEOUT_MS + 500; + synchronized (lock) { + while (running + && sessionReady + && lastShutdownAckMagic != magic + && lastShutdownExitAtMs < startedAtMs + && hasPendingOrInflightMagicLocked(magic)) { + long remaining = ackDeadline - SystemClock.elapsedRealtime(); + if (remaining <= 0) { + break; + } + try { + lock.wait(Math.min(remaining, 100)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + boolean acked = lastShutdownAckMagic == magic; + if (acked) { + long exitDeadline = SystemClock.elapsedRealtime() + ACK_TIMEOUT_MS + 500; + while (running && sessionReady && lastShutdownExitAtMs < startedAtMs) { + long remaining = exitDeadline - SystemClock.elapsedRealtime(); + if (remaining <= 0) { + break; + } + try { + lock.wait(Math.min(remaining, 100)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + } + return acked || lastShutdownExitAtMs >= startedAtMs; + } + } + + + @Override + public void run() { + logLine(String.format(Locale.US, "communicator start R=%s L=%s ring=%s", rightAddress, leftAddress, ringAddress)); + while (true) { + try { + if (!running) { + Log.w(TAG, "Exiting event looop"); + break; + } + if (!sessionReady) { + long now = SystemClock.elapsedRealtime(); + if (now < reconnectAfterMs) { + interruptibleSleep.sleep(Math.min(IDLE_SLEEP_MS, reconnectAfterMs - now)); + continue; + } + Log.w(TAG, "Attempting to connect"); + connectLoopOnce(); + continue; + } + + long sleepMs = driveSession(); + Log.i(TAG, "driveSession returned " + sleepMs + "ms"); + if (sleepMs > 0) { + interruptibleSleep.sleep(sleepMs); + } + } catch (Throwable t) { + logLine("communicator loop error: " + safeMessage(t)); + handleTransportFailure("loop error"); + } + } + logLine("communicator stop"); + } + + @Override + public void onNotification(String address, String characteristicUuid, byte[] data) { + if (address == null || characteristicUuid == null || data == null) { + return; + } + String uuid = characteristicUuid.toLowerCase(Locale.US); + if (!BleProtocol.NOTIFY_CHAR_UUID.equals(uuid)) { + return; + } + Log.i(TAG, "onNotification: address=" + address + " characteristicUuid=" + characteristicUuid + " data.length=" + data.length); + BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data); + AsyncEvent event = null; + synchronized (lock) { + lastIncomingAtMs = SystemClock.elapsedRealtime(); + if (frame.ok && frame.msgSeq >= 0 && frame.flag != BleProtocol.FLAG_NOTIFY && frame.flag != BleProtocol.FLAG_NOTIFY_ALT) { + lastAckAtMs = lastIncomingAtMs; + resolveAckLocked(frame.sid, frame.msgSeq, frame.pb); + } + if (frame.ok && address.equalsIgnoreCase(rightAddress) && (frame.flag == BleProtocol.FLAG_NOTIFY || frame.flag == BleProtocol.FLAG_NOTIFY_ALT)) { + event = decodeAsyncEventLocked(frame); + if (event != null) { + lastConnectionOrInputAtMs = lastIncomingAtMs; + } + } + lock.notifyAll(); + } + interruptibleSleep.interrupt(); + if (event != null) { + emitRingEvent(event.kind, event.containerName, event.eventType, event.eventSource, event.systemExitReasonCode); + } + } + + @Override + public void onConnectionStateChange(String address, boolean connected) { + synchronized (lock) { + if (address == null) { + return; + } + if (address.equalsIgnoreCase(rightAddress)) { + rightConnected = connected; + } else if (address.equalsIgnoreCase(leftAddress)) { + leftConnected = connected; + } + if (!connected) { + sessionReady = false; + fixedLayoutCreated = false; + warmedUp = false; + startupProbePending = false; + clearAllMessagesLocked("connection lost"); + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + reconnectAfterMs = SystemClock.elapsedRealtime() + RECONNECT_DELAY_MS; + phase = userDisconnectRequested ? "disconnecting" : "connecting"; + status = userDisconnectRequested + ? "Disconnecting..." + : "Connection lost. Reconnecting..."; + } + lock.notifyAll(); + } + interruptibleSleep.interrupt(); + emitState(); + } + + private void connectLoopOnce() throws InterruptedException { //{{{ + setState("connecting", "Connecting to the glasses..."); + try { + connectArm(rightAddress, true); + connectArm(leftAddress, false); + if (!interruptibleSleep.sleep(800)) { + return; + } + sendPrelude(); + + synchronized (lock) { + sessionReady = true; + fixedLayoutCreated = false; + warmedUp = false; + clearAllMessagesLocked("session ready"); + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + lastAckAtMs = SystemClock.elapsedRealtime(); + lastIncomingAtMs = lastAckAtMs; + lastConnectionOrInputAtMs = lastAckAtMs; + lastSessionReadyAtMs = lastAckAtMs; + lastBatteryRefreshAtMs = 0; + imageRetryAfterMs = 0; + lastHeartbeatQueuedAtMs = 0; + consecutiveAckTimeouts = 0; + } + setState("connected", "Connected."); + logLine("session ready"); + } catch (Throwable t) { + logLine("connect failed: " + safeMessage(t)); + handleTransportFailure("connect failed"); + } + } //}}} + + private void connectArm(String address, boolean enableRenderNotify) { + if (!bleManager.connect(address, CONNECT_TIMEOUT_MS)) { + throw new IllegalStateException("connect failed: " + address); + } + bleManager.requestConnectionPriority(address, CONNECTION_PRIORITY_HIGH); + bleManager.requestMtu(address, DESIRED_MTU, CONNECT_TIMEOUT_MS); + if (!bleManager.discoverServices(address, SERVICES_TIMEOUT_MS)) { + throw new IllegalStateException("discoverServices failed: " + address); + } + if (!bleManager.enableNotifications(address, BleProtocol.NOTIFY_CHAR_UUID, true, DESCRIPTOR_TIMEOUT_MS)) { + throw new IllegalStateException("enableNotifications failed: " + address + " " + BleProtocol.NOTIFY_CHAR_UUID); + } + if (enableRenderNotify) { + bleManager.enableNotifications(address, BleProtocol.RENDER_NOTIFY_UUID, true, DESCRIPTOR_TIMEOUT_MS); + } + synchronized (lock) { + if (address.equalsIgnoreCase(rightAddress)) { + rightConnected = true; + } else if (address.equalsIgnoreCase(leftAddress)) { + leftConnected = true; + } + } + } + + private void sendPrelude() throws InterruptedException { //{{{ + synchronized (lock) { + clearAllMessagesLocked("prelude"); + long now = SystemClock.elapsedRealtime(); + OutboundMessage prelude = new OutboundMessage( + "prelude", + BleProtocol.PRELUDE_ACK_SID, + BleProtocol.PRELUDE_ACK_MAGIC, + CollectionUtils.singletonList(Arrays.copyOf(BleProtocol.PRELUDE_F5872, BleProtocol.PRELUDE_F5872.length)), + WRITE_TIMEOUT_MS, + 0, + now + PRELUDE_TIMEOUT_MS + ); + prelude.sentAtMs = now; + inFlightMessages.add(prelude); + } + if (!bleManager.writeFrames( + rightAddress, + BleProtocol.WRITE_CHAR_UUID, + CollectionUtils.singletonList(Arrays.copyOf(BleProtocol.PRELUDE_F5872, BleProtocol.PRELUDE_F5872.length)), + WRITE_TYPE, + WRITE_TIMEOUT_MS + )) { + throw new IllegalStateException("prelude queue failed"); + } + + long deadline = SystemClock.elapsedRealtime() + PRELUDE_TIMEOUT_MS; + synchronized (lock) { + while (running && !userDisconnectRequested && !inFlightMessages.isEmpty()) { + long remaining = deadline - SystemClock.elapsedRealtime(); + if (remaining <= 0) { + break; + } + lock.wait(Math.min(remaining, 100)); + } + if (!inFlightMessages.isEmpty()) { + clearInFlightMessagesLocked("prelude timeout"); + throw new IllegalStateException("prelude ack timeout"); + } + } + } //}}} + + private long driveSession() { + Log.i(TAG, "driveSession called (pendingMessages.size=" + pendingMessages.size() + " inFlightMessages.size=" + inFlightMessages.size() + ")"); + synchronized (lock) { + Log.i(TAG, "driveSession took lock"); + long now = SystemClock.elapsedRealtime(); + + if (!inFlightMessages.isEmpty()) { + OutboundMessage oldest = inFlightMessages.peekFirst(); + if (oldest != null && oldest.ackDeadlineAtMs <= now) { + Log.i(TAG, "message timed out: " + oldest.label); + inFlightMessages.removeFirst(); + logLine("message timed out: " + oldest.label); + releaseMagicLocked(oldest, "timeout"); + handleAckTimeoutLocked(oldest); + return 0; + } + } + + if (!shutdownRequested && !fixedLayoutCreated && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { + Log.i(TAG, "enqueueing create layout"); + enqueueStartupProbeLocked(); + } + if (!shutdownRequested && fixedLayoutCreated && !warmedUp && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { + Log.i(TAG, "enqueueing warmup"); + enqueueWarmupLocked(); + } + + // We always write a heartbeat if it's due, even if this goes in between image fragments + if (!shutdownRequested && !hasPendingOrInflightKindLocked("heartbeat") && now - lastHeartbeatQueuedAtMs >= HEARTBEAT_INTERVAL_MS && warmedUp && fixedLayoutCreated) { + Log.i(TAG, "Writing heartbeat"); + writeHeartbeatLocked(); + return 0; + } + + while (sessionReady && inFlightMessages.size() < WINDOW_SIZE && !pendingMessages.isEmpty()) { + OutboundMessage message = pendingMessages.removeFirst(); + Log.i(TAG, "sending pending message: " + message.label); + if (!writeMessageLocked(message)) { + pendingMessages.addFirst(message); + handleTransportFailureLocked("write failed"); + return 0; + } + } + if (!shutdownRequested && fixedLayoutCreated && warmedUp && pendingMessages.isEmpty() && inFlightMessages.isEmpty() + && now >= imageRetryAfterMs + && !getDesiredFingerprint().equals(displayedFingerprint)) { + Log.i(TAG, "Enqueued image update"); + enqueueDesiredImageLocked(); + return 0; + } + + if (shouldPollBatteryLocked(now)) { + Log.i(TAG, "Writing battery query"); + writeBatteryQueryLocked(now); + return 0; + } + + if (!pendingMessages.isEmpty() || !inFlightMessages.isEmpty()) { + return IDLE_SLEEP_MS; + } + return 250; + } + } + + private boolean writeMessageLocked(OutboundMessage message) { + if (!bleManager.writeFrames( + rightAddress, + BleProtocol.WRITE_CHAR_UUID, + message.frames, + WRITE_TYPE, + WRITE_TIMEOUT_MS + )) { + return false; + } + message.sentAtMs = SystemClock.elapsedRealtime(); + message.ackDeadlineAtMs = message.sentAtMs + message.ackTimeoutMs; + if (message.magic != 0) { + inFlightMessages.addLast(message); + } + logImageUpdateSendLandmarkLocked(message); + return true; + } + + private void resolveAckLocked(int sid, int magic, byte[] pb) { + Log.i(TAG, "Received ack for sid=" + sid + " magic=" + magic); + Iterator iterator = inFlightMessages.iterator(); + while (iterator.hasNext()) { + OutboundMessage message = iterator.next(); + if (message.sid == sid && message.magic == magic) { + iterator.remove(); + message.ackPayload = pb == null ? new byte[0] : Arrays.copyOf(pb, pb.length); + releaseMagicLocked(message, "ack"); + onMessageAckLocked(message); + return; + } + } + recordUnexpectedAckLocked(sid, magic); + } + + private void onMessageAckLocked(OutboundMessage message) { + consecutiveAckTimeouts = 0; + if ("create-layout".equals(message.kind)) { + startupProbePending = false; + clearMessagesOfKindLocked("startup-text-probe"); + fixedLayoutCreated = true; + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + return; + } + if ("startup-text-probe".equals(message.kind)) { + startupProbePending = false; + clearMessagesOfKindLocked("create-layout"); + fixedLayoutCreated = true; + warmedUp = true; + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + logLine("existing dashboard layout accepted text probe"); + return; + } + if ("warmup".equals(message.kind)) { + // The first tile warmup primes the image path but does not reliably + // guarantee that the tile is now visible on-screen, so it must not + // update the displayed-tile cache used by image dedupe. + warmedUp = true; + return; + } + if ("image".equals(message.kind)) { + imageRetryAfterMs = 0; + logImageUpdateAckLandmarkLocked(message); + if (message.tileIndex >= 0 && !hasPendingOrInflightTileLocked(message.tileIndex)) { + displayedTileBmps[message.tileIndex] = copyTileBmp(message.tileBmp); + } + boolean imageStillInFlight = false; + for (OutboundMessage inFlight : inFlightMessages) { + if ("image".equals(inFlight.kind)) { + imageStillInFlight = true; + break; + } + } + if (!imageStillInFlight) { + boolean imageStillQueued = false; + for (OutboundMessage queued : pendingMessages) { + if ("image".equals(queued.kind)) { + imageStillQueued = true; + break; + } + } + if (!imageStillQueued) { + displayedFingerprint = message.fingerprint; + } + } + return; + } + if ("heartbeat".equals(message.kind)) { + return; + } + if ("battery".equals(message.kind)) { + BleProtocol.BatterySnapshot snapshot = BleProtocol.parseSettingsBattery(message.ackPayload); + if (snapshot != null) { + headsetBattery = snapshot.battery; + headsetCharging = snapshot.charging; + emitBatteryState(headsetBattery, headsetCharging); + } + return; + } + if ("shutdown".equals(message.kind)) { + lastShutdownAckMagic = message.magic; + fixedLayoutCreated = false; + warmedUp = false; + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + return; + } + } + + private void logImageUpdateSendLandmarkLocked(OutboundMessage message) { + if (message.imageUpdateId <= 0) { + return; + } + if (message.imageMessageNumber == 1) { + logImageUpdateLandmarkLocked("first bluetooth message sent", message, message.sentAtMs); + } + if (message.imageMessageNumber == message.imageMessageCount) { + logImageUpdateLandmarkLocked("last bluetooth message sent", message, message.sentAtMs); + } + } + + private void logImageUpdateAckLandmarkLocked(OutboundMessage message) { + if (message.imageUpdateId <= 0 || message.imageMessageNumber != message.imageMessageCount) { + return; + } + logImageUpdateLandmarkLocked("last bluetooth message acked", message, SystemClock.elapsedRealtime()); + } + + private void logImageUpdateLandmarkLocked(String event, OutboundMessage message, long elapsedMs) { + logLine("image update#" + message.imageUpdateId + " " + event + + " at " + timestamp(elapsedMs) + + " message=" + message.imageMessageNumber + "/" + message.imageMessageCount + + " label=" + message.label); + } + + private void enqueueCreateLayoutLocked() { + int magic = nextMagic(); + pendingMessages.addLast(new OutboundMessage( + "create-layout", + "create-layout", + BleProtocol.SID_EVENHUB, + magic, + BleProtocol.framePb( + BleProtocol.buildCreateMixedImagePage(magic, DASHBOARD_TILES), + BleProtocol.SID_EVENHUB, + BleProtocol.FLAG_REQUEST, + nextTransportSeq++ + ), + ACK_TIMEOUT_MS, + getDesiredFingerprint(), + -1, + null + )); + logLine("queue create layout"); + } + + private void enqueueStartupProbeLocked() { + enqueueCreateLayoutLocked(); + + int magic = nextMagic(); + pendingMessages.addLast(new OutboundMessage( + "startup-text-probe", + "startup text probe", + BleProtocol.SID_EVENHUB, + magic, + BleProtocol.framePb( + BleProtocol.buildDashboardTextUpgrade(magic), + BleProtocol.SID_EVENHUB, + BleProtocol.FLAG_REQUEST, + nextTransportSeq++ + ), + ACK_TIMEOUT_MS, + getDesiredFingerprint(), + -1, + null + )); + startupProbePending = true; + logLine("queue startup text probe"); + } + + private void enqueueWarmupLocked() { + byte[] bmp; + synchronized (desiredTilesLock) { + bmp = desiredTileBmps[0]; + } + if (bmp == null || bmp.length == 0) { + bmp = new byte[] {0}; + } + BleProtocol.ImageTileOptions tile = DASHBOARD_TILES[0]; + int sessionId = nextMapSessionId(); + List fragments = BleImageOptimizer.planImageFragments(bmp, IMAGE_FRAGMENT_SIZE); + for (BleProtocol.ImageFragment fragment : fragments) { + int magic = nextMagic(); + pendingMessages.addLast(new OutboundMessage( + "warmup", + "warmup " + tile.name + "#" + fragment.index, + BleProtocol.SID_EVENHUB, + magic, + BleProtocol.framePb( + BleProtocol.buildImageRawData(tile, sessionId, bmp.length, fragment, magic), + BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, + nextTransportSeq++ + ), + WARMUP_FRAGMENT_TIMEOUT_MS, + getDesiredFingerprint(), + 0, + bmp + )); + } + logLine("queue warmup"); + } + + private void enqueueDesiredImageLocked() { + String fingerprint = getDesiredFingerprint(); + List changedTiles = new ArrayList<>(); + byte[][] tileBmps; + synchronized (desiredTilesLock) { + tileBmps = desiredTileBmps; + } + for (int i = 0; i < DASHBOARD_TILES.length; i++) { + BleProtocol.ImageTileOptions tile = DASHBOARD_TILES[i]; + byte[] bmp = tileBmps[i]; + if (bmp == null) { + bmp = new byte[0]; + } + byte[] displayedBmp = displayedTileBmps[i]; + if (Arrays.equals(bmp, displayedBmp)) { + continue; + } + changedTiles.add(new TileImagePlan(i, tile, bmp, nextMapSessionId())); + } + if (changedTiles.isEmpty()) { + displayedFingerprint = fingerprint; + return; + } + + boolean synchronizeCommits = changedTiles.size() > 1; + boolean reserveLastByte = false; + for (TileImagePlan plan : changedTiles) { + plan.fragments = BleImageOptimizer.planImageFragments(plan.bmp, IMAGE_FRAGMENT_SIZE, reserveLastByte); + } + + int updateId = nextImageUpdateId++; + int messageCount = 0; + for (TileImagePlan plan : changedTiles) { + messageCount += plan.fragments.size(); + } + int messageNumber = 1; + if (!synchronizeCommits) { + TileImagePlan plan = changedTiles.get(0); + for (BleProtocol.ImageFragment fragment : plan.fragments) { + enqueueImageFragmentLocked(plan, fragment, fingerprint, updateId, messageNumber++, messageCount, nextTransportSeq++, true, true); + } + } else { + for (TileImagePlan plan : changedTiles) { + for (int i = 0; i < plan.fragments.size() - 1; i++) { + enqueueImageFragmentLocked(plan, plan.fragments.get(i), fingerprint, updateId, messageNumber++, messageCount, nextTransportSeq++, true, false); + } + } + for (TileImagePlan plan : changedTiles) { + enqueueImageFragmentLocked(plan, plan.fragments.get(plan.fragments.size() - 1), fingerprint, updateId, messageNumber++, messageCount, nextTransportSeq++, true, true); + } + } + + logLine("queue image update#" + updateId + " fingerprint=" + fingerprint + + " changedTiles=" + changedTiles.size() + " messages=" + messageCount); + } + + private void enqueueImageFragmentLocked( + TileImagePlan plan, + BleProtocol.ImageFragment fragment, + String fingerprint, + int updateId, + int messageNumber, + int messageCount, + int transportSeq, + boolean requestAck, + boolean isLast + ) { + int magic = IMAGE_FRAGMENT_NO_ACK ? 0 : nextMagic(); + OutboundMessage message = new OutboundMessage( + "image", + "image " + plan.tile.name + "#" + fragment.index, + BleProtocol.SID_EVENHUB, + magic, + BleProtocol.framePb( + BleProtocol.buildImageRawData(plan.tile, plan.sessionId, plan.bmp.length, fragment, magic), + BleProtocol.SID_EVENHUB, + BleProtocol.FLAG_REQUEST, //isLast ? 0 : BleProtocol.FLAG_REQUEST, + transportSeq + ), + ACK_TIMEOUT_MS, + fingerprint, + plan.tileIndex, + plan.bmp + ); + message.setImageUpdatePosition(updateId, messageNumber, messageCount); + pendingMessages.addLast(message); + } + + private void writeHeartbeatLocked() { + int magic = nextMagic(); + OutboundMessage heartbeatMessage = new OutboundMessage( + "heartbeat", + "heartbeat", + BleProtocol.SID_EVENHUB, + magic, + BleProtocol.framePb(BleProtocol.buildHeartbeat(magic), BleProtocol.SID_EVENHUB, BleProtocol.FLAG_REQUEST, nextTransportSeq++), + ACK_TIMEOUT_MS, + displayedFingerprint, + -1, + null + ); + writeMessageLocked(heartbeatMessage); + lastHeartbeatQueuedAtMs = SystemClock.elapsedRealtime(); + } + + private boolean shouldPollBatteryLocked(long now) { + return !shutdownRequested + && sessionReady + && pendingMessages.isEmpty() + && inFlightMessages.isEmpty() + && now - lastConnectionOrInputAtMs >= BATTERY_INPUT_QUIET_MS + && (lastBatteryRefreshAtMs == 0 || now - lastBatteryRefreshAtMs >= BATTERY_REFRESH_INTERVAL_MS); + } + + private void writeBatteryQueryLocked(long now) { + int magic = nextMagic(); + OutboundMessage batteryMessage = new OutboundMessage( + "battery", + "battery", + BleProtocol.SID_UI_SETTING, + magic, + BleProtocol.framePb( + BleProtocol.buildSettingsQuery(magic), + BleProtocol.SID_UI_SETTING, + BleProtocol.FLAG_REQUEST, + nextTransportSeq++ + ), + ACK_TIMEOUT_MS, + displayedFingerprint, + -1, + null + ); + if (writeMessageLocked(batteryMessage)) { + lastBatteryRefreshAtMs = now; + } + } + + private boolean hasPendingOrInflightKindLocked(String kind) { + for (OutboundMessage queued : pendingMessages) { + if (kind.equals(queued.kind)) { + return true; + } + } + for (OutboundMessage inFlight : inFlightMessages) { + if (kind.equals(inFlight.kind)) { + return true; + } + } + return false; + } + + private boolean hasPendingOrInflightMagicLocked(int magic) { + for (OutboundMessage queued : pendingMessages) { + if (queued.magic == magic) { + return true; + } + } + for (OutboundMessage inFlight : inFlightMessages) { + if (inFlight.magic == magic) { + return true; + } + } + return false; + } + + private boolean hasPendingMagicLocked(int sid, int magic) { + for (OutboundMessage queued : pendingMessages) { + if (queued.sid == sid && queued.magic == magic) { + return true; + } + } + return false; + } + + private void handleAckTimeoutLocked(OutboundMessage message) { + consecutiveAckTimeouts += 1; + if ("create-layout".equals(message.kind) && startupProbePending) { + logLine("create layout timed out while startup text probe is pending"); + if (hasPendingOrInflightKindLocked("startup-text-probe")) { + return; + } + startupProbePending = false; + } + if ("create-layout".equals(message.kind) || "prelude".equals(message.kind)) { + handleTransportFailureLocked("ack timeout"); + return; + } + + if ("startup-text-probe".equals(message.kind)) { + startupProbePending = false; + if (hasPendingOrInflightKindLocked("create-layout")) { + return; + } + handleTransportFailureLocked("ack timeout"); + return; + } + + if ("warmup".equals(message.kind)) { + warmedUp = false; + clearMessagesOfKindLocked("warmup"); + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + } else if ("image".equals(message.kind)) { + clearMessagesOfKindLocked("image"); + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + imageRetryAfterMs = SystemClock.elapsedRealtime() + IMAGE_RETRY_DELAY_MS; + } + + if (consecutiveAckTimeouts > MAX_CONSECUTIVE_ACK_TIMEOUTS) { + handleTransportFailureLocked("too many ack timeouts"); + } + } + + private void clearMessagesOfKindLocked(String kind) { + Iterator pendingIterator = pendingMessages.iterator(); + while (pendingIterator.hasNext()) { + OutboundMessage message = pendingIterator.next(); + if (kind.equals(message.kind)) { + pendingIterator.remove(); + releaseMagicLocked(message, "cleared pending " + kind); + } + } + Iterator inFlightIterator = inFlightMessages.iterator(); + while (inFlightIterator.hasNext()) { + OutboundMessage message = inFlightIterator.next(); + if (kind.equals(message.kind)) { + inFlightIterator.remove(); + releaseMagicLocked(message, "cleared inflight " + kind); + } + } + } + + private void clearAllMessagesLocked(String reason) { + clearPendingMessagesLocked(reason); + clearInFlightMessagesLocked(reason); + } + + private void clearPendingMessagesLocked(String reason) { + while (!pendingMessages.isEmpty()) { + releaseMagicLocked(pendingMessages.removeFirst(), "cleared pending: " + reason); + } + } + + private void clearInFlightMessagesLocked(String reason) { + while (!inFlightMessages.isEmpty()) { + releaseMagicLocked(inFlightMessages.removeFirst(), "cleared inflight: " + reason); + } + } + + private void releaseMagicLocked(OutboundMessage message, String reason) { + if (message == null || message.magic < BleMagicPool.MIN_MAGIC || message.magic > BleMagicPool.MAX_MAGIC) { + return; + } + magicPool.release(message.sid, message.magic, message.label, reason); + } + + private void recordUnexpectedAckLocked(int sid, int magic) { + if (magic < BleMagicPool.MIN_MAGIC || magic > BleMagicPool.MAX_MAGIC) { + return; + } + BleMagicPool.ReleaseRecord previous = magicPool.getReleaseRecord(sid, magic); + if (previous == null) { + String pendingNote = hasPendingMagicLocked(sid, magic) ? " while that magic is only pending locally" : ""; + logLine("unexpected ACK sid=" + sid + " magic=" + magic + pendingNote + + "; possible Even app BLE contention"); + return; + } + if ("timeout".equals(previous.reason)) { + logLine("late ACK after timeout sid=" + sid + " magic=" + magic + + " label=" + previous.label + + "; ACK timeout may be too short"); + return; + } + if ("ack".equals(previous.reason)) { + logLine("duplicate ACK for already-acked message sid=" + sid + " magic=" + magic + + " label=" + previous.label + + "; possible Even app BLE contention"); + return; + } + logLine("late ACK for released message sid=" + sid + " magic=" + magic + + " label=" + previous.label + + " release=" + previous.reason); + } + + private void handleTransportFailure(String reason) { + Log.i(TAG, "handleTransportFailure called"); + synchronized (lock) { + handleTransportFailureLocked(reason); + } + } + + private void handleTransportFailureLocked(String reason) { + Log.e(TAG, "Transport failure: "+reason); + maybeEmitEvenAppConflictLocked(reason); + sessionReady = false; + fixedLayoutCreated = false; + warmedUp = false; + startupProbePending = false; + shutdownRequested = false; + imageRetryAfterMs = 0; + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + clearAllMessagesLocked("transport failure: " + reason); + reconnectAfterMs = SystemClock.elapsedRealtime() + RECONNECT_DELAY_MS; + if (!userDisconnectRequested) { + phase = "retrying"; + status = reason == null || reason.isEmpty() ? "Reconnecting..." : "Reconnecting after " + reason; + } + lock.notifyAll(); + interruptibleSleep.interrupt(); + bleManager.disconnect(rightAddress); + bleManager.disconnect(leftAddress); + emitState(); + } + + private void resetSessionStateLocked() { + sessionReady = false; + fixedLayoutCreated = false; + warmedUp = false; + rightConnected = false; + leftConnected = false; + reconnectAfterMs = 0; + lastAckAtMs = 0; + lastIncomingAtMs = 0; + lastHeartbeatQueuedAtMs = 0; + lastSessionReadyAtMs = 0; + consecutiveAckTimeouts = 0; + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + } + + private boolean hasPendingOrInflightTileLocked(int tileIndex) { + for (OutboundMessage queued : pendingMessages) { + if (queued.tileIndex == tileIndex && ("image".equals(queued.kind) || "warmup".equals(queued.kind))) { + return true; + } + } + for (OutboundMessage inFlight : inFlightMessages) { + if (inFlight.tileIndex == tileIndex && ("image".equals(inFlight.kind) || "warmup".equals(inFlight.kind))) { + return true; + } + } + return false; + } + + private AsyncEvent decodeAsyncEventLocked(BleProtocol.ParsedFrame frame) { + byte[] pb = BleProtocol.stripTrailingCrc(frame.pb); + byte[] deviceEvent = BleProtocol.readFieldBytes(pb, 13); + if (deviceEvent == null) { + return null; + } + + byte[] listEvent = BleProtocol.readFieldBytes(deviceEvent, 1); + if (listEvent != null) { + return new AsyncEvent( + "list-click", + BleProtocol.readStringFieldValue(listEvent, 2), + BleProtocol.readVarintFieldValue(listEvent, 5, BleProtocol.EVENT_CLICK), + 0, + 0 + ); + } + + byte[] textEvent = BleProtocol.readFieldBytes(deviceEvent, 2); + if (textEvent != null) { + return new AsyncEvent( + "text-click", + BleProtocol.readStringFieldValue(textEvent, 2), + BleProtocol.readVarintFieldValue(textEvent, 3, BleProtocol.EVENT_CLICK), + 0, + 0 + ); + } + + byte[] sysEvent = BleProtocol.readFieldBytes(deviceEvent, 3); + if (sysEvent != null) { + int eventType = BleProtocol.readVarintFieldValue(sysEvent, 1, BleProtocol.EVENT_CLICK); + int eventSource = BleProtocol.readVarintFieldValue(sysEvent, 2, 0); + int exitReason = BleProtocol.readVarintFieldValue(sysEvent, 4, 0); + if (eventType == BleProtocol.EVENT_FOREGROUND_EXIT || eventType == BleProtocol.EVENT_ABNORMAL_EXIT || eventType == BleProtocol.EVENT_SYSTEM_EXIT) { + if (shutdownRequested) { + lastShutdownExitAtMs = SystemClock.elapsedRealtime(); + } + fixedLayoutCreated = false; + warmedUp = false; + displayedFingerprint = ""; + displayedTileBmps = emptyTileSet(); + clearAllMessagesLocked("firmware exit event"); + } + return new AsyncEvent("sys-event", "", eventType, eventSource, exitReason); + } + return null; + } + + private void emitRingEvent(String kind, String containerName, int eventType, int eventSource, int systemExitReasonCode) { + final FaceclawBleCommunicatorListener current = listener; + if (current == null) { + return; + } + final String containerNameSnapshot = containerName == null ? "" : containerName; + mainHandler.post(() -> { + try { + current.onRingEvent(kind, containerNameSnapshot, eventType, eventSource, systemExitReasonCode); + } catch (Throwable t) { + Log.w(TAG, "listener onRingEvent failed", t); + } + }); + } + + private void emitBatteryState(int headsetBattery, int headsetCharging) { + final FaceclawBleCommunicatorListener current = listener; + if (current == null) { + return; + } + mainHandler.post(() -> { + try { + current.onBatteryState(headsetBattery, headsetCharging); + } catch (Throwable t) { + Log.w(TAG, "listener onBatteryState failed", t); + } + }); + } + + private void maybeEmitEvenAppConflictLocked(String reason) { + if (!"write failed".equals(reason)) { + return; + } + long now = SystemClock.elapsedRealtime(); + if (lastSessionReadyAtMs <= 0 || now - lastSessionReadyAtMs > EVEN_APP_WRITE_FAILURE_WINDOW_MS) { + return; + } + if (lastEvenAppConflictAtMs > 0 && now - lastEvenAppConflictAtMs < 60_000) { + return; + } + if (!FaceclawEvenAppDetector.isEvenNotificationActive(appContext)) { + return; + } + lastEvenAppConflictAtMs = now; + emitEvenAppConflict("The Even Realities app still appears to be running. It can hold the glasses BLE link and cause Faceclaw write failures. Open its app settings and force stop it, then reconnect Faceclaw."); + } + + private void emitEvenAppConflict(String message) { + final FaceclawBleCommunicatorListener current = listener; + if (current == null) { + return; + } + final String messageSnapshot = message == null ? "" : message; + mainHandler.post(() -> { + try { + current.onEvenAppConflict(messageSnapshot); + } catch (Throwable t) { + Log.w(TAG, "listener onEvenAppConflict failed", t); + } + }); + } + + private void setState(String nextPhase, String nextStatus) { + synchronized (lock) { + phase = nextPhase; + status = nextStatus; + } + emitState(); + } + + private void emitState() { + final FaceclawBleCommunicatorListener current = listener; + if (current == null) { + return; + } + final String phaseSnapshot; + final String statusSnapshot; + synchronized (lock) { + phaseSnapshot = phase; + statusSnapshot = status; + } + mainHandler.post(() -> { + try { + current.onStateChange(phaseSnapshot, statusSnapshot); + } catch (Throwable t) { + Log.w(TAG, "listener onStateChange failed", t); + } + }); + } + + private void logLine(String line) { + Log.i(TAG, line); + final FaceclawBleCommunicatorListener current = listener; + if (current == null) { + return; + } + mainHandler.post(() -> { + try { + current.onLog(line); + } catch (Throwable t) { + Log.w(TAG, "listener onLog failed", t); + } + }); + } + + private static String timestamp(long elapsedMs) { + long wallMs = System.currentTimeMillis(); + return String.format(Locale.US, "%tF %tT.%tL elapsed=%dms", wallMs, wallMs, wallMs, elapsedMs); + } + + private int nextMagic() { + return magicPool.allocate(); + } + + private int nextMapSessionId() { + int id = nextMapSessionId; + nextMapSessionId = (nextMapSessionId + 1) & 0xff; + return id; + } + + private static String requireAddress(String name, String address) { + if (address == null || address.trim().isEmpty()) { + throw new IllegalArgumentException(name + " is required"); + } + return address.trim(); + } + + private static byte[][] emptyTileSet() { + return new byte[][] {new byte[0], new byte[0], new byte[0], new byte[0]}; + } + + private static String safeMessage(Throwable t) { + String message = t == null ? "unknown" : t.getMessage(); + return message == null || message.trim().isEmpty() ? String.valueOf(t) : message; + } + + private String getDesiredFingerprint() { + synchronized (desiredTilesLock) { + return desiredFingerprint; + } + } + + private static final class BleMagicPool { + static final int MIN_MAGIC = 100; + static final int MAX_MAGIC = 255; + + private final ArrayDeque available = new ArrayDeque<>(); + private final boolean[] allocated = new boolean[256]; + private final Map releaseRecords = new HashMap<>(); + + BleMagicPool() { + for (int magic = MIN_MAGIC; magic <= MAX_MAGIC; magic++) { + available.addLast(magic); + } + } + + int allocate() { + Integer magic = available.pollFirst(); + if (magic == null) { + throw new IllegalStateException("no BLE magic values available"); + } + allocated[magic] = true; + return magic; + } + + void release(int sid, int magic, String label, String reason) { + if (magic < MIN_MAGIC || magic > MAX_MAGIC) { + return; + } + releaseRecords.put(key(sid, magic), new ReleaseRecord(label, reason, SystemClock.elapsedRealtime())); + if (!allocated[magic]) { + return; + } + allocated[magic] = false; + available.addLast(magic); + } + + ReleaseRecord getReleaseRecord(int sid, int magic) { + return releaseRecords.get(key(sid, magic)); + } + + private static String key(int sid, int magic) { + return sid + ":" + magic; + } + + private static final class ReleaseRecord { + final String label; + final String reason; + final long releasedAtMs; + + ReleaseRecord(String label, String reason, long releasedAtMs) { + this.label = label == null ? "" : label; + this.reason = reason == null ? "" : reason; + this.releasedAtMs = releasedAtMs; + } + } + } + + private static final class AsyncEvent { + final String kind; + final String containerName; + final int eventType; + final int eventSource; + final int systemExitReasonCode; + + AsyncEvent(String kind, String containerName, int eventType, int eventSource, int systemExitReasonCode) { + this.kind = kind; + this.containerName = containerName; + this.eventType = eventType; + this.eventSource = eventSource; + this.systemExitReasonCode = systemExitReasonCode; + } + } + + private static final class TileImagePlan { + final int tileIndex; + final BleProtocol.ImageTileOptions tile; + final byte[] bmp; + final int sessionId; + List fragments = Collections.emptyList(); + + TileImagePlan(int tileIndex, BleProtocol.ImageTileOptions tile, byte[] bmp, int sessionId) { + this.tileIndex = tileIndex; + this.tile = tile; + this.bmp = copyTileBmp(bmp); + this.sessionId = sessionId; + } + } + + private static final class OutboundMessage { + final String kind; + final String label; + final int sid; + final int magic; + final List frames; + final int ackTimeoutMs; + final String fingerprint; + final int tileIndex; + final byte[] tileBmp; + + int imageUpdateId; + int imageMessageNumber; + int imageMessageCount; + long sentAtMs; + long ackDeadlineAtMs; + byte[] ackPayload = new byte[0]; + + OutboundMessage(String kind, String label, int sid, int magic, List frames, int ackTimeoutMs, String fingerprint, int tileIndex, byte[] tileBmp) { + this.kind = kind; + this.label = label; + this.sid = sid; + this.magic = magic; + this.frames = frames; + this.ackTimeoutMs = ackTimeoutMs; + this.fingerprint = fingerprint == null ? "" : fingerprint; + this.tileIndex = tileIndex; + this.tileBmp = copyTileBmp(tileBmp); + } + + OutboundMessage(String label, int sid, int magic, List frames, int writeTimeoutMs, int ignored, long ackDeadlineAtMs) { + this.kind = "prelude"; + this.label = label; + this.sid = sid; + this.magic = magic; + this.frames = frames; + this.ackTimeoutMs = writeTimeoutMs; + this.fingerprint = ""; + this.tileIndex = -1; + this.tileBmp = new byte[0]; + this.ackDeadlineAtMs = ackDeadlineAtMs; + } + + void setImageUpdatePosition(int updateId, int messageNumber, int messageCount) { + this.imageUpdateId = updateId; + this.imageMessageNumber = messageNumber; + this.imageMessageCount = messageCount; + } + } + + private static byte[] copyTileBmp(byte[] bmp) { + if (bmp == null || bmp.length == 0) { + return new byte[0]; + } + return Arrays.copyOf(bmp, bmp.length); + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicatorListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicatorListener.java new file mode 100644 index 00000000..4e4277f3 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicatorListener.java @@ -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); +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleListener.java new file mode 100644 index 00000000..2a64c2fd --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleListener.java @@ -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); +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.java new file mode 100644 index 00000000..7a1004fb --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.java @@ -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 gattClients = new ConcurrentHashMap<>(); + private final ConcurrentHashMap writeLocks = new ConcurrentHashMap<>(); + + private final ConcurrentHashMap connectLatches = new ConcurrentHashMap<>(); + private final ConcurrentHashMap connectResults = new ConcurrentHashMap<>(); + + private final ConcurrentHashMap servicesLatches = new ConcurrentHashMap<>(); + private final ConcurrentHashMap servicesStatuses = new ConcurrentHashMap<>(); + + private final ConcurrentHashMap mtuLatches = new ConcurrentHashMap<>(); + private final ConcurrentHashMap mtuStatuses = new ConcurrentHashMap<>(); + + private final ConcurrentHashMap descriptorLatches = new ConcurrentHashMap<>(); + private final ConcurrentHashMap descriptorStatuses = new ConcurrentHashMap<>(); + + private final ConcurrentHashMap writeLatches = new ConcurrentHashMap<>(); + private final ConcurrentHashMap 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 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 runOnMainSync(Callable callable) { + if (Looper.myLooper() == Looper.getMainLooper()) { + try { + return callable.call(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + CountDownLatch latch = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + AtomicReference 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)); + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBridge.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBridge.java new file mode 100644 index 00000000..2b6196af --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBridge.java @@ -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; + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceDiscovery.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceDiscovery.java new file mode 100644 index 00000000..d57c4d3a --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawDeviceDiscovery.java @@ -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 matches = new LinkedHashMap<>(); + Set 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 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 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 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 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; + } + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawEvenAppDetector.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawEvenAppDetector.java new file mode 100644 index 00000000..6fc488d1 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawEvenAppDetector.java @@ -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); + } + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawForegroundService.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawForegroundService.java new file mode 100644 index 00000000..8cf6c136 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawForegroundService.java @@ -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(); + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java new file mode 100644 index 00000000..e7ef0d07 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java @@ -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 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 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; + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaControllerListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaControllerListener.java new file mode 100644 index 00000000..54774b6e --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaControllerListener.java @@ -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 + ); +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java new file mode 100644 index 00000000..be089fdd --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java @@ -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(); + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/InterruptibleSleep.java b/App_Resources/Android/src/main/java/com/faceclaw/app/InterruptibleSleep.java new file mode 100644 index 00000000..320f980d --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/InterruptibleSleep.java @@ -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(); + } + } +} diff --git a/App_Resources/Android/src/main/res/drawable-hdpi/background.png b/App_Resources/Android/src/main/res/drawable-hdpi/background.png new file mode 100644 index 00000000..bbefbf42 Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-hdpi/background.png differ diff --git a/App_Resources/Android/src/main/res/drawable-hdpi/logo.png b/App_Resources/Android/src/main/res/drawable-hdpi/logo.png new file mode 100644 index 00000000..e788deb3 Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-hdpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-ldpi/background.png b/App_Resources/Android/src/main/res/drawable-ldpi/background.png new file mode 100644 index 00000000..f6a08eea Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-ldpi/background.png differ diff --git a/App_Resources/Android/src/main/res/drawable-ldpi/logo.png b/App_Resources/Android/src/main/res/drawable-ldpi/logo.png new file mode 100644 index 00000000..e4cac1ad Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-ldpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-mdpi/background.png b/App_Resources/Android/src/main/res/drawable-mdpi/background.png new file mode 100644 index 00000000..0c90f0f7 Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-mdpi/background.png differ diff --git a/App_Resources/Android/src/main/res/drawable-mdpi/logo.png b/App_Resources/Android/src/main/res/drawable-mdpi/logo.png new file mode 100644 index 00000000..ce3c3a4b Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-mdpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-nodpi/splash_screen.xml b/App_Resources/Android/src/main/res/drawable-nodpi/splash_screen.xml new file mode 100644 index 00000000..ada77f92 --- /dev/null +++ b/App_Resources/Android/src/main/res/drawable-nodpi/splash_screen.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/App_Resources/Android/src/main/res/drawable-xhdpi/background.png b/App_Resources/Android/src/main/res/drawable-xhdpi/background.png new file mode 100644 index 00000000..3541570c Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-xhdpi/background.png differ diff --git a/App_Resources/Android/src/main/res/drawable-xhdpi/logo.png b/App_Resources/Android/src/main/res/drawable-xhdpi/logo.png new file mode 100644 index 00000000..88267df0 Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-xhdpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-xxhdpi/background.png b/App_Resources/Android/src/main/res/drawable-xxhdpi/background.png new file mode 100644 index 00000000..abb0fc70 Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-xxhdpi/background.png differ diff --git a/App_Resources/Android/src/main/res/drawable-xxhdpi/logo.png b/App_Resources/Android/src/main/res/drawable-xxhdpi/logo.png new file mode 100644 index 00000000..55800c9a Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-xxhdpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable-xxxhdpi/background.png b/App_Resources/Android/src/main/res/drawable-xxxhdpi/background.png new file mode 100644 index 00000000..10897752 Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-xxxhdpi/background.png differ diff --git a/App_Resources/Android/src/main/res/drawable-xxxhdpi/logo.png b/App_Resources/Android/src/main/res/drawable-xxxhdpi/logo.png new file mode 100644 index 00000000..0703f90f Binary files /dev/null and b/App_Resources/Android/src/main/res/drawable-xxxhdpi/logo.png differ diff --git a/App_Resources/Android/src/main/res/drawable/ic_launcher_foreground.xml b/App_Resources/Android/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 00000000..fd826a31 --- /dev/null +++ b/App_Resources/Android/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/App_Resources/Android/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/App_Resources/Android/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..7353dbd1 --- /dev/null +++ b/App_Resources/Android/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/App_Resources/Android/src/main/res/mipmap-hdpi/ic_launcher.png b/App_Resources/Android/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..69948d22 Binary files /dev/null and b/App_Resources/Android/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/App_Resources/Android/src/main/res/mipmap-mdpi/ic_launcher.png b/App_Resources/Android/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..90a58cd7 Binary files /dev/null and b/App_Resources/Android/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/App_Resources/Android/src/main/res/mipmap-xhdpi/ic_launcher.png b/App_Resources/Android/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..70a2a0d0 Binary files /dev/null and b/App_Resources/Android/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/App_Resources/Android/src/main/res/mipmap-xxhdpi/ic_launcher.png b/App_Resources/Android/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..1ee5a941 Binary files /dev/null and b/App_Resources/Android/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/App_Resources/Android/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/App_Resources/Android/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..66e9d4bb Binary files /dev/null and b/App_Resources/Android/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/App_Resources/Android/src/main/res/values-v21/colors.xml b/App_Resources/Android/src/main/res/values-v21/colors.xml new file mode 100644 index 00000000..da5ca2fe --- /dev/null +++ b/App_Resources/Android/src/main/res/values-v21/colors.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/App_Resources/Android/src/main/res/values-v21/styles.xml b/App_Resources/Android/src/main/res/values-v21/styles.xml new file mode 100644 index 00000000..04d8a065 --- /dev/null +++ b/App_Resources/Android/src/main/res/values-v21/styles.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + diff --git a/App_Resources/Android/src/main/res/values-v29/styles.xml b/App_Resources/Android/src/main/res/values-v29/styles.xml new file mode 100644 index 00000000..9a2a79d5 --- /dev/null +++ b/App_Resources/Android/src/main/res/values-v29/styles.xml @@ -0,0 +1,18 @@ + + + + + + + + + \ No newline at end of file diff --git a/App_Resources/Android/src/main/res/values/colors.xml b/App_Resources/Android/src/main/res/values/colors.xml new file mode 100644 index 00000000..78c4a519 --- /dev/null +++ b/App_Resources/Android/src/main/res/values/colors.xml @@ -0,0 +1,14 @@ + + + + #F5F5F5 + + + #757575 + + + #65ADF1 + + + + diff --git a/App_Resources/Android/src/main/res/values/ic_launcher_background.xml b/App_Resources/Android/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 00000000..c5d5899f --- /dev/null +++ b/App_Resources/Android/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file diff --git a/App_Resources/Android/src/main/res/values/styles.xml b/App_Resources/Android/src/main/res/values/styles.xml new file mode 100644 index 00000000..4f91b610 --- /dev/null +++ b/App_Resources/Android/src/main/res/values/styles.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..fd3743d6 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,14 @@ +This is Faceclaw, an Android program that provides user interface on the Even +Realities G2 smart glasses. It is written in a mix of Typescript/NativeScript +(for the user interface parts) and Java (for the low-level bluetooth parts and +for interfacing with Android SDK). + +Typescript parts are in app/. Java parts are in App_Resources/Android/src/main/java/com/faceclaw/app/. + +If you are working on low-level communication bits, consider checking out +https://github.com/Commute773/g2-kit-unofficial/ and referring to ble/docs/ +and ble/gen/ directories inside. That repository contains automatically +extracted protobuf schemas, communication test scripts, and documentation of +caveats that come up when communicating with the headset. + +For instructions getting this to compile and install, refer to README. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README b/README new file mode 100644 index 00000000..fb225375 --- /dev/null +++ b/README @@ -0,0 +1,35 @@ +# Faceclaw - An unofficial user interface for the Even Realities G2 smart glasses + +This is an unofficial user interface for the Even Realities G2 smart glasses. +It is entirely unofficial, and comes with no support or warranty from Even +Realities or from anyone. If this damages your glasses somehow, this void your +warranty. + +THIS IS AN UNFINISHED DEVELOPMENT PROTOTYPE; IF YOU DON'T HAVE ANY PROGRAMMING +EXPERIENCE, OR YOU AREN'T COMFORTABLE EDITING, COMPILING, AND SIDELOADING AN +ANDROID APPLICATION YOURSELF, OR YOU DON'T HAVE AN ANDROID DEVICE TO RUN IT +ON, THIS IS NOT FOR YOU. + +In its current state, it's more of a demo/research project than something you +could actually use, mainly because it's extremely slow: updating the display +on the headset takes multiple seconds. This is because it's entirely designed +around sending images to the headset, which is slow, rather than updating text +containers that use the builtin font, which is fast but very limiting. Hopefully +a future firmware update or reverse-engineering discovery will speed this up +enough to be fully usable. In the mean time, you can use it as a dashboard +(which doesn't require fast updates), and you can operate the UI via the phone +screen, which shows the same UI but more quickly. + +The name Faceclaw implies plans to integrate this with OpenClaw. These plans +have not yet been iplemented. If you want to use OpenClaw with Even Realities G2 +smart glasses today, consider using OcuClaw (which is an Even Hub app) instead. + + +## Compiling and Installing + +To compile this, you will need an Android SDK environment, with SDK version 35 +installed and licenses accepted, and the ANDROID_HOME pointing to the install. +You will need a JDK environment (v21), with the JAVA_HOME environment variable +pointed at it. You will also need a reasonably up to date npm and nodejs +installed. + diff --git a/app/app-root.xml b/app/app-root.xml new file mode 100644 index 00000000..85ad5b73 --- /dev/null +++ b/app/app-root.xml @@ -0,0 +1,2 @@ + + diff --git a/app/app.css b/app/app.css new file mode 100644 index 00000000..ad61db27 --- /dev/null +++ b/app/app.css @@ -0,0 +1,15 @@ +@import '@nativescript/theme/css/core.css'; +@import '@nativescript/theme/css/default.css'; + +Button.-primary { + font-size: 18; +} + +.system-name-modal { + margin: 16; + padding: 16; + background-color: #f6f6f6; + border-color: #222222; + border-width: 1; + border-radius: 8; +} diff --git a/app/app.ts b/app/app.ts new file mode 100644 index 00000000..83d01785 --- /dev/null +++ b/app/app.ts @@ -0,0 +1,14 @@ +/* +In NativeScript, the app.ts file is the entry point to your application. +You can use this file to perform app-level initialization, but the primary +purpose of the file is to pass control to the app’s first module. +*/ + +import { Application } from '@nativescript/core' + +Application.run({ moduleName: 'app-root' }) + +/* +Do not place any code after the application has been started as it will not +be executed on iOS. +*/ diff --git a/app/config-page.ts b/app/config-page.ts new file mode 100644 index 00000000..3fdf928b --- /dev/null +++ b/app/config-page.ts @@ -0,0 +1,8 @@ +import { EventData, Page } from "@nativescript/core"; + +import { ConfigViewModel } from "./config-view-model"; + +export function navigatingTo(args: EventData): void { + const page = args.object as Page; + page.bindingContext = new ConfigViewModel(); +} diff --git a/app/config-page.xml b/app/config-page.xml new file mode 100644 index 00000000..f180828d --- /dev/null +++ b/app/config-page.xml @@ -0,0 +1,38 @@ + + + + +