Settings.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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_client_status_topic", mqttClientStatusTopic);
  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. this->setIfPresent(parsedSettings, "wifi_static_ip", wifiStaticIP);
  96. this->setIfPresent(parsedSettings, "wifi_static_ip_gateway", wifiStaticIPGateway);
  97. this->setIfPresent(parsedSettings, "wifi_static_ip_netmask", wifiStaticIPNetmask);
  98. if (parsedSettings.containsKey("rf24_channels")) {
  99. JsonArray& arr = parsedSettings["rf24_channels"];
  100. rf24Channels = JsonHelpers::jsonArrToVector<RF24Channel>(arr, RF24ChannelHelpers::valueFromName);
  101. }
  102. if (parsedSettings.containsKey("rf24_listen_channel")) {
  103. this->rf24ListenChannel = RF24ChannelHelpers::valueFromName(parsedSettings["rf24_listen_channel"]);
  104. }
  105. if (parsedSettings.containsKey("rf24_power_level")) {
  106. this->rf24PowerLevel = RF24PowerLevelHelpers::valueFromName(parsedSettings["rf24_power_level"]);
  107. }
  108. if (parsedSettings.containsKey("led_mode_wifi_config")) {
  109. this->ledModeWifiConfig = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_config"]);
  110. }
  111. if (parsedSettings.containsKey("led_mode_wifi_failed")) {
  112. this->ledModeWifiFailed = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_failed"]);
  113. }
  114. if (parsedSettings.containsKey("led_mode_operating")) {
  115. this->ledModeOperating = LEDStatus::stringToLEDMode(parsedSettings["led_mode_operating"]);
  116. }
  117. if (parsedSettings.containsKey("led_mode_packet")) {
  118. this->ledModePacket = LEDStatus::stringToLEDMode(parsedSettings["led_mode_packet"]);
  119. }
  120. if (parsedSettings.containsKey("radio_interface_type")) {
  121. this->radioInterfaceType = Settings::typeFromString(parsedSettings["radio_interface_type"]);
  122. }
  123. if (parsedSettings.containsKey("device_ids")) {
  124. JsonArray& arr = parsedSettings["device_ids"];
  125. updateDeviceIds(arr);
  126. }
  127. if (parsedSettings.containsKey("gateway_configs")) {
  128. JsonArray& arr = parsedSettings["gateway_configs"];
  129. updateGatewayConfigs(arr);
  130. }
  131. if (parsedSettings.containsKey("group_state_fields")) {
  132. JsonArray& arr = parsedSettings["group_state_fields"];
  133. updateGroupStateFields(arr);
  134. }
  135. }
  136. }
  137. void Settings::load(Settings& settings) {
  138. if (SPIFFS.exists(SETTINGS_FILE)) {
  139. // Clear in-memory settings
  140. settings = Settings();
  141. File f = SPIFFS.open(SETTINGS_FILE, "r");
  142. String settingsContents = f.readStringUntil(SETTINGS_TERMINATOR);
  143. f.close();
  144. deserialize(settings, settingsContents);
  145. } else {
  146. settings.save();
  147. }
  148. }
  149. String Settings::toJson(const bool prettyPrint) {
  150. String buffer = "";
  151. StringStream s(buffer);
  152. serialize(s, prettyPrint);
  153. return buffer;
  154. }
  155. void Settings::save() {
  156. File f = SPIFFS.open(SETTINGS_FILE, "w");
  157. if (!f) {
  158. Serial.println(F("Opening settings file failed"));
  159. } else {
  160. serialize(f);
  161. f.close();
  162. }
  163. }
  164. void Settings::serialize(Stream& stream, const bool prettyPrint) {
  165. DynamicJsonBuffer jsonBuffer;
  166. JsonObject& root = jsonBuffer.createObject();
  167. root["admin_username"] = this->adminUsername;
  168. root["admin_password"] = this->adminPassword;
  169. root["ce_pin"] = this->cePin;
  170. root["csn_pin"] = this->csnPin;
  171. root["reset_pin"] = this->resetPin;
  172. root["led_pin"] = this->ledPin;
  173. root["radio_interface_type"] = typeToString(this->radioInterfaceType);
  174. root["packet_repeats"] = this->packetRepeats;
  175. root["http_repeat_factor"] = this->httpRepeatFactor;
  176. root["auto_restart_period"] = this->_autoRestartPeriod;
  177. root["mqtt_server"] = this->_mqttServer;
  178. root["mqtt_username"] = this->mqttUsername;
  179. root["mqtt_password"] = this->mqttPassword;
  180. root["mqtt_topic_pattern"] = this->mqttTopicPattern;
  181. root["mqtt_update_topic_pattern"] = this->mqttUpdateTopicPattern;
  182. root["mqtt_state_topic_pattern"] = this->mqttStateTopicPattern;
  183. root["mqtt_client_status_topic"] = this->mqttClientStatusTopic;
  184. root["discovery_port"] = this->discoveryPort;
  185. root["listen_repeats"] = this->listenRepeats;
  186. root["state_flush_interval"] = this->stateFlushInterval;
  187. root["mqtt_state_rate_limit"] = this->mqttStateRateLimit;
  188. root["packet_repeat_throttle_sensitivity"] = this->packetRepeatThrottleSensitivity;
  189. root["packet_repeat_throttle_threshold"] = this->packetRepeatThrottleThreshold;
  190. root["packet_repeat_minimum"] = this->packetRepeatMinimum;
  191. root["enable_automatic_mode_switching"] = this->enableAutomaticModeSwitching;
  192. root["led_mode_wifi_config"] = LEDStatus::LEDModeToString(this->ledModeWifiConfig);
  193. root["led_mode_wifi_failed"] = LEDStatus::LEDModeToString(this->ledModeWifiFailed);
  194. root["led_mode_operating"] = LEDStatus::LEDModeToString(this->ledModeOperating);
  195. root["led_mode_packet"] = LEDStatus::LEDModeToString(this->ledModePacket);
  196. root["led_mode_packet_count"] = this->ledModePacketCount;
  197. root["hostname"] = this->hostname;
  198. root["rf24_power_level"] = RF24PowerLevelHelpers::nameFromValue(this->rf24PowerLevel);
  199. root["rf24_listen_channel"] = RF24ChannelHelpers::nameFromValue(rf24ListenChannel);
  200. root["wifi_static_ip"] = this->wifiStaticIP;
  201. root["wifi_static_ip_gateway"] = this->wifiStaticIPGateway;
  202. root["wifi_static_ip_netmask"] = this->wifiStaticIPNetmask;
  203. JsonArray& channelArr = jsonBuffer.createArray();
  204. JsonHelpers::vectorToJsonArr<RF24Channel>(channelArr, rf24Channels, RF24ChannelHelpers::nameFromValue);
  205. root["rf24_channels"] = channelArr;
  206. if (this->deviceIds) {
  207. JsonArray& arr = jsonBuffer.createArray();
  208. arr.copyFrom(this->deviceIds, this->numDeviceIds);
  209. root["device_ids"] = arr;
  210. }
  211. if (this->gatewayConfigs) {
  212. JsonArray& arr = jsonBuffer.createArray();
  213. for (size_t i = 0; i < this->numGatewayConfigs; i++) {
  214. JsonArray& elmt = jsonBuffer.createArray();
  215. elmt.add(this->gatewayConfigs[i]->deviceId);
  216. elmt.add(this->gatewayConfigs[i]->port);
  217. elmt.add(this->gatewayConfigs[i]->protocolVersion);
  218. arr.add(elmt);
  219. }
  220. root["gateway_configs"] = arr;
  221. }
  222. if (this->groupStateFields) {
  223. JsonArray& arr = jsonBuffer.createArray();
  224. for (size_t i = 0; i < this->numGroupStateFields; i++) {
  225. arr.add(GroupStateFieldHelpers::getFieldName(this->groupStateFields[i]));
  226. }
  227. root["group_state_fields"] = arr;
  228. }
  229. if (prettyPrint) {
  230. root.prettyPrintTo(stream);
  231. } else {
  232. root.printTo(stream);
  233. }
  234. }
  235. String Settings::mqttServer() {
  236. int pos = PORT_POSITION(_mqttServer);
  237. if (pos == -1) {
  238. return _mqttServer;
  239. } else {
  240. return _mqttServer.substring(0, pos);
  241. }
  242. }
  243. uint16_t Settings::mqttPort() {
  244. int pos = PORT_POSITION(_mqttServer);
  245. if (pos == -1) {
  246. return DEFAULT_MQTT_PORT;
  247. } else {
  248. return atoi(_mqttServer.c_str() + pos + 1);
  249. }
  250. }
  251. RadioInterfaceType Settings::typeFromString(const String& s) {
  252. if (s.equalsIgnoreCase("lt8900")) {
  253. return LT8900;
  254. } else {
  255. return nRF24;
  256. }
  257. }
  258. String Settings::typeToString(RadioInterfaceType type) {
  259. switch (type) {
  260. case LT8900:
  261. return "LT8900";
  262. case nRF24:
  263. default:
  264. return "nRF24";
  265. }
  266. }