ModuleSwitch.cpp 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include "ModuleBase.h"
  2. #include <iostream>
  3. namespace mdd{
  4. class ModuleSwitch : public ModuleBase {
  5. public:
  6. ModuleSwitch();
  7. bool configure(const std::string& config) override;
  8. std::string getConfiguration() override;
  9. state update() override;
  10. };
  11. ModuleSwitch::ModuleSwitch()
  12. :ModuleBase(R"JSON(
  13. [{
  14. "name":"size",
  15. "value": 1
  16. }])JSON")
  17. {
  18. std::vector<double> default_val = { 1 };
  19. inputs.push_back(std::make_shared<Input>(this, "Switch", 0, default_val));
  20. inputs.push_back(std::make_shared<Input>(this, "Default", 0, default_val));
  21. outputs.push_back(std::make_shared<Output>(this, "Value", 0, default_val));
  22. key = "ModuleSwitch";
  23. setName("Switch");
  24. }
  25. bool ModuleSwitch::configure(const std::string& config) {
  26. json config_parsed = json::parse(config);
  27. for (size_t i = 0; i < config_parsed.size(); i++)
  28. {
  29. if (config_parsed[i].contains("name"))
  30. {
  31. if (config_parsed[i]["name"].get<std::string>() == "size")
  32. {
  33. size_t length = config_parsed[i]["value"].get<size_t>();
  34. if (length != inputs.size() -1)
  35. {
  36. size_t length_before = inputs.size();
  37. if (length_before != 1)
  38. {
  39. inputs.back()->setName("Value");
  40. }
  41. for (size_t j = length_before - 1; j < length; j++)
  42. {
  43. inputs.push_back(std::make_shared<Input>(this, "Value", inputs.size() - 1, std::vector<double>{1}));
  44. }
  45. for (size_t j = length; j < length_before-1; j++)
  46. {
  47. inputs.pop_back();
  48. }
  49. if (length != 0)
  50. {
  51. inputs.back()->setName("Default");
  52. }
  53. }
  54. return true;
  55. }
  56. }
  57. }
  58. return false;
  59. }
  60. std::string ModuleSwitch::getConfiguration() {
  61. json ret = json::parse(ModuleBase::getConfiguration());
  62. for (size_t i = 0; i < ret.size(); i++)
  63. {
  64. if (ret[i].contains("name"))
  65. {
  66. if (ret[i]["name"].get<std::string>() == "size")
  67. {
  68. ret[i]["value"] = inputs.size() - 1;
  69. }
  70. }
  71. }
  72. return ret.dump();
  73. }
  74. state ModuleSwitch::update(){
  75. std::vector<double> ret;
  76. size_t length = getInput(0)->getValue().size();
  77. for (size_t i = 0; i < length; i++)
  78. {
  79. int index = (int)getInput(0)->getValue()[i];
  80. if (index == 0) {
  81. index = 1;
  82. }
  83. if (index > inputs.size() - 1) {
  84. index = inputs.size() - 1;
  85. }
  86. for (size_t j = 0; j < getInput(index)->getValue().size(); j++)
  87. {
  88. ret.push_back(getInput(index)->getValue()[j]);
  89. }
  90. }
  91. return getOutput(0)->setValue(ret);
  92. }
  93. }