Settings.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. GatewayConfig::GatewayConfig(uint16_t deviceId, uint16_t port, uint8_t protocolVersion)
  9. : deviceId(deviceId)
  10. , port(port)
  11. , protocolVersion(protocolVersion)
  12. { }
  13. bool Settings::isAuthenticationEnabled() const {
  14. return adminUsername.length() > 0 && adminPassword.length() > 0;
  15. }
  16. const String& Settings::getUsername() const {
  17. return adminUsername;
  18. }
  19. const String& Settings::getPassword() const {
  20. return adminPassword;
  21. }
  22. bool Settings::isAutoRestartEnabled() {
  23. return _autoRestartPeriod > 0;
  24. }
  25. size_t Settings::getAutoRestartPeriod() {
  26. if (_autoRestartPeriod == 0) {
  27. return 0;
  28. }
  29. return std::max(_autoRestartPeriod, static_cast<size_t>(MINIMUM_RESTART_PERIOD));
  30. }
  31. void Settings::updateDeviceIds(JsonArray arr) {
  32. this->deviceIds.clear();
  33. for (size_t i = 0; i < arr.size(); ++i) {
  34. this->deviceIds.push_back(arr[i]);
  35. }
  36. }
  37. void Settings::updateGatewayConfigs(JsonArray arr) {
  38. gatewayConfigs.clear();
  39. for (size_t i = 0; i < arr.size(); i++) {
  40. JsonArray params = arr[i];
  41. if (params.size() == 3) {
  42. std::shared_ptr<GatewayConfig> ptr = std::make_shared<GatewayConfig>(parseInt<uint16_t>(params[0]), params[1], params[2]);
  43. gatewayConfigs.push_back(std::move(ptr));
  44. } else {
  45. Serial.print(F("Settings - skipped parsing gateway ports settings for element #"));
  46. Serial.println(i);
  47. }
  48. }
  49. }
  50. void Settings::patch(JsonObject parsedSettings) {
  51. if (parsedSettings.isNull()) {
  52. Serial.println(F("Skipping patching loaded settings. Parsed settings was null."));
  53. return;
  54. }
  55. this->setIfPresent(parsedSettings, "admin_username", adminUsername);
  56. this->setIfPresent(parsedSettings, "admin_password", adminPassword);
  57. this->setIfPresent(parsedSettings, "ce_pin", cePin);
  58. this->setIfPresent(parsedSettings, "csn_pin", csnPin);
  59. this->setIfPresent(parsedSettings, "reset_pin", resetPin);
  60. this->setIfPresent(parsedSettings, "led_pin", ledPin);
  61. this->setIfPresent(parsedSettings, "packet_repeats", packetRepeats);
  62. this->setIfPresent(parsedSettings, "http_repeat_factor", httpRepeatFactor);
  63. this->setIfPresent(parsedSettings, "auto_restart_period", _autoRestartPeriod);
  64. this->setIfPresent(parsedSettings, "mqtt_server", _mqttServer);
  65. this->setIfPresent(parsedSettings, "mqtt_username", mqttUsername);
  66. this->setIfPresent(parsedSettings, "mqtt_password", mqttPassword);
  67. this->setIfPresent(parsedSettings, "mqtt_topic_pattern", mqttTopicPattern);
  68. this->setIfPresent(parsedSettings, "mqtt_update_topic_pattern", mqttUpdateTopicPattern);
  69. this->setIfPresent(parsedSettings, "mqtt_state_topic_pattern", mqttStateTopicPattern);
  70. this->setIfPresent(parsedSettings, "mqtt_client_status_topic", mqttClientStatusTopic);
  71. this->setIfPresent(parsedSettings, "simple_mqtt_client_status", simpleMqttClientStatus);
  72. this->setIfPresent(parsedSettings, "discovery_port", discoveryPort);
  73. this->setIfPresent(parsedSettings, "listen_repeats", listenRepeats);
  74. this->setIfPresent(parsedSettings, "state_flush_interval", stateFlushInterval);
  75. this->setIfPresent(parsedSettings, "mqtt_state_rate_limit", mqttStateRateLimit);
  76. this->setIfPresent(parsedSettings, "packet_repeat_throttle_threshold", packetRepeatThrottleThreshold);
  77. this->setIfPresent(parsedSettings, "packet_repeat_throttle_sensitivity", packetRepeatThrottleSensitivity);
  78. this->setIfPresent(parsedSettings, "packet_repeat_minimum", packetRepeatMinimum);
  79. this->setIfPresent(parsedSettings, "enable_automatic_mode_switching", enableAutomaticModeSwitching);
  80. this->setIfPresent(parsedSettings, "led_mode_packet_count", ledModePacketCount);
  81. this->setIfPresent(parsedSettings, "hostname", hostname);
  82. this->setIfPresent(parsedSettings, "wifi_static_ip", wifiStaticIP);
  83. this->setIfPresent(parsedSettings, "wifi_static_ip_gateway", wifiStaticIPGateway);
  84. this->setIfPresent(parsedSettings, "wifi_static_ip_netmask", wifiStaticIPNetmask);
  85. this->setIfPresent(parsedSettings, "packet_repeats_per_loop", packetRepeatsPerLoop);
  86. this->setIfPresent(parsedSettings, "home_assistant_discovery_prefix", homeAssistantDiscoveryPrefix);
  87. if (parsedSettings.containsKey("rf24_channels")) {
  88. JsonArray arr = parsedSettings["rf24_channels"];
  89. rf24Channels = JsonHelpers::jsonArrToVector<RF24Channel, String>(arr, RF24ChannelHelpers::valueFromName);
  90. }
  91. if (parsedSettings.containsKey("rf24_listen_channel")) {
  92. this->rf24ListenChannel = RF24ChannelHelpers::valueFromName(parsedSettings["rf24_listen_channel"]);
  93. }
  94. if (parsedSettings.containsKey("rf24_power_level")) {
  95. this->rf24PowerLevel = RF24PowerLevelHelpers::valueFromName(parsedSettings["rf24_power_level"]);
  96. }
  97. if (parsedSettings.containsKey("led_mode_wifi_config")) {
  98. this->ledModeWifiConfig = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_config"]);
  99. }
  100. if (parsedSettings.containsKey("led_mode_wifi_failed")) {
  101. this->ledModeWifiFailed = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_failed"]);
  102. }
  103. if (parsedSettings.containsKey("led_mode_operating")) {
  104. this->ledModeOperating = LEDStatus::stringToLEDMode(parsedSettings["led_mode_operating"]);
  105. }
  106. if (parsedSettings.containsKey("led_mode_packet")) {
  107. this->ledModePacket = LEDStatus::stringToLEDMode(parsedSettings["led_mode_packet"]);
  108. }
  109. if (parsedSettings.containsKey("radio_interface_type")) {
  110. this->radioInterfaceType = Settings::typeFromString(parsedSettings["radio_interface_type"]);
  111. }
  112. if (parsedSettings.containsKey("device_ids")) {
  113. JsonArray arr = parsedSettings["device_ids"];
  114. updateDeviceIds(arr);
  115. }
  116. if (parsedSettings.containsKey("gateway_configs")) {
  117. JsonArray arr = parsedSettings["gateway_configs"];
  118. updateGatewayConfigs(arr);
  119. }
  120. if (parsedSettings.containsKey("group_state_fields")) {
  121. JsonArray arr = parsedSettings["group_state_fields"];
  122. groupStateFields = JsonHelpers::jsonArrToVector<GroupStateField, const char*>(arr, GroupStateFieldHelpers::getFieldByName);
  123. }
  124. if (parsedSettings.containsKey("group_id_aliases")) {
  125. parseGroupIdAliases(parsedSettings);
  126. }
  127. }
  128. std::map<String, BulbId>::const_iterator Settings::findAlias(MiLightRemoteType deviceType, uint16_t deviceId, uint8_t groupId) {
  129. BulbId searchId{ deviceId, groupId, deviceType };
  130. for (auto it = groupIdAliases.begin(); it != groupIdAliases.end(); ++it) {
  131. if (searchId == it->second) {
  132. return it;
  133. }
  134. }
  135. return groupIdAliases.end();
  136. }
  137. void Settings::parseGroupIdAliases(JsonObject json) {
  138. JsonObject aliases = json["group_id_aliases"];
  139. groupIdAliases.clear();
  140. for (JsonPair kv : aliases) {
  141. JsonArray bulbIdProps = kv.value();
  142. BulbId bulbId = {
  143. bulbIdProps[1].as<uint16_t>(),
  144. bulbIdProps[2].as<uint8_t>(),
  145. MiLightRemoteTypeHelpers::remoteTypeFromString(bulbIdProps[0].as<String>())
  146. };
  147. groupIdAliases[kv.key().c_str()] = bulbId;
  148. }
  149. }
  150. void Settings::dumpGroupIdAliases(JsonObject json) {
  151. JsonObject aliases = json.createNestedObject("group_id_aliases");
  152. for (std::map<String, BulbId>::iterator itr = groupIdAliases.begin(); itr != groupIdAliases.end(); ++itr) {
  153. JsonArray bulbProps = aliases.createNestedArray(itr->first);
  154. BulbId bulbId = itr->second;
  155. bulbProps.add(MiLightRemoteTypeHelpers::remoteTypeToString(bulbId.deviceType));
  156. bulbProps.add(bulbId.deviceId);
  157. bulbProps.add(bulbId.groupId);
  158. }
  159. }
  160. void Settings::load(Settings& settings) {
  161. if (SPIFFS.exists(SETTINGS_FILE)) {
  162. // Clear in-memory settings
  163. settings = Settings();
  164. File f = SPIFFS.open(SETTINGS_FILE, "r");
  165. DynamicJsonDocument json(MILIGHT_HUB_SETTINGS_BUFFER_SIZE);
  166. auto error = deserializeJson(json, f);
  167. f.close();
  168. if (! error) {
  169. JsonObject parsedSettings = json.as<JsonObject>();
  170. settings.patch(parsedSettings);
  171. } else {
  172. Serial.print(F("Error parsing saved settings file: "));
  173. Serial.println(error.c_str());
  174. }
  175. } else {
  176. settings.save();
  177. }
  178. }
  179. String Settings::toJson(const bool prettyPrint) {
  180. String buffer = "";
  181. StringStream s(buffer);
  182. serialize(s, prettyPrint);
  183. return buffer;
  184. }
  185. void Settings::save() {
  186. File f = SPIFFS.open(SETTINGS_FILE, "w");
  187. if (!f) {
  188. Serial.println(F("Opening settings file failed"));
  189. } else {
  190. serialize(f);
  191. f.close();
  192. }
  193. }
  194. void Settings::serialize(Print& stream, const bool prettyPrint) {
  195. DynamicJsonDocument root(MILIGHT_HUB_SETTINGS_BUFFER_SIZE);
  196. root["admin_username"] = this->adminUsername;
  197. root["admin_password"] = this->adminPassword;
  198. root["ce_pin"] = this->cePin;
  199. root["csn_pin"] = this->csnPin;
  200. root["reset_pin"] = this->resetPin;
  201. root["led_pin"] = this->ledPin;
  202. root["radio_interface_type"] = typeToString(this->radioInterfaceType);
  203. root["packet_repeats"] = this->packetRepeats;
  204. root["http_repeat_factor"] = this->httpRepeatFactor;
  205. root["auto_restart_period"] = this->_autoRestartPeriod;
  206. root["mqtt_server"] = this->_mqttServer;
  207. root["mqtt_username"] = this->mqttUsername;
  208. root["mqtt_password"] = this->mqttPassword;
  209. root["mqtt_topic_pattern"] = this->mqttTopicPattern;
  210. root["mqtt_update_topic_pattern"] = this->mqttUpdateTopicPattern;
  211. root["mqtt_state_topic_pattern"] = this->mqttStateTopicPattern;
  212. root["mqtt_client_status_topic"] = this->mqttClientStatusTopic;
  213. root["simple_mqtt_client_status"] = this->simpleMqttClientStatus;
  214. root["discovery_port"] = this->discoveryPort;
  215. root["listen_repeats"] = this->listenRepeats;
  216. root["state_flush_interval"] = this->stateFlushInterval;
  217. root["mqtt_state_rate_limit"] = this->mqttStateRateLimit;
  218. root["packet_repeat_throttle_sensitivity"] = this->packetRepeatThrottleSensitivity;
  219. root["packet_repeat_throttle_threshold"] = this->packetRepeatThrottleThreshold;
  220. root["packet_repeat_minimum"] = this->packetRepeatMinimum;
  221. root["enable_automatic_mode_switching"] = this->enableAutomaticModeSwitching;
  222. root["led_mode_wifi_config"] = LEDStatus::LEDModeToString(this->ledModeWifiConfig);
  223. root["led_mode_wifi_failed"] = LEDStatus::LEDModeToString(this->ledModeWifiFailed);
  224. root["led_mode_operating"] = LEDStatus::LEDModeToString(this->ledModeOperating);
  225. root["led_mode_packet"] = LEDStatus::LEDModeToString(this->ledModePacket);
  226. root["led_mode_packet_count"] = this->ledModePacketCount;
  227. root["hostname"] = this->hostname;
  228. root["rf24_power_level"] = RF24PowerLevelHelpers::nameFromValue(this->rf24PowerLevel);
  229. root["rf24_listen_channel"] = RF24ChannelHelpers::nameFromValue(rf24ListenChannel);
  230. root["wifi_static_ip"] = this->wifiStaticIP;
  231. root["wifi_static_ip_gateway"] = this->wifiStaticIPGateway;
  232. root["wifi_static_ip_netmask"] = this->wifiStaticIPNetmask;
  233. root["packet_repeats_per_loop"] = this->packetRepeatsPerLoop;
  234. root["home_assistant_discovery_prefix"] = this->homeAssistantDiscoveryPrefix;
  235. JsonArray channelArr = root.createNestedArray("rf24_channels");
  236. JsonHelpers::vectorToJsonArr<RF24Channel, String>(channelArr, rf24Channels, RF24ChannelHelpers::nameFromValue);
  237. JsonArray deviceIdsArr = root.createNestedArray("device_ids");
  238. JsonHelpers::copyFrom<uint16_t>(deviceIdsArr, this->deviceIds);
  239. JsonArray gatewayConfigsArr = root.createNestedArray("gateway_configs");
  240. for (size_t i = 0; i < this->gatewayConfigs.size(); i++) {
  241. JsonArray elmt = gatewayConfigsArr.createNestedArray();
  242. elmt.add(this->gatewayConfigs[i]->deviceId);
  243. elmt.add(this->gatewayConfigs[i]->port);
  244. elmt.add(this->gatewayConfigs[i]->protocolVersion);
  245. }
  246. JsonArray groupStateFieldArr = root.createNestedArray("group_state_fields");
  247. JsonHelpers::vectorToJsonArr<GroupStateField, const char*>(groupStateFieldArr, groupStateFields, GroupStateFieldHelpers::getFieldName);
  248. dumpGroupIdAliases(root.as<JsonObject>());
  249. if (prettyPrint) {
  250. serializeJsonPretty(root, stream);
  251. } else {
  252. serializeJson(root, stream);
  253. }
  254. }
  255. String Settings::mqttServer() {
  256. int pos = PORT_POSITION(_mqttServer);
  257. if (pos == -1) {
  258. return _mqttServer;
  259. } else {
  260. return _mqttServer.substring(0, pos);
  261. }
  262. }
  263. uint16_t Settings::mqttPort() {
  264. int pos = PORT_POSITION(_mqttServer);
  265. if (pos == -1) {
  266. return DEFAULT_MQTT_PORT;
  267. } else {
  268. return atoi(_mqttServer.c_str() + pos + 1);
  269. }
  270. }
  271. RadioInterfaceType Settings::typeFromString(const String& s) {
  272. if (s.equalsIgnoreCase("lt8900")) {
  273. return LT8900;
  274. } else {
  275. return nRF24;
  276. }
  277. }
  278. String Settings::typeToString(RadioInterfaceType type) {
  279. switch (type) {
  280. case LT8900:
  281. return "LT8900";
  282. case nRF24:
  283. default:
  284. return "nRF24";
  285. }
  286. }