summaryrefslogtreecommitdiff
path: root/src/system_fsm/idle.cpp
blob: 91075fc6ee6ddcf67d3dfee5f731da1401d0f150 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
 * Copyright 2023 jacqueline <me@jacqueline.id.au>
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#include "app_console.hpp"
#include "file_gatherer.hpp"
#include "freertos/portmacro.h"
#include "freertos/projdefs.h"
#include "gpios.hpp"
#include "result.hpp"

#include "audio_fsm.hpp"
#include "event_queue.hpp"
#include "storage.hpp"
#include "system_events.hpp"
#include "system_fsm.hpp"
#include "ui_fsm.hpp"

namespace system_fsm {
namespace states {

static const char kTag[] = "IDLE";
static const TickType_t kTicksBeforeSleep = pdMS_TO_TICKS(10000);

static void timer_callback(TimerHandle_t timer) {
  events::System().Dispatch(internal::IdleTimeout{});
}

/*
 * Ensure the storage and database are both available. If either of these fails
 * to open, then we assume it's an issue with the underlying SD card.
 */
void Idle::entry() {
  ESP_LOGI(kTag, "system became idle");
  events::Audio().Dispatch(OnIdle{});
  events::Ui().Dispatch(OnIdle{});

  sIdleTimeout = xTimerCreate("idle_timeout", kTicksBeforeSleep, false, NULL,
                              timer_callback);
  xTimerStart(sIdleTimeout, portMAX_DELAY);
}

void Idle::exit() {
  xTimerStop(sIdleTimeout, portMAX_DELAY);
  xTimerDelete(sIdleTimeout, portMAX_DELAY);
  ESP_LOGI(kTag, "system left idle");
}

void Idle::react(const KeyLockChanged& ev) {
  if (!ev.falling) {
    transit<Running>();
  }
}

void Idle::react(const internal::IdleTimeout& ev) {
  ESP_LOGI(kTag, "system shutting down");

  // FIXME: It would be neater to just free a bunch of our pointers, deinit the
  // other state machines, etc.
  if (sTouch) {
    sTouch->PowerDown();
  }

  // Pull down to turn things off
  sGpios->WriteBuffered(drivers::IGpios::Pin::kAmplifierEnable, false);
  sGpios->WriteBuffered(drivers::IGpios::Pin::kSdPowerEnable, false);
  sGpios->WriteBuffered(drivers::IGpios::Pin::kDisplayEnable, false);

  // Leave up to match the external pullups
  sGpios->WriteBuffered(drivers::IGpios::Pin::kSdMuxSwitch, true);
  sGpios->WriteBuffered(drivers::IGpios::Pin::kSdMuxDisable, true);

  // Pull down to prevent sourcing current uselessly from input pins.
  sGpios->WriteBuffered(drivers::IGpios::Pin::kSdCardDetect, false);
  sGpios->WriteBuffered(drivers::IGpios::Pin::kKeyUp, false);
  sGpios->WriteBuffered(drivers::IGpios::Pin::kKeyDown, false);

  sGpios->Flush();

  sSamd->PowerDown();
}

}  // namespace states
}  // namespace system_fsm