forked from dastels/neo_pixel_state_machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate_machine.cpp
126 lines (104 loc) · 2.33 KB
/
state_machine.cpp
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// -*- mode: c++ -*-
// State Machine
//
// Copyright (c) 2021 Dave Astels
#include <string.h>
#include <Arduino.h>
#include "state_machine.h"
uint8_t colour_data[4] = {0, 0, 0, 0};
StateMachine::StateMachine()
: _current_state(NULL)
, _initial_state_name(nullptr)
, _number_of_states(0)
{
}
bool StateMachine::add_state(State *state)
{
if (_number_of_states == MAX_STATES) {
Serial.print("Adding state ");
Serial.print(state->name());
Serial.println(" failed");
return false;
}
_states[_number_of_states++] = state;
if (!_initial_state_name) {
_initial_state_name = state->name();
}
return true;
}
bool StateMachine::reset()
{
if (go_to_state(_initial_state_name, colour_data)) {
return true;
}
Serial.print("Resetting to ");
Serial.print(_initial_state_name);
Serial.println(" failed!");
return false;
}
State *StateMachine::find_state(char *state_name)
{
for (int index = 0; index < _number_of_states; index++) {
if (_states[index]->is_named(state_name)) {
return _states[index];
}
}
return nullptr;
}
bool StateMachine::go_to_state(char *state_name, uint8_t *data)
{
if (!state_name || !*state_name) { // no state name
Serial.println("No state name to go to");
return false;
}
State *new_state = find_state(state_name);
if (new_state == nullptr) { // bad state name
Serial.print("No state named ");
Serial.println(state_name);
return false;
}
if (_current_state) {
_current_state->exit();
}
_current_state = new_state;
_current_state->enter(data);
return true;
}
void StateMachine::tick(uint32_t now)
{
if (_current_state) {
_current_state->tick(now);
}
}
void StateMachine::mode_button()
{
if (_current_state) {
_current_state->mode_button();
}
}
void StateMachine::red_button()
{
if (_current_state) {
_current_state->red_button();
}
}
void StateMachine::green_button()
{
if (_current_state) {
_current_state->green_button();
}
}
void StateMachine::blue_button()
{
if (_current_state) {
_current_state->blue_button();
}
}
const char *StateMachine::current_state_name()
{
if (_current_state) {
return _current_state->name();
} else {
return "NOT_SET";
}
}