Exemple #1
0
void timers_restore(void) {

  if (! persist_exists(PERSIST_TIMERS_VERSION)) {
    timers_migrate_1();
    return;
  }

  if (TIMERS_VERSION_TINY == persist_read_int(PERSIST_TIMERS_VERSION)) {
    timers_migrate_2();
    return;
  }

  timers_clear();

  time_t now = time(NULL);
  uint16_t seconds_elapsed = 0;

  TimerBlock* block = NULL;
  if (persist_exists(PERSIST_TIMER_START)) {
    block = malloc(sizeof(TimerBlock));
    persist_read_data(PERSIST_TIMER_START, block, sizeof(TimerBlock));
    uint8_t num_timers = block->total_timers;
    uint8_t block_offset = 0;
    seconds_elapsed = now - block->save_time;

    for (uint8_t t = 0; t < num_timers; t += 1) {
      if (! block) {
        block = malloc(sizeof(TimerBlock));
        persist_read_data(PERSIST_TIMER_START + block_offset, block, sizeof(TimerBlock));
      }
      Timer* timer = timer_clone(&block->timers[t % TIMER_BLOCK_SIZE]);
      timers_add(timer);
      timer_restore(timer, seconds_elapsed);
      if (t % TIMER_BLOCK_SIZE == (TIMER_BLOCK_SIZE - 1)) {
        free(block);
        block = NULL;
        block_offset += 1;
      }
    }
    if (block) {
      free(block);
      block = NULL;
    }
  }
}
Exemple #2
0
status_t timers_restore(void) {
  timers_clear();

  if (! persist_exists(STORAGE_TIMER_START)) {
    return 0;
  }

  int block = 0;
  TimerBlock* timerBlock = malloc(sizeof(TimerBlock));
  persist_read_data(STORAGE_TIMER_START, timerBlock, sizeof(TimerBlock));

  uint8_t timer_count = timerBlock->count;
  int seconds_elapsed = 0;
  if (settings()->resume_timers) {
    int save_time = timerBlock->time;
    seconds_elapsed = time(NULL) - save_time;
  }

  for (int t = 0; t < timer_count; t += 1) {

    if (t > 0 && t % TIMER_BLOCK_SIZE == 0) {
      block += 1;
      free_safe(timerBlock);
      timerBlock = malloc(sizeof(TimerBlock));
      persist_read_data(STORAGE_TIMER_START + block, timerBlock, sizeof(TimerBlock));
    }

    Timer* timer = timer_clone(&timerBlock->timers[t % TIMER_BLOCK_SIZE]);
    timers_add(timer);

    timer->app_timer = NULL;
    if (! settings()->resume_timers) {
      timer_reset(timer);
      continue;
    }
    if (TIMER_STATUS_RUNNING != timer->status) {
      continue;
    }
    if (TIMER_DIRECTION_UP == timer->direction) {
      timer->time_left += seconds_elapsed;
    }
    else {
      if (true == timer->repeat) {
        timer->time_left -= (seconds_elapsed % timer->length);
        if (timer->time_left <= 0) {
          timer->time_left += timer->length;
        }
      }
      else {
        timer->time_left -= seconds_elapsed;
        if (0 >= timer->time_left) {
          timer->time_left = 0;
          timer->status = TIMER_STATUS_FINISHED;
          continue;
        }
      }
    }
    timer_resume(timer);
  }
  free_safe(timerBlock);
  return 0;
}