Skip to content

Commit

Permalink
Updated to 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Mateusz Pusz committed Sep 30, 2018
1 parent 69c9c59 commit 4861d5f
Show file tree
Hide file tree
Showing 19 changed files with 652 additions and 156 deletions.
6 changes: 3 additions & 3 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

cmake_minimum_required(VERSION 3.5)
project(fsm_variant)
cmake_minimum_required(VERSION 3.8)
project(fsm_dev)

# set path to custom cmake modules
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/common/cmake")
Expand All @@ -36,4 +36,4 @@ include(compile_flags)
add_subdirectory(src)

# add_examples
add_subdirectory(examples)
add_subdirectory(example)
48 changes: 48 additions & 0 deletions INSTALL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Installation and Reuse

There are a few different ways of installing/reusing `mp::fsm` in your project

## Copy

`mp::fsm` is a standalone header-only library without any additional dependencies.
It can be simply copied to your source tree and used as a regular header file.

## cmake

To use `mp::fsm` as a `cmake` imported library exported as `cmake` target via `cmake`
configuration files following steps may be done.

### cmake install

```bash
mkdir build && cd build
cmake ../src -DCMAKE_INSTALL_PREFIX=<your_cmake_installation_dir> <your_cmake_configuration>
cmake --build . --target install <your_cmake_configuration>
```

To use such `cmake` target in your project it is enough to add following line to your `CMakeList.txt` file

```cmake
find_package(fsm CONFIG REQUIRED)
```

and configure it with

```bash
cmake .. -DCMAKE_INSTALL_PREFIX=<your_cmake_installation_dir> <your_cmake_configuration>
```

### cmake + conan

To use `mp::fsm` with `cmake` via `conan` it is enough to:
- add following remote to your local `conan` instance

```bash
conan remote add conan-mpusz https://api.bintray.com/conan/mpusz/conan-mpusz
```

- add following dependency to your `conanfile.txt` or `conanfile.py` files:

```python
requires = "fsm-variant/1.0.0@mpusz/stable"
```
File renamed without changes.
53 changes: 51 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,56 @@
# mp::fsm

Finite State Machine implementation using `std::variant` and `std::optional` under the hood.
Implementation of Finite State Machine presented by me on CppCon 2018 in a talk
[Effective replacement of dynamic polymorphism with std::variant](https://github.com/CppCon/CppCon2018/blob/master/Presentations/effective_replacement_of_dynamic_polymorphism_with_stdvariant/effective_replacement_of_dynamic_polymorphism_with_stdvariant__mateusz_pusz__cppcon_2018.pdf).

Based on:
It uses `std::variant` and `std::optional` under the hood.


## How to?

FSM works with any types defining **events**. **State** is represented by any type too.
All states have to be put into the variant and the initial state should appear the first
on the list. Both states and events can be stateful.

```cpp
#include <mp/fsm.h>

struct event_connect {};
struct event_disconnect {};

struct state_idle {};
struct state_connected {};

using state = std::variant<state_idle, state_connected>;

class sample_fsm : public mp::fsm<sample_fsm, state> {
public:
template<typename State, typename Event>
auto on_event(State&, const Event&) { return std::nullopt; }

auto on_event(state_idle&, const event_connect&) { return state_connected{}; }
auto on_event(state_connected&, const event_disconnect&) { return state_idle{}; }
};

int main()
{
sample_fsm fsm;
fsm.dispatch(event_connect());
fsm.dispatch(event_disconnect());
}
```
## Building, testing and installation
For detailed information on project compilation, testing and reuse please refer to
[INSTALL.md](INSTALL.md).
## Acknowledgements
The FSM design was inspired by:
- http://khuttun.github.io/2017/02/04/implementing-state-machines-with-std-variant.html
- http://mooooo.ooo/sumtypes-and-statemachines/
Thank you!
2 changes: 1 addition & 1 deletion cmake/common
58 changes: 58 additions & 0 deletions conanfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# The MIT License (MIT)
#
# Copyright (c) 2017 Mateusz Pusz
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from conans import ConanFile, CMake

class FsmVariantConan(ConanFile):
name = "fsm-variant"
version = "1.0.0"
description = "Finite State Machine implementation using `std::variant` and `std::optional` under the hood"
author = "Mateusz Pusz"
license = "https://github.com/mpusz/fsm-variant/blob/master/LICENSE.md"
url = "https://github.com/mpusz/fsm-variant"
exports = ["LICENSE.md"]
settings = "os", "compiler", "build_type", "arch"
scm = {
"type": "git",
"url": "auto",
"revision": "auto"
}

def _configure_cmake(self):
cmake = CMake(self)
cmake.configure(source_folder="src")
return cmake

def build(self):
cmake = self._configure_cmake()
cmake.build()

def package(self):
self.copy("license*", dst="licenses", ignore_case=True, keep_path=False)
cmake = self._configure_cmake()
cmake.install()

def package_info(self):
self.cpp_info.libs = ["fsm"]

def package_id(self):
self.info.header_only()
10 changes: 3 additions & 7 deletions examples/CMakeLists.txt → example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,10 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/../cmake/common/cmake")
# include common tools and workarounds
include(tools)

# use Conan configuration if available
conan_init()

# add dependencies
if(NOT TARGET mp::fsm)
find_package(fsm_variant CONFIG REQUIRED)
find_package(fsm CONFIG REQUIRED)
endif()

add_executable(connection_fsm connection_fsm.cpp)
target_link_libraries(connection_fsm
PRIVATE mp::fsm)
add_subdirectory(connection_fsm)
add_subdirectory(tcp_fsm)
28 changes: 28 additions & 0 deletions example/connection_fsm/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# The MIT License (MIT)
#
# Copyright (c) 2016 Mateusz Pusz
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


add_executable(connection_fsm
connection_fsm.h
connection_fsm_tests.cpp
)
target_link_libraries(connection_fsm PRIVATE mp::fsm)
70 changes: 70 additions & 0 deletions example/connection_fsm/connection_fsm.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// The MIT License (MIT)
//
// Copyright (c) 2017 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#pragma once

#include "mp/fsm.h"
#include <iostream>
#include <string_view>

struct event_connect { std::string_view address; };
struct event_connected {};
struct event_disconnect {};
struct event_timeout {};

struct state_idle {
state_idle() { std::cout << "Idle\n"; }
};

struct state_connecting {
static constexpr int n_max = 3;
int n = 0;
std::string address;
explicit state_connecting(std::string address_) : address(std::move(address_))
{
std::cout << "Connecting to: " << address << '\n';
}
};

struct state_connected {
state_connected() { std::cout << "Connected\n"; }
};

using state = std::variant<state_idle, state_connecting, state_connected>;

class connection_fsm : public mp::fsm<connection_fsm, state> {
public:
template<typename State, typename Event>
auto on_event(State&, const Event&)
{
std::cout << "Invalid transition\n";
return std::nullopt;
}

auto on_event(state_idle&, const event_connect& e) { return state_connecting{std::string(e.address)}; }
auto on_event(state_connecting&, const event_connected&) { return state_connected{}; }
auto on_event(state_connecting& s, const event_timeout&)
{
return ++s.n < state_connecting::n_max ? std::nullopt : std::optional<state>(state_idle{});
}
auto on_event(state_connected&, const event_disconnect&) { return state_idle{}; }
};
65 changes: 65 additions & 0 deletions example/connection_fsm/connection_fsm_tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// The MIT License (MIT)
//
// Copyright (c) 2017 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "connection_fsm.h"

template<typename Fsm, typename... Events>
void dispatch(Fsm& fsm, Events&&... events)
{
(fsm.dispatch(std::forward<Events>(events)), ...);
}

void sequence_1()
{
std::cout << "\nSequence #1\n";
connection_fsm fsm;
dispatch(fsm, event_connect{"train-it.eu"}, event_connected{}, event_disconnect{});
}

void sequence_2()
{
std::cout << "\nSequence #2\n";
connection_fsm fsm;
dispatch(fsm, event_connect{"train-it.eu"}, event_timeout{}, event_connected{}, event_disconnect{});
}

void sequence_3()
{
std::cout << "\nSequence #3\n";
connection_fsm fsm;
dispatch(fsm, event_connect{"train-it.eu"}, event_timeout{}, event_timeout{}, event_timeout{});
}

int main()
{
try {
sequence_1();
sequence_2();
sequence_3();
}
catch(const std::exception& ex) {
std::cerr << "Unhandled std exception caught: " << ex.what() << '\n';
}
catch(...) {
std::cerr << "Unhandled unknown exception caught\n";
}
}
Loading

0 comments on commit 4861d5f

Please sign in to comment.