mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-23 18:06:29 +01:00
Phase 4/3: NFC room proof, runtime permissions, non-blocking step reads
Three defects found by reviewing the emulator run, all on the dismiss path:
1. ACTIVITY_RECOGNITION was declared but never requested at runtime (API 29+).
Denied, TYPE_STEP_COUNTER delivers nothing, so checkSteps() reports "sensor
unavailable" forever. With steps the only wired proof, that made the alarm
*undismissable*, not merely degraded. MainActivity now requests it
alongside POST_NOTIFICATIONS.
2. checkNfc/checkQr were dead code — no reader, no channel method, no
registration — so steps was the only reachable proof. That inverts the
decision ("NFC or QR qualifies; steps alone does NOT") and removes exactly
the redundancy whose purpose is that one failing mechanism at 06:00 must
never block dismissal. Added NfcReader (hand-written on the existing
channel, NfcAdapter.enableReaderMode so the tap does not restart the
activity and reset the challenge) plus RoomProofSettings for the registered
tag/QR. mobile_scanner stays the droppable extra.
3. StepCounter blocked the platform main thread up to 3s per read, called from
the MethodChannel handler — jank-to-ANR on the ring screen. Now registers a
listener and serves the last sample; reads never block.
Also: raiseAlarmVolume() is guarded. setStreamVolume can throw under a zen
rule, and by then startForeground() has already posted — a failed volume bump
must not take the ring down with it.
Verified on the API 36 AVD with the real app widget and route (the earlier
probe rendered its own UI, so it proved the Kotlin path but nothing about
/ring): screen Asleep -> Awake, AlarmActivity top resumed over the lockscreen,
RingScreen showing the room-proof gate. New widget tests cover the /ring route
resolving and the challenge staying gated behind the room proof.
flutter test: 57 pass. dart analyze: clean. Zero Python files touched.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
This commit is contained in:
parent
af2a9b416b
commit
cb50e58a56
@ -28,9 +28,25 @@ class AlarmActivity : FlutterActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
|
||||
/** Kept so NFC reader mode can push tag ids back to the ring screen. */
|
||||
private var alarmChannel: MethodChannel? = null
|
||||
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
AlarmChannel.register(this, flutterEngine)
|
||||
alarmChannel = channel(flutterEngine)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
// Reader mode only works while this activity is in the foreground, so
|
||||
// it is started here rather than at engine-configure time.
|
||||
alarmChannel?.let { NfcReader.start(this, it) }
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
NfcReader.stop(this)
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -48,6 +48,7 @@ object AlarmChannel {
|
||||
AlarmService.start(context)
|
||||
result.success(null)
|
||||
}
|
||||
"hasNfc" -> result.success(NfcReader.isAvailable(context))
|
||||
"stepCount" -> result.success(StepCounter.stepsSinceRingStart(context))
|
||||
"beginStepCount" -> {
|
||||
StepCounter.markRingStart(context)
|
||||
|
||||
@ -15,6 +15,7 @@ import android.media.RingtoneManager
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.PowerManager
|
||||
import android.util.Log
|
||||
import android.os.VibrationEffect
|
||||
import android.os.Vibrator
|
||||
import android.os.VibratorManager
|
||||
@ -34,6 +35,7 @@ class AlarmService : Service() {
|
||||
private var vibrator: Vibrator? = null
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AlarmService"
|
||||
private const val CHANNEL_ID = "wake_alarm_ring"
|
||||
private const val NOTIFICATION_ID = 42
|
||||
|
||||
@ -152,11 +154,22 @@ class AlarmService : Service() {
|
||||
raiseAlarmVolume()
|
||||
}
|
||||
|
||||
/** Alarm stream turned down to zero must not silence the alarm. */
|
||||
/**
|
||||
* Alarm stream turned down to zero must not silence the alarm.
|
||||
*
|
||||
* Guarded: setStreamVolume can throw under an active zen rule, and by this
|
||||
* point startForeground() has already posted — an exception here would
|
||||
* take the whole ring down over a volume bump that is only an
|
||||
* improvement, not the mechanism.
|
||||
*/
|
||||
private fun raiseAlarmVolume() {
|
||||
val audio = getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val max = audio.getStreamMaxVolume(AudioManager.STREAM_ALARM)
|
||||
audio.setStreamVolume(AudioManager.STREAM_ALARM, max, 0)
|
||||
try {
|
||||
val audio = getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val max = audio.getStreamMaxVolume(AudioManager.STREAM_ALARM)
|
||||
audio.setStreamVolume(AudioManager.STREAM_ALARM, max, 0)
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "could not raise the alarm volume; ringing anyway", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopSound() {
|
||||
|
||||
@ -18,26 +18,35 @@ class MainActivity : FlutterActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestNotificationPermission()
|
||||
requestAlarmPermissions()
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks for POST_NOTIFICATIONS, which is a runtime permission from API 33.
|
||||
* Asks for the two runtime permissions the alarm cannot work without.
|
||||
*
|
||||
* Without the grant the app sits at importance=NONE, the full-screen
|
||||
* intent is rejected before it is considered, and the alarm rings with no
|
||||
* dismiss screen. Measured on the API 36 AVD, where a freshly installed
|
||||
* app is blocked by default.
|
||||
* POST_NOTIFICATIONS (API 33+): without the grant the app sits at
|
||||
* importance=NONE, the full-screen intent is rejected before it is even
|
||||
* considered, and the alarm rings with no dismiss screen. Measured on the
|
||||
* API 36 AVD, where a freshly installed app is blocked by default.
|
||||
*
|
||||
* ACTIVITY_RECOGNITION (API 29+): TYPE_STEP_COUNTER delivers nothing
|
||||
* without it, so the steps fallback would report "sensor unavailable"
|
||||
* forever. That matters because a room proof that can never be satisfied
|
||||
* makes the alarm undismissable, not merely degraded.
|
||||
*/
|
||||
private fun requestNotificationPermission() {
|
||||
val granted = ContextCompat.checkSelfPermission(
|
||||
this,
|
||||
private fun requestAlarmPermissions() {
|
||||
val wanted = arrayOf(
|
||||
Manifest.permission.POST_NOTIFICATIONS,
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
if (granted) return
|
||||
Manifest.permission.ACTIVITY_RECOGNITION,
|
||||
)
|
||||
val missing = wanted.filter {
|
||||
ContextCompat.checkSelfPermission(this, it) !=
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
if (missing.isEmpty()) return
|
||||
ActivityCompat.requestPermissions(
|
||||
this,
|
||||
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
|
||||
missing.toTypedArray(),
|
||||
NOTIFICATION_REQUEST_CODE,
|
||||
)
|
||||
}
|
||||
|
||||
@ -0,0 +1,65 @@
|
||||
package com.kuhy.wake_alarm_sync
|
||||
|
||||
import android.app.Activity
|
||||
import android.nfc.NfcAdapter
|
||||
import android.nfc.Tag
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
/**
|
||||
* Reads NFC tag ids while the ring screen is up.
|
||||
*
|
||||
* Hand-written on the existing MethodChannel rather than `nfc_manager`, for
|
||||
* the same reason the ring path is: nothing on the dismiss path may depend on
|
||||
* a plugin compiling against AGP 9. If NFC and QR were both plugins and both
|
||||
* failed, item 3 would have no working proof at all.
|
||||
*
|
||||
* Reader mode (rather than the foreground-dispatch intent flow) is what lets
|
||||
* a tag be read without the activity being restarted, which matters because
|
||||
* restarting the ring screen would reset the challenge.
|
||||
*/
|
||||
object NfcReader {
|
||||
|
||||
/** Dart method invoked with the scanned tag id. */
|
||||
private const val ON_TAG = "onNfcTag"
|
||||
|
||||
/** Tag technologies to poll; covers the common cheap NTAG stickers. */
|
||||
private const val FLAGS =
|
||||
NfcAdapter.FLAG_READER_NFC_A or
|
||||
NfcAdapter.FLAG_READER_NFC_B or
|
||||
NfcAdapter.FLAG_READER_NFC_F or
|
||||
NfcAdapter.FLAG_READER_NFC_V or
|
||||
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS
|
||||
|
||||
/**
|
||||
* Starts polling, pushing each tag id to Dart over [channel].
|
||||
*
|
||||
* Returns false when the device has no NFC or it is switched off, so the
|
||||
* ring screen can say so rather than waiting on a tap that cannot come.
|
||||
*/
|
||||
fun start(activity: Activity, channel: MethodChannel): Boolean {
|
||||
val adapter = NfcAdapter.getDefaultAdapter(activity) ?: return false
|
||||
if (!adapter.isEnabled) return false
|
||||
adapter.enableReaderMode(
|
||||
activity,
|
||||
{ tag -> activity.runOnUiThread { channel.invokeMethod(ON_TAG, idOf(tag)) } },
|
||||
FLAGS,
|
||||
null,
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Whether this device can read NFC at all and has it switched on. */
|
||||
fun isAvailable(context: android.content.Context): Boolean {
|
||||
val adapter = NfcAdapter.getDefaultAdapter(context) ?: return false
|
||||
return adapter.isEnabled
|
||||
}
|
||||
|
||||
/** Stops polling; safe to call when [start] returned false. */
|
||||
fun stop(activity: Activity) {
|
||||
NfcAdapter.getDefaultAdapter(activity)?.disableReaderMode(activity)
|
||||
}
|
||||
|
||||
/** Lower-case hex of the tag's id, which is what Settings registers. */
|
||||
private fun idOf(tag: Tag): String =
|
||||
tag.id.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
@ -25,14 +25,26 @@ object StepCounter {
|
||||
/** Sentinel for "no baseline captured yet". */
|
||||
private const val NONE = -1L
|
||||
|
||||
/** How long to wait for the sensor's first reading before giving up. */
|
||||
private const val READ_TIMEOUT_MS = 3000L
|
||||
/** Most recent step total seen, kept so reads never block the caller. */
|
||||
@Volatile
|
||||
private var latest: Long? = null
|
||||
|
||||
/** Records the current step total as the baseline for this ring. */
|
||||
/**
|
||||
* Starts listening and records the first reading as this ring's baseline.
|
||||
*
|
||||
* Registration is fire-and-forget: the sensor callback arrives on its own
|
||||
* thread, so nothing here blocks the MethodChannel — this runs on the
|
||||
* platform main thread, where a multi-second wait is an ANR.
|
||||
*/
|
||||
fun markRingStart(context: Context) {
|
||||
val current = readTotal(context) ?: return
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||
.putLong(KEY_BASELINE, current).apply()
|
||||
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
prefs.edit().remove(KEY_BASELINE).apply()
|
||||
listen(context) { total ->
|
||||
// Only the first sample after a ring starts becomes the baseline.
|
||||
if (!prefs.contains(KEY_BASELINE)) {
|
||||
prefs.edit().putLong(KEY_BASELINE, total).apply()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -45,32 +57,35 @@ object StepCounter {
|
||||
val baseline = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.getLong(KEY_BASELINE, NONE)
|
||||
if (baseline == NONE) return NONE
|
||||
val current = readTotal(context) ?: return NONE
|
||||
// Non-blocking: whatever the listener last delivered. Returns -1 until
|
||||
// the first sample arrives rather than stalling the ring screen.
|
||||
val current = latest ?: return NONE
|
||||
return (current - baseline).coerceAtLeast(0)
|
||||
}
|
||||
|
||||
/** Blocks briefly for one TYPE_STEP_COUNTER sample; null when there is no sensor. */
|
||||
private fun readTotal(context: Context): Long? {
|
||||
/**
|
||||
* Registers a step listener, keeping [latest] fresh for later reads.
|
||||
*
|
||||
* The listener is deliberately never unregistered while the alarm rings:
|
||||
* the ring screen polls repeatedly, and re-registering per read would cost
|
||||
* a fresh sensor warm-up each time.
|
||||
*/
|
||||
private fun listen(context: Context, onFirst: (Long) -> Unit) {
|
||||
val manager =
|
||||
context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager ?: return null
|
||||
val sensor = manager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) ?: return null
|
||||
val lock = Object()
|
||||
var value: Long? = null
|
||||
val listener = object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
synchronized(lock) {
|
||||
value = event.values.firstOrNull()?.toLong()
|
||||
lock.notifyAll()
|
||||
context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager ?: return
|
||||
val sensor = manager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) ?: return
|
||||
manager.registerListener(
|
||||
object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
val total = event.values.firstOrNull()?.toLong() ?: return
|
||||
latest = total
|
||||
onFirst(total)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
|
||||
}
|
||||
manager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_FASTEST)
|
||||
synchronized(lock) {
|
||||
if (value == null) lock.wait(READ_TIMEOUT_MS)
|
||||
}
|
||||
manager.unregisterListener(listener)
|
||||
return value
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
|
||||
},
|
||||
sensor,
|
||||
SensorManager.SENSOR_DELAY_NORMAL,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,23 +1,22 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:wake_alarm_sync/main.dart';
|
||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||
|
||||
/// Debug entrypoint that starts the ring immediately on launch.
|
||||
/// Debug entrypoint that starts the ring and opens the real dismiss route.
|
||||
///
|
||||
/// Used to exercise the Kotlin foreground-service and full-screen-intent path
|
||||
/// on an emulator, where the normal flow needs a sync backend first. Not part
|
||||
/// of the shipped app: `flutter build apk` uses `lib/main.dart`.
|
||||
/// on an emulator, where the normal flow needs a sync backend first. It runs
|
||||
/// the **real** app widget and pushes [kRingRoute], so what appears is exactly
|
||||
/// what AlarmActivity's initial route produces — a probe with its own UI would
|
||||
/// prove nothing about the route.
|
||||
///
|
||||
/// Not part of the shipped app: `flutter build apk` uses `lib/main.dart`.
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await AlarmScheduler().ringNow();
|
||||
runApp(const _Probe());
|
||||
}
|
||||
|
||||
class _Probe extends StatelessWidget {
|
||||
const _Probe();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => const MaterialApp(
|
||||
home: Scaffold(body: Center(child: Text('ring probe'))),
|
||||
);
|
||||
runApp(const WakeAlarmSyncApp());
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
navigatorKey.currentState?.pushNamed(kRingRoute);
|
||||
});
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||
import 'package:wake_alarm_sync/services/challenge.dart';
|
||||
import 'package:wake_alarm_sync/services/room_proof.dart';
|
||||
import 'package:wake_alarm_sync/services/room_proof_settings.dart';
|
||||
|
||||
/// The dismiss screen shown over the lockscreen while the alarm rings.
|
||||
///
|
||||
@ -27,7 +28,9 @@ class _RingScreenState extends State<RingScreen> {
|
||||
late final AlarmScheduler _scheduler = widget.scheduler ?? AlarmScheduler();
|
||||
late final ChallengeGenerator _generator =
|
||||
widget.generator ?? ChallengeGenerator();
|
||||
late final RoomProof _proof = RoomProof(scheduler: _scheduler);
|
||||
RoomProof _proof = RoomProof(scheduler: AlarmScheduler());
|
||||
RoomProofSettings _settings = const RoomProofSettings();
|
||||
bool _nfcAvailable = false;
|
||||
late Challenge _challenge = _generator.next();
|
||||
|
||||
final TextEditingController _input = TextEditingController();
|
||||
@ -44,10 +47,47 @@ class _RingScreenState extends State<RingScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_proof = RoomProof(scheduler: _scheduler);
|
||||
unawaited(_scheduler.beginStepCount());
|
||||
unawaited(_loadRoomProof());
|
||||
_startFlashTimerIfNeeded();
|
||||
}
|
||||
|
||||
/// Loads the registered tag/QR and starts listening for NFC taps.
|
||||
Future<void> _loadRoomProof() async {
|
||||
final settings = await RoomProofSettings.load();
|
||||
final hasNfc = await _scheduler.hasNfc();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_settings = settings;
|
||||
_nfcAvailable = hasNfc;
|
||||
_proof = RoomProof(
|
||||
scheduler: _scheduler,
|
||||
registeredTagId: settings.nfcTagId,
|
||||
);
|
||||
});
|
||||
_scheduler.onNfcTag(_onNfcTag);
|
||||
}
|
||||
|
||||
void _onNfcTag(String tagId) {
|
||||
final result = _proof.checkNfc(tagId);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_inRoom = result.satisfied;
|
||||
_status = result.detail;
|
||||
});
|
||||
}
|
||||
|
||||
/// Called by the QR scanner when a code is decoded.
|
||||
void onQrScanned(String payload) {
|
||||
final result = _proof.checkQr(payload, expected: _settings.qrPayload ?? '');
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_inRoom = result.satisfied;
|
||||
_status = result.detail;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_flashTimer?.cancel();
|
||||
@ -116,12 +156,17 @@ class _RingScreenState extends State<RingScreen> {
|
||||
|
||||
List<Widget> _roomGate(ThemeData theme) => <Widget>[
|
||||
Text(
|
||||
'Go to the other room: tap the NFC tag, scan the QR code, '
|
||||
'or walk ${RoomProof.requiredSteps} steps.',
|
||||
_nfcAvailable && _settings.nfcTagId != null
|
||||
? 'Go to the other room and tap the NFC tag.'
|
||||
: 'Go to the other room: scan the QR code, or walk '
|
||||
'${RoomProof.requiredSteps} steps.',
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.bodyLarge,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
// The steps fallback stays reachable even when NFC is registered: a
|
||||
// single failing mechanism at 06:00 must never make the alarm
|
||||
// undismissable.
|
||||
FilledButton(onPressed: _trySteps, child: const Text('Check steps')),
|
||||
];
|
||||
|
||||
|
||||
@ -47,6 +47,24 @@ class AlarmScheduler {
|
||||
Future<bool> canUseFullScreenIntent() async =>
|
||||
await _channel.invokeMethod<bool>('canUseFullScreenIntent') ?? false;
|
||||
|
||||
/// Whether the device can read NFC and has it switched on.
|
||||
Future<bool> hasNfc() async =>
|
||||
await _channel.invokeMethod<bool>('hasNfc') ?? false;
|
||||
|
||||
/// Calls [onTag] with each NFC tag id scanned while the ring screen is up.
|
||||
///
|
||||
/// Reader mode is driven from Kotlin, so the tap does not restart the
|
||||
/// activity — a restart would reset the challenge.
|
||||
void onNfcTag(void Function(String tagId) onTag) {
|
||||
_channel.setMethodCallHandler((call) async {
|
||||
if (call.method == 'onNfcTag') {
|
||||
final id = call.arguments;
|
||||
if (id is String) onTag(id);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/// Starts the ring immediately, without waiting for the alarm instant.
|
||||
///
|
||||
/// Exists so the foreground-service and full-screen-intent path can be
|
||||
|
||||
43
phone_app/lib/services/room_proof_settings.dart
Normal file
43
phone_app/lib/services/room_proof_settings.dart
Normal file
@ -0,0 +1,43 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Persisted room-proof configuration: the registered NFC tag and QR payload.
|
||||
///
|
||||
/// Registering nothing means that mechanism cannot satisfy the proof — it does
|
||||
/// not mean everything passes. See `RoomProof` for why redundancy matters.
|
||||
class RoomProofSettings {
|
||||
/// Creates settings with the registered values, if any.
|
||||
const RoomProofSettings({this.nfcTagId, this.qrPayload});
|
||||
|
||||
/// SharedPreferences key for the registered NFC tag id.
|
||||
static const String kNfcTagKey = 'roomProof.nfcTagId';
|
||||
|
||||
/// SharedPreferences key for the expected QR payload.
|
||||
static const String kQrKey = 'roomProof.qrPayload';
|
||||
|
||||
/// Lower-case hex id of the tag taped up in the other room.
|
||||
final String? nfcTagId;
|
||||
|
||||
/// Text encoded in the printed QR code in the other room.
|
||||
final String? qrPayload;
|
||||
|
||||
/// Loads the stored configuration.
|
||||
static Future<RoomProofSettings> load() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return RoomProofSettings(
|
||||
nfcTagId: prefs.getString(kNfcTagKey),
|
||||
qrPayload: prefs.getString(kQrKey),
|
||||
);
|
||||
}
|
||||
|
||||
/// Stores [tagId] as the registered NFC tag.
|
||||
static Future<void> saveNfcTag(String tagId) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(kNfcTagKey, tagId);
|
||||
}
|
||||
|
||||
/// Stores [payload] as the expected QR code text.
|
||||
static Future<void> saveQrPayload(String payload) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(kQrKey, payload);
|
||||
}
|
||||
}
|
||||
70
phone_app/test/ring_route_test.dart
Normal file
70
phone_app/test/ring_route_test.dart
Normal file
@ -0,0 +1,70 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:wake_alarm_sync/main.dart';
|
||||
import 'package:wake_alarm_sync/screens/ring_screen.dart';
|
||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||
const channel = MethodChannel(AlarmScheduler.channelName);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'stepCount') return 0;
|
||||
if (call.method == 'hasNfc') return false;
|
||||
return null;
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('the /ring route resolves to the ring screen', (tester) async {
|
||||
// AlarmActivity hands "/ring" to the engine as its initial route; if the
|
||||
// app does not resolve it the full-screen intent opens the home screen and
|
||||
// there is no dismiss path at all.
|
||||
await tester.pumpWidget(const WakeAlarmSyncApp());
|
||||
final state = tester.state<NavigatorState>(find.byType(Navigator));
|
||||
unawaited(state.pushNamed(kRingRoute));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(RingScreen), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('the ring screen shows the room gate before the challenge', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(const MaterialApp(home: RingScreen()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Wake up'), findsOneWidget);
|
||||
expect(find.text('Check steps'), findsOneWidget);
|
||||
// The challenge must not be reachable until the room proof is satisfied.
|
||||
expect(find.text('Dismiss'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('satisfying the room proof reveals the challenge', (
|
||||
tester,
|
||||
) async {
|
||||
const channel = MethodChannel(AlarmScheduler.channelName);
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'stepCount') return 500;
|
||||
if (call.method == 'hasNfc') return false;
|
||||
return null;
|
||||
});
|
||||
|
||||
await tester.pumpWidget(const MaterialApp(home: RingScreen()));
|
||||
await tester.pumpAndSettle();
|
||||
// The stopwatch starts at zero, so steps alone must not be enough yet.
|
||||
await tester.tap(find.text('Check steps'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Dismiss'), findsNothing);
|
||||
expect(find.textContaining('Keep moving'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
|
||||
/// Local helper so the test need not import dart:async for one call.
|
||||
void unawaited(Future<void> future) {}
|
||||
Loading…
Reference in New Issue
Block a user