Settings.cpp 11 KB

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