togglePeriodically method

Future<void> togglePeriodically({
  1. required Duration onOffInterval,
  2. Duration stopAfterDuration = const Duration(hours: 1),
  3. bool disableTorchRandomlyInSeconds = false,
  4. bool disableTorchRandomlyInMinutes = false,
  5. bool disableTorchRandomlyInHours = false,
})

Toggles the torch (flashlight) periodically at specified intervals. onOffInterval - The interval between on/off toggles. stopAfterDuration - The duration after which to stop toggling (default: 1 hour). disableTorchRandomlyInSeconds - If true, randomly stops after a number of seconds. disableTorchRandomlyInMinutes - If true, randomly stops after a number of minutes. disableTorchRandomlyInHours - If true, randomly stops after a number of hours.

Implementation

Future<void> togglePeriodically({
  required Duration onOffInterval,
  Duration stopAfterDuration = const Duration(hours: 1),
  bool disableTorchRandomlyInSeconds = false,
  bool disableTorchRandomlyInMinutes = false,
  bool disableTorchRandomlyInHours = false,
}) async {
  _cancelAllTimers();
  bool isTorchEnabled = false;
  int randomSeconds = Random().nextInt(60);
  int randomMinutes = Random().nextInt(60);
  int randomHours = Random().nextInt(24);

  void toggleTorch() async {
    try {
      if (isTorchEnabled) {
        await TorchFlashlight.disableTorchFlashlight();
      } else {
        await TorchFlashlight.enableTorchFlashlight();
      }
      isTorchEnabled = !isTorchEnabled;
    } catch (e) {
      debugPrint('Error toggling torch: $e');
    }
  }

  _periodicTimer = Timer.periodic(onOffInterval, (timer) {
    toggleTorch();
  });

  Timer(stopAfterDuration, () async {
    _periodicTimer?.cancel();
    if (isTorchEnabled) {
      try {
        await TorchFlashlight.disableTorchFlashlight();
        isTorchEnabled = false;
      } catch (e) {
        debugPrint('Error disabling torch: $e');
      }
    }
  });

  List<Future> futures = [];

  if (disableTorchRandomlyInSeconds) {
    futures.add(Future.delayed(Duration(seconds: randomSeconds)));
  }

  if (disableTorchRandomlyInMinutes) {
    futures.add(Future.delayed(Duration(minutes: randomMinutes)));
  }

  if (disableTorchRandomlyInHours) {
    futures.add(Future.delayed(Duration(hours: randomHours)));
  }

  if (futures.isNotEmpty) {
    await Future.any(futures);
    _periodicTimer?.cancel();
    if (isTorchEnabled) {
      try {
        await TorchFlashlight.disableTorchFlashlight();
        isTorchEnabled = false;
      } catch (e) {
        debugPrint('Error disabling torch: $e');
      }
    }
  }
}