Settings.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. #include <Settings.h>
  2. #include <ArduinoJson.h>
  3. #include <FS.h>
  4. #include <IntParsing.h>
  5. #include <algorithm>
  6. #define PORT_POSITION(s) ( s.indexOf(':') )
  7. bool Settings::hasAuthSettings() {
  8. return adminUsername.length() > 0 && adminPassword.length() > 0;
  9. }
  10. bool Settings::isAutoRestartEnabled() {
  11. return _autoRestartPeriod > 0;
  12. }
  13. size_t Settings::getAutoRestartPeriod() {
  14. if (_autoRestartPeriod == 0) {
  15. return 0;
  16. }
  17. return std::max(_autoRestartPeriod, static_cast<size_t>(MINIMUM_RESTART_PERIOD));
  18. }
  19. void Settings::deserialize(Settings& settings, String json) {
  20. DynamicJsonBuffer jsonBuffer;
  21. JsonObject& parsedSettings = jsonBuffer.parseObject(json);
  22. settings.patch(parsedSettings);
  23. }
  24. void Settings::updateDeviceIds(JsonArray& arr) {
  25. if (arr.success()) {
  26. if (this->deviceIds) {
  27. delete this->deviceIds;
  28. }
  29. this->deviceIds = new uint16_t[arr.size()];
  30. this->numDeviceIds = arr.size();
  31. arr.copyTo(this->deviceIds, arr.size());
  32. }
  33. }
  34. void Settings::updateGatewayConfigs(JsonArray& arr) {
  35. if (arr.success()) {
  36. if (this->gatewayConfigs) {
  37. delete[] this->gatewayConfigs;
  38. }
  39. this->gatewayConfigs = new GatewayConfig*[arr.size()];
  40. this->numGatewayConfigs = arr.size();
  41. for (size_t i = 0; i < arr.size(); i++) {
  42. JsonArray& params = arr[i];
  43. if (params.success() && params.size() == 3) {
  44. this->gatewayConfigs[i] = new GatewayConfig(parseInt<uint16_t>(params[0]), params[1], params[2]);
  45. } else {
  46. Serial.print(F("Settings - skipped parsing gateway ports settings for element #"));
  47. Serial.println(i);
  48. }
  49. }
  50. }
  51. }
  52. void Settings::updateGroupStateFields(JsonArray &arr) {
  53. if (arr.success()) {
  54. if (this->groupStateFields) {
  55. delete this->groupStateFields;
  56. }
  57. this->groupStateFields = new GroupStateField[arr.size()];
  58. this->numGroupStateFields = arr.size();
  59. for (size_t i = 0; i < arr.size(); i++) {
  60. String name = arr[i];
  61. name.toLowerCase();
  62. this->groupStateFields[i] = GroupStateFieldHelpers::getFieldByName(name.c_str());
  63. }
  64. }
  65. }
  66. void Settings::patch(JsonObject& parsedSettings) {
  67. if (parsedSettings.success()) {
  68. this->setIfPresent<String>(parsedSettings, "admin_username", adminUsername);
  69. this->setIfPresent(parsedSettings, "admin_password", adminPassword);
  70. this->setIfPresent(parsedSettings, "ce_pin", cePin);
  71. this->setIfPresent(parsedSettings, "csn_pin", csnPin);
  72. this->setIfPresent(parsedSettings, "reset_pin", resetPin);
  73. this->setIfPresent(parsedSettings, "led_pin", ledPin);
  74. this->setIfPresent(parsedSettings, "packet_repeats", packetRepeats);
  75. this->setIfPresent(parsedSettings, "http_repeat_factor", httpRepeatFactor);
  76. this->setIfPresent(parsedSettings, "auto_restart_period", _autoRestartPeriod);
  77. this->setIfPresent(parsedSettings, "mqtt_server", _mqttServer);
  78. this->setIfPresent(parsedSettings, "mqtt_username", mqttUsername);
  79. this->setIfPresent(parsedSettings, "mqtt_password", mqttPassword);
  80. this->setIfPresent(parsedSettings, "mqtt_topic_pattern", mqttTopicPattern);
  81. this->setIfPresent(parsedSettings, "mqtt_update_topic_pattern", mqttUpdateTopicPattern);
  82. this->setIfPresent(parsedSettings, "mqtt_state_topic_pattern", mqttStateTopicPattern);
  83. this->setIfPresent(parsedSettings, "mqtt_lwt_topic", mqttLwtTopic);
  84. this->setIfPresent(parsedSettings, "mqtt_lwt_message", mqttLwtMessage);
  85. this->setIfPresent(parsedSettings, "discovery_port", discoveryPort);
  86. this->setIfPresent(parsedSettings, "listen_repeats", listenRepeats);
  87. this->setIfPresent(parsedSettings, "state_flush_interval", stateFlushInterval);
  88. this->setIfPresent(parsedSettings, "mqtt_state_rate_limit", mqttStateRateLimit);
  89. this->setIfPresent(parsedSettings, "packet_repeat_throttle_threshold", packetRepeatThrottleThreshold);
  90. this->setIfPresent(parsedSettings, "packet_repeat_throttle_sensitivity", packetRepeatThrottleSensitivity);
  91. this->setIfPresent(parsedSettings, "packet_repeat_minimum", packetRepeatMinimum);
  92. this->setIfPresent(parsedSettings, "enable_automatic_mode_switching", enableAutomaticModeSwitching);
  93. this->setIfPresent(parsedSettings, "led_mode_packet_count", ledModePacketCount);
  94. this->setIfPresent(parsedSettings, "hostname", hostname);
  95. if (parsedSettings.containsKey("led_mode_wifi_config")) {
  96. this->ledModeWifiConfig = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_config"]);
  97. }
  98. if (parsedSettings.containsKey("led_mode_wifi_failed")) {
  99. this->ledModeWifiFailed = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_failed"]);
  100. }
  101. if (parsedSettings.containsKey("led_mode_operating")) {
  102. this->ledModeOperating = LEDStatus::stringToLEDMode(parsedSettings["led_mode_operating"]);
  103. }
  104. if (parsedSettings.containsKey("led_mode_packet")) {
  105. this->ledModePacket = LEDStatus::stringToLEDMode(parsedSettings["led_mode_packet"]);
  106. }
  107. if (parsedSettings.containsKey("radio_interface_type")) {
  108. this->radioInterfaceType = Settings::typeFromString(parsedSettings["radio_interface_type"]);
  109. }
  110. if (parsedSettings.containsKey("device_ids")) {
  111. JsonArray& arr = parsedSettings["device_ids"];
  112. updateDeviceIds(arr);
  113. }
  114. if (parsedSettings.containsKey("gateway_configs")) {
  115. JsonArray& arr = parsedSettings["gateway_configs"];
  116. updateGatewayConfigs(arr);
  117. }
  118. if (parsedSettings.containsKey("group_state_fields")) {
  119. JsonArray& arr = parsedSettings["group_state_fields"];
  120. updateGroupStateFields(arr);
  121. }
  122. }
  123. }
  124. void Settings::load(Settings& settings) {
  125. if (SPIFFS.exists(SETTINGS_FILE)) {
  126. File f = SPIFFS.open(SETTINGS_FILE, "r");
  127. String settingsContents = f.readStringUntil(SETTINGS_TERMINATOR);
  128. f.close();
  129. deserialize(settings, settingsContents);
  130. } else {
  131. settings.save();
  132. }
  133. }
  134. String Settings::toJson(const bool prettyPrint) {
  135. String buffer = "";
  136. StringStream s(buffer);
  137. serialize(s, prettyPrint);
  138. return buffer;
  139. }
  140. void Settings::save() {
  141. File f = SPIFFS.open(SETTINGS_FILE, "w");
  142. if (!f) {
  143. Serial.println(F("Opening settings file failed"));
  144. } else {
  145. serialize(f);
  146. f.close();
  147. }
  148. }
  149. void Settings::serialize(Stream& stream, const bool prettyPrint) {
  150. DynamicJsonBuffer jsonBuffer;
  151. JsonObject& root = jsonBuffer.createObject();
  152. root["admin_username"] = this->adminUsername;
  153. root["admin_password"] = this->adminPassword;
  154. root["ce_pin"] = this->cePin;
  155. root["csn_pin"] = this->csnPin;
  156. root["reset_pin"] = this->resetPin;
  157. root["led_pin"] = this->ledPin;
  158. root["radio_interface_type"] = typeToString(this->radioInterfaceType);
  159. root["packet_repeats"] = this->packetRepeats;
  160. root["http_repeat_factor"] = this->httpRepeatFactor;
  161. root["auto_restart_period"] = this->_autoRestartPeriod;
  162. root["mqtt_server"] = this->_mqttServer;
  163. root["mqtt_username"] = this->mqttUsername;
  164. root["mqtt_password"] = this->mqttPassword;
  165. root["mqtt_topic_pattern"] = this->mqttTopicPattern;
  166. root["mqtt_update_topic_pattern"] = this->mqttUpdateTopicPattern;
  167. root["mqtt_state_topic_pattern"] = this->mqttStateTopicPattern;
  168. root["mqtt_lwt_topic"] = this->mqttLwtTopic;
  169. root["mqtt_lwt_message"] = this->mqttLwtMessage;
  170. root["discovery_port"] = this->discoveryPort;
  171. root["listen_repeats"] = this->listenRepeats;
  172. root["state_flush_interval"] = this->stateFlushInterval;
  173. root["mqtt_state_rate_limit"] = this->mqttStateRateLimit;
  174. root["packet_repeat_throttle_sensitivity"] = this->packetRepeatThrottleSensitivity;
  175. root["packet_repeat_throttle_threshold"] = this->packetRepeatThrottleThreshold;
  176. root["packet_repeat_minimum"] = this->packetRepeatMinimum;
  177. root["enable_automatic_mode_switching"] = this->enableAutomaticModeSwitching;
  178. root["led_mode_wifi_config"] = LEDStatus::LEDModeToString(this->ledModeWifiConfig);
  179. root["led_mode_wifi_failed"] = LEDStatus::LEDModeToString(this->ledModeWifiFailed);
  180. root["led_mode_operating"] = LEDStatus::LEDModeToString(this->ledModeOperating);
  181. root["led_mode_packet"] = LEDStatus::LEDModeToString(this->ledModePacket);
  182. root["led_mode_packet_count"] = this->ledModePacketCount;
  183. root["hostname"] = this->hostname;
  184. if (this->deviceIds) {
  185. JsonArray& arr = jsonBuffer.createArray();
  186. arr.copyFrom(this->deviceIds, this->numDeviceIds);
  187. root["device_ids"] = arr;
  188. }
  189. if (this->gatewayConfigs) {
  190. JsonArray& arr = jsonBuffer.createArray();
  191. for (size_t i = 0; i < this->numGatewayConfigs; i++) {
  192. JsonArray& elmt = jsonBuffer.createArray();
  193. elmt.add(this->gatewayConfigs[i]->deviceId);
  194. elmt.add(this->gatewayConfigs[i]->port);
  195. elmt.add(this->gatewayConfigs[i]->protocolVersion);
  196. arr.add(elmt);
  197. }
  198. root["gateway_configs"] = arr;
  199. }
  200. if (this->groupStateFields) {
  201. JsonArray& arr = jsonBuffer.createArray();
  202. for (size_t i = 0; i < this->numGroupStateFields; i++) {
  203. arr.add(GroupStateFieldHelpers::getFieldName(this->groupStateFields[i]));
  204. }
  205. root["group_state_fields"] = arr;
  206. }
  207. if (prettyPrint) {
  208. root.prettyPrintTo(stream);
  209. } else {
  210. root.printTo(stream);
  211. }
  212. }
  213. String Settings::mqttServer() {
  214. int pos = PORT_POSITION(_mqttServer);
  215. if (pos == -1) {
  216. return _mqttServer;
  217. } else {
  218. return _mqttServer.substring(0, pos);
  219. }
  220. }
  221. uint16_t Settings::mqttPort() {
  222. int pos = PORT_POSITION(_mqttServer);
  223. if (pos == -1) {
  224. return DEFAULT_MQTT_PORT;
  225. } else {
  226. return atoi(_mqttServer.c_str() + pos + 1);
  227. }
  228. }
  229. RadioInterfaceType Settings::typeFromString(const String& s) {
  230. if (s.equalsIgnoreCase("lt8900")) {
  231. return LT8900;
  232. } else {
  233. return nRF24;
  234. }
  235. }
  236. String Settings::typeToString(RadioInterfaceType type) {
  237. switch (type) {
  238. case LT8900:
  239. return "LT8900";
  240. case nRF24:
  241. default:
  242. return "nRF24";
  243. }
  244. }