2
* fsm-states.c: State-handling functions for SpaghettiMonster.
4
* Copyright (C) 2017 Selene Scriven
6
* This program is free software: you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License as published by
8
* the Free Software Foundation, either version 3 of the License, or
9
* (at your option) any later version.
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
* GNU General Public License for more details.
16
* You should have received a copy of the GNU General Public License
17
* along with this program. If not, see <http://www.gnu.org/licenses/>.
23
#include "fsm-states.h"
26
// TODO: if callback doesn't handle current event,
27
// pass event to next state on stack?
28
// Callback return values:
29
// 0: event handled normally
30
// 1: event not handled
31
// 255: error (not sure what this would even mean though, or what difference it would make)
32
// TODO: function to call stacked callbacks until one returns "handled"
34
void _set_state(StatePtr new_state, uint16_t arg,
35
EventPtr exit_event, EventPtr enter_event) {
36
// call old state-exit hook (don't use stack)
37
if (current_state != NULL) current_state(exit_event, arg);
39
current_state = new_state;
40
// call new state-enter hook (don't use stack)
41
if (new_state != NULL) current_state(enter_event, arg);
44
int8_t push_state(StatePtr new_state, uint16_t arg) {
45
if (state_stack_len < STATE_STACK_SIZE) {
46
// TODO: call old state's exit hook?
47
// new hook for non-exit recursion into child?
48
state_stack[state_stack_len] = new_state;
50
// FIXME: use EV_stacked_state?
51
_set_state(new_state, arg, EV_leave_state, EV_enter_state);
52
return state_stack_len;
54
// TODO: um... how is a flashlight supposed to handle a recursion depth error?
59
StatePtr pop_state() {
60
// TODO: how to handle pop from empty stack?
61
StatePtr old_state = NULL;
62
StatePtr new_state = NULL;
63
if (state_stack_len > 0) {
65
old_state = state_stack[state_stack_len];
67
if (state_stack_len > 0) {
68
new_state = state_stack[state_stack_len-1];
70
// FIXME: what should 'arg' be? (maybe re-entry should be entry with arg+1?)
71
_set_state(new_state, 0, EV_leave_state, EV_reenter_state);
75
uint8_t set_state(StatePtr new_state, uint16_t arg) {
76
// FIXME: this calls exit/enter hooks it shouldn't
77
// (for the layer underneath the top)
79
return push_state(new_state, arg);
82
#ifndef DONT_USE_DEFAULT_STATE
83
// bottom state on stack
84
// handles default actions for LVP, thermal regulation, etc
85
uint8_t default_state(EventPtr event, uint16_t arg) {
86
if (0) {} // this should get compiled out
89
else if (event == EV_voltage_low) {
96
#ifdef USE_THERMAL_REGULATION
97
else if (event == EV_temperature_high) {
102
else if (event == EV_temperature_low) {
110
return EVENT_NOT_HANDLED;