wake-alarm/phone_app/lib/services/alarm_scheduler.dart
Krzysztof kuhy Rudnicki cb50e58a56 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
2026-08-27 21:28:24 +02:00

82 lines
3.3 KiB
Dart

import 'package:flutter/services.dart';
/// Dart side of the single MethodChannel the Kotlin ring path exposes.
///
/// One channel for the whole feature (see `AlarmChannel.kt`): the alarm must
/// never depend on a pub plugin compiling against AGP 9.
class AlarmScheduler {
/// Creates a scheduler; [channel] is injectable so tests need no platform.
AlarmScheduler({MethodChannel? channel})
: _channel = channel ?? const MethodChannel(channelName);
/// Channel name, matching `AlarmActivity.CHANNEL` on the Kotlin side.
static const String channelName = 'com.kuhy.wake_alarm_sync/alarm';
final MethodChannel _channel;
/// Arms the alarm for the next occurrence of [hour]:[minute] in local time.
///
/// The phone rings **daily**, matching the PC's `ALARM_DAYS` which is
/// currently all seven days. The two are deliberately not synced — a shared
/// day set is item 8's shape, and diverging defaults would have the halves
/// firing on different days.
Future<void> schedule(int hour, int minute) =>
_channel.invokeMethod<void>('schedule', <String, int>{
'hour': hour,
'minute': minute,
});
/// Cancels the armed alarm and forgets the stored time.
Future<void> cancel() => _channel.invokeMethod<void>('cancel');
/// Re-arms from the stored time; false when no alarm was ever set.
///
/// Called from the app's init seam because the store has no change stream:
/// without this, an app restart that does not touch the picker would leave
/// nothing armed.
Future<bool> rearm() async =>
await _channel.invokeMethod<bool>('rearm') ?? false;
/// Stops the ring and immediately re-arms for tomorrow.
Future<void> dismiss() => _channel.invokeMethod<void>('dismiss');
/// Whether the system will honour the full-screen intent.
///
/// False from API 34 unless granted. The caller must treat this as a hard
/// failure: without it the alarm posts a notification the sleeper never sees.
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
/// exercised on an emulator; it arms nothing and changes no stored time.
Future<void> ringNow() => _channel.invokeMethod<void>('ringNow');
/// Captures the step baseline for this ring.
Future<void> beginStepCount() =>
_channel.invokeMethod<void>('beginStepCount');
/// Steps since [beginStepCount], or -1 when unavailable.
Future<int> stepsSinceRingStart() async =>
await _channel.invokeMethod<int>('stepCount') ?? -1;
}