Settings.cpp 13 KB

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