ferrochrome-tests: Unlock screen before launch

Bug: 351946798
Change-Id: I8f603078f9f37354f518335b33c630ad5432aa78
Test: Manually with locked with swipe, locked with pattern, and unlocked device
diff --git a/tests/ferrochrome/ferrochrome.sh b/tests/ferrochrome/ferrochrome.sh
index 72b5433..210548a 100755
--- a/tests/ferrochrome/ferrochrome.sh
+++ b/tests/ferrochrome/ferrochrome.sh
@@ -27,6 +27,7 @@
 FECR_BOOT_COMPLETED_LOG="Have fun and send patches!"
 FECR_BOOT_TIMEOUT="300" # 5 minutes (300 seconds)
 ACTION_NAME="android.virtualization.VM_LAUNCHER"
+TRY_UNLOCK_MAX=10
 
 fecr_clean_up() {
   trap - INT
@@ -132,6 +133,35 @@
   adb push ${fecr_script_path}/assets/vm_config.json ${FECR_CONFIG_PATH}
 fi
 
+echo "Ensure screen unlocked"
+
+try_unlock=0
+while [[ "${try_unlock}" -le "${TRY_UNLOCK_MAX}" ]]; do
+  screen_state=$(adb shell dumpsys nfc | sed -n 's/^mScreenState=\(.*\)$/\1/p')
+  case "${screen_state}" in
+    "ON_UNLOCKED")
+      break
+      ;;
+    "ON_LOCKED")
+      # Disclaimer: This can unlock phone only if unlock method is swipe (default after FDR)
+      adb shell input keyevent KEYCODE_MENU
+      ;;
+    "OFF_LOCKED"|"OFF_UNLOCKED")
+      adb shell input keyevent KEYCODE_WAKEUP
+      ;;
+    *)
+      echo "Unknown screen state. Continue to boot, but may fail"
+      break
+      ;;
+  esac
+  sleep 1
+  try_unlock=$((try_unlock+1))
+done
+if [[ "${try_unlock}" -gt "${TRY_UNLOCK_MAX}" ]]; then
+  >&2 echo "Failed to unlock screen. Try again after manual unlock"
+  exit 1
+fi
+
 echo "Starting ferrochrome"
 adb shell am start-activity -a ${ACTION_NAME} > /dev/null