SerializableJSONStateMachine.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-09-17
  6. * Changed: 2020-11-06
  7. *
  8. * */
  9. #include "../../../../../include/ls_std/serialization/logic/SerializableJSONStateMachine.hpp"
  10. #include "../../../../../include/ls_std/serialization/logic/SerializableJSONState.hpp"
  11. ls_std::SerializableJSONStateMachine::SerializableJSONStateMachine(std::shared_ptr<StateMachine> _value) :
  12. Class("SerializableJSONStateMachine"),
  13. value(std::move(_value))
  14. {}
  15. ls_std::byte_field ls_std::SerializableJSONStateMachine::marshal()
  16. {
  17. this->_update();
  18. return this->jsonObject.dump();
  19. }
  20. void ls_std::SerializableJSONStateMachine::unmarshal(const ls_std::byte_field &_data)
  21. {
  22. this->jsonObject = nlohmann::json::parse(_data);
  23. this->_unmarshalStates();
  24. this->_unmarshalCurrentState();
  25. this->value->setMemory(this->jsonObject["memory"]);
  26. this->value->setName(this->jsonObject["name"]);
  27. }
  28. void ls_std::SerializableJSONStateMachine::_unmarshalCurrentState()
  29. {
  30. if(this->jsonObject.contains("currentState")) {
  31. this->value->setStartState(this->jsonObject["currentState"]);
  32. }
  33. }
  34. void ls_std::SerializableJSONStateMachine::_unmarshalStates()
  35. {
  36. for(const auto& serializedState : this->jsonObject["states"]) {
  37. std::shared_ptr<ls_std::State> state = std::make_shared<ls_std::State>("");
  38. ls_std::SerializableJSONState{state}.unmarshal(serializedState.dump());
  39. this->value->addState(state);
  40. }
  41. }
  42. void ls_std::SerializableJSONStateMachine::_update()
  43. {
  44. this->_updateCurrentState();
  45. this->jsonObject["memory"] = this->value->getMemory();
  46. this->jsonObject["name"] = this->value->getName();
  47. this->_updateStates();
  48. }
  49. void ls_std::SerializableJSONStateMachine::_updateCurrentState()
  50. {
  51. if(this->value->getCurrentState() != nullptr) {
  52. this->jsonObject["currentState"] = this->value->getCurrentState()->getId();
  53. }
  54. }
  55. void ls_std::SerializableJSONStateMachine::_updateStates()
  56. {
  57. std::string jsonString {};
  58. for(const auto& state : this->value->getStates()) {
  59. jsonString = ls_std::SerializableJSONState{state.second}.marshal();
  60. this->jsonObject["states"][state.first] = nlohmann::json::parse(jsonString);
  61. }
  62. }