Settings.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. this->setIfPresent(parsedSettings, "wifi_force_b_mode", wifiForceBMode);
  88. if (parsedSettings.containsKey("rf24_channels")) {
  89. JsonArray arr = parsedSettings["rf24_channels"];
  90. rf24Channels = JsonHelpers::jsonArrToVector<RF24Channel, String>(arr, RF24ChannelHelpers::valueFromName);
  91. }
  92. if (parsedSettings.containsKey("rf24_listen_channel")) {
  93. this->rf24ListenChannel = RF24ChannelHelpers::valueFromName(parsedSettings["rf24_listen_channel"]);
  94. }
  95. if (parsedSettings.containsKey("rf24_power_level")) {
  96. this->rf24PowerLevel = RF24PowerLevelHelpers::valueFromName(parsedSettings["rf24_power_level"]);
  97. }
  98. if (parsedSettings.containsKey("led_mode_wifi_config")) {
  99. this->ledModeWifiConfig = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_config"]);
  100. }
  101. if (parsedSettings.containsKey("led_mode_wifi_failed")) {
  102. this->ledModeWifiFailed = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_failed"]);
  103. }
  104. if (parsedSettings.containsKey("led_mode_operating")) {
  105. this->ledModeOperating = LEDStatus::stringToLEDMode(parsedSettings["led_mode_operating"]);
  106. }
  107. if (parsedSettings.containsKey("led_mode_packet")) {
  108. this->ledModePacket = LEDStatus::stringToLEDMode(parsedSettings["led_mode_packet"]);
  109. }
  110. if (parsedSettings.containsKey("radio_interface_type")) {
  111. this->radioInterfaceType = Settings::typeFromString(parsedSettings["radio_interface_type"]);
  112. }
  113. if (parsedSettings.containsKey("device_ids")) {
  114. JsonArray arr = parsedSettings["device_ids"];
  115. updateDeviceIds(arr);
  116. }
  117. if (parsedSettings.containsKey("gateway_configs")) {
  118. JsonArray arr = parsedSettings["gateway_configs"];
  119. updateGatewayConfigs(arr);
  120. }
  121. if (parsedSettings.containsKey("group_state_fields")) {
  122. JsonArray arr = parsedSettings["group_state_fields"];
  123. groupStateFields = JsonHelpers::jsonArrToVector<GroupStateField, const char*>(arr, GroupStateFieldHelpers::getFieldByName);
  124. }
  125. if (parsedSettings.containsKey("group_id_aliases")) {
  126. parseGroupIdAliases(parsedSettings);
  127. }
  128. }
  129. std::map<String, BulbId>::const_iterator Settings::findAlias(MiLightRemoteType deviceType, uint16_t deviceId, uint8_t groupId) {
  130. BulbId searchId{ deviceId, groupId, deviceType };
  131. for (auto it = groupIdAliases.begin(); it != groupIdAliases.end(); ++it) {
  132. if (searchId == it->second) {
  133. return it;
  134. }
  135. }
  136. return groupIdAliases.end();
  137. }
  138. void Settings::parseGroupIdAliases(JsonObject json) {
  139. JsonObject aliases = json["group_id_aliases"];
  140. // Save group IDs that were deleted so that they can be processed by discovery
  141. // if necessary
  142. for (auto it = groupIdAliases.begin(); it != groupIdAliases.end(); ++it) {
  143. deletedGroupIdAliases[it->second.getCompactId()] = it->second;
  144. }
  145. groupIdAliases.clear();
  146. for (JsonPair kv : aliases) {
  147. JsonArray bulbIdProps = kv.value();
  148. BulbId bulbId = {
  149. bulbIdProps[1].as<uint16_t>(),
  150. bulbIdProps[2].as<uint8_t>(),
  151. MiLightRemoteTypeHelpers::remoteTypeFromString(bulbIdProps[0].as<String>())
  152. };
  153. groupIdAliases[kv.key().c_str()] = bulbId;
  154. // If added this round, do not mark as deleted.
  155. deletedGroupIdAliases.erase(bulbId.getCompactId());
  156. }
  157. }
  158. void Settings::dumpGroupIdAliases(JsonObject json) {
  159. JsonObject aliases = json.createNestedObject("group_id_aliases");
  160. for (std::map<String, BulbId>::iterator itr = groupIdAliases.begin(); itr != groupIdAliases.end(); ++itr) {
  161. JsonArray bulbProps = aliases.createNestedArray(itr->first);
  162. BulbId bulbId = itr->second;
  163. bulbProps.add(MiLightRemoteTypeHelpers::remoteTypeToString(bulbId.deviceType));
  164. bulbProps.add(bulbId.deviceId);
  165. bulbProps.add(bulbId.groupId);
  166. }
  167. }
  168. void Settings::load(Settings& settings) {
  169. if (SPIFFS.exists(SETTINGS_FILE)) {
  170. // Clear in-memory settings
  171. settings = Settings();
  172. File f = SPIFFS.open(SETTINGS_FILE, "r");
  173. DynamicJsonDocument json(MILIGHT_HUB_SETTINGS_BUFFER_SIZE);
  174. auto error = deserializeJson(json, f);
  175. f.close();
  176. if (! error) {
  177. JsonObject parsedSettings = json.as<JsonObject>();
  178. settings.patch(parsedSettings);
  179. } else {
  180. Serial.print(F("Error parsing saved settings file: "));
  181. Serial.println(error.c_str());
  182. }
  183. } else {
  184. settings.save();
  185. }
  186. }
  187. String Settings::toJson(const bool prettyPrint) {
  188. String buffer = "";
  189. StringStream s(buffer);
  190. serialize(s, prettyPrint);
  191. return buffer;
  192. }
  193. void Settings::save() {
  194. File f = SPIFFS.open(SETTINGS_FILE, "w");
  195. if (!f) {
  196. Serial.println(F("Opening settings file failed"));
  197. } else {
  198. serialize(f);
  199. f.close();
  200. }
  201. }
  202. void Settings::serialize(Print& stream, const bool prettyPrint) {
  203. DynamicJsonDocument root(MILIGHT_HUB_SETTINGS_BUFFER_SIZE);
  204. root["admin_username"] = this->adminUsername;
  205. root["admin_password"] = this->adminPassword;
  206. root["ce_pin"] = this->cePin;
  207. root["csn_pin"] = this->csnPin;
  208. root["reset_pin"] = this->resetPin;
  209. root["led_pin"] = this->ledPin;
  210. root["radio_interface_type"] = typeToString(this->radioInterfaceType);
  211. root["packet_repeats"] = this->packetRepeats;
  212. root["http_repeat_factor"] = this->httpRepeatFactor;
  213. root["auto_restart_period"] = this->_autoRestartPeriod;
  214. root["mqtt_server"] = this->_mqttServer;
  215. root["mqtt_username"] = this->mqttUsername;
  216. root["mqtt_password"] = this->mqttPassword;
  217. root["mqtt_topic_pattern"] = this->mqttTopicPattern;
  218. root["mqtt_update_topic_pattern"] = this->mqttUpdateTopicPattern;
  219. root["mqtt_state_topic_pattern"] = this->mqttStateTopicPattern;
  220. root["mqtt_client_status_topic"] = this->mqttClientStatusTopic;
  221. root["simple_mqtt_client_status"] = this->simpleMqttClientStatus;
  222. root["discovery_port"] = this->discoveryPort;
  223. root["listen_repeats"] = this->listenRepeats;
  224. root["state_flush_interval"] = this->stateFlushInterval;
  225. root["mqtt_state_rate_limit"] = this->mqttStateRateLimit;
  226. root["packet_repeat_throttle_sensitivity"] = this->packetRepeatThrottleSensitivity;
  227. root["packet_repeat_throttle_threshold"] = this->packetRepeatThrottleThreshold;
  228. root["packet_repeat_minimum"] = this->packetRepeatMinimum;
  229. root["enable_automatic_mode_switching"] = this->enableAutomaticModeSwitching;
  230. root["led_mode_wifi_config"] = LEDStatus::LEDModeToString(this->ledModeWifiConfig);
  231. root["led_mode_wifi_failed"] = LEDStatus::LEDModeToString(this->ledModeWifiFailed);
  232. root["led_mode_operating"] = LEDStatus::LEDModeToString(this->ledModeOperating);
  233. root["led_mode_packet"] = LEDStatus::LEDModeToString(this->ledModePacket);
  234. root["led_mode_packet_count"] = this->ledModePacketCount;
  235. root["hostname"] = this->hostname;
  236. root["rf24_power_level"] = RF24PowerLevelHelpers::nameFromValue(this->rf24PowerLevel);
  237. root["rf24_listen_channel"] = RF24ChannelHelpers::nameFromValue(rf24ListenChannel);
  238. root["wifi_static_ip"] = this->wifiStaticIP;
  239. root["wifi_static_ip_gateway"] = this->wifiStaticIPGateway;
  240. root["wifi_static_ip_netmask"] = this->wifiStaticIPNetmask;
  241. root["packet_repeats_per_loop"] = this->packetRepeatsPerLoop;
  242. root["home_assistant_discovery_prefix"] = this->homeAssistantDiscoveryPrefix;
  243. root["wifi_force_b_mode"] = this->wifiForceBMode;
  244. JsonArray channelArr = root.createNestedArray("rf24_channels");
  245. JsonHelpers::vectorToJsonArr<RF24Channel, String>(channelArr, rf24Channels, RF24ChannelHelpers::nameFromValue);
  246. JsonArray deviceIdsArr = root.createNestedArray("device_ids");
  247. JsonHelpers::copyFrom<uint16_t>(deviceIdsArr, this->deviceIds);
  248. JsonArray gatewayConfigsArr = root.createNestedArray("gateway_configs");
  249. for (size_t i = 0; i < this->gatewayConfigs.size(); i++) {
  250. JsonArray elmt = gatewayConfigsArr.createNestedArray();
  251. elmt.add(this->gatewayConfigs[i]->deviceId);
  252. elmt.add(this->gatewayConfigs[i]->port);
  253. elmt.add(this->gatewayConfigs[i]->protocolVersion);
  254. }
  255. JsonArray groupStateFieldArr = root.createNestedArray("group_state_fields");
  256. JsonHelpers::vectorToJsonArr<GroupStateField, const char*>(groupStateFieldArr, groupStateFields, GroupStateFieldHelpers::getFieldName);
  257. dumpGroupIdAliases(root.as<JsonObject>());
  258. if (prettyPrint) {
  259. serializeJsonPretty(root, stream);
  260. } else {
  261. serializeJson(root, stream);
  262. }
  263. }
  264. String Settings::mqttServer() {
  265. int pos = PORT_POSITION(_mqttServer);
  266. if (pos == -1) {
  267. return _mqttServer;
  268. } else {
  269. return _mqttServer.substring(0, pos);
  270. }
  271. }
  272. uint16_t Settings::mqttPort() {
  273. int pos = PORT_POSITION(_mqttServer);
  274. if (pos == -1) {
  275. return DEFAULT_MQTT_PORT;
  276. } else {
  277. return atoi(_mqttServer.c_str() + pos + 1);
  278. }
  279. }
  280. RadioInterfaceType Settings::typeFromString(const String& s) {
  281. if (s.equalsIgnoreCase("lt8900")) {
  282. return LT8900;
  283. } else {
  284. return nRF24;
  285. }
  286. }
  287. String Settings::typeToString(RadioInterfaceType type) {
  288. switch (type) {
  289. case LT8900:
  290. return "LT8900";
  291. case nRF24:
  292. default:
  293. return "nRF24";
  294. }
  295. }