简体   繁体   中英

State design pattern usage in embedded software

I have been solving following problem. I'm a newbie in C++ and I need to implement a state machine for an embedded software. This state machine should constitute core of an application logic. It should control transitions between states "STANDSTILL", "RUN" and "FAULT" of a controller. These transitions occur based on: logic inputs state, analog inputs state, messages received over communication lines and messages created internally in the controller's software.

I would like to implement this state machine in such a manner that I utilize the power of the C++ (object oriented programming). So I have spent some time in looking for some appropriate design pattern. I have found the "state" desing pattern but I am not sure whether it is a good choice for me. As far as I understand the definition in right manner it is intended for situations when I have some object (so called context object) which behavior (methods of its public interface) is strongly dependent on its state.

My first idea was that the so called context object could be the controller itself. (I mean a class which will realize the software model of the whole device.) The state dependent methods could be the methods asociated with the above mentioned inputs processed by the state machine ie logic inputs, analog inputs, messages received over communication lines and internal messages. But I am not sure whether it is good approach. Does anybody have any experience with such usage of the state design pattern? Thanks for any suggestions.

Just because you are using C++, you are not necessarily using object-oriented design. Nor do you have to use OOD when implementing trivial things. It is quite feasible to implement a state machine without involving OOD, since it is such a simple data structure. Basically it is just an array (of function pointers) with named members.

The "pattern" is known as finite state machine . A typical C implementation for embedded systems can be found here . You could write a simple class around that array. State machines in embedded systems are almost always static and read-only, so the class would have to be a "Singleton". You'll find that there's no obvious benefit of using a class here.

the state pattern is a good design to start with. But as mentioned, there are existing tools that can generate the code for you. Another one you could look at is http://scxmlcc.org . This one create code that uses 'the power of C++' and is also based on the state pattern design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM