buf(new char[size]);
+
+ configFile.readBytes(buf.get(), size);
+ /////////new code JSON6
+ DynamicJsonDocument json(1024);
+ auto deserializeError = deserializeJson(json, buf.get());
+ serializeJson(json, Serial);
+
+ //if (json.success()) /////json5
+ if ( ! deserializeError ) /////json6
+
+ {
+
+ strcpy(host, json["host"]);
+ strcpy(update_username, json["update_username"]);
+ strcpy(update_password, json["update_password"]);
+
+ if (json.containsKey("battery_system")) {strcpy(battery_system, json["battery_system"]);}
+ if (json.containsKey("battery_capacity")) {strcpy(battery_capacity, json["battery_capacity"]);}
+ if (json.containsKey("system_power")) {strcpy(system_power, json["system_power"]);}
+ if (json.containsKey("tele_battery_set")) {strcpy(tele_battery_set, json["tele_battery_set"]);}
+ if (json.containsKey("remote_switch")) {strcpy(remote_switch, json["remote_switch"]);}
+ if (json.containsKey("auto_discovery")) {strcpy(auto_discovery, json["auto_discovery"]);}
+ if (json.containsKey("open_limit_set")) {strcpy(open_limit_set, json["open_limit_set"]);}
+ if (json.containsKey("close_limit_set")) {strcpy(close_limit_set, json["close_limit_set"]);}
+ strcpy(mqtt_isAuthentication, json["mqtt_isAuthentication"]);
+ strcpy(mqtt_username, json["mqtt_username"]);
+ strcpy(mqtt_password, json["mqtt_password"]);
+
+ strcpy(update_path, json["update_path"]);
+
+ strcpy(mqtt_server, json["mqtt_server"]);
+
+ strcpy(mqtt_port, json["mqtt_port"]);
+ strcpy(mqtt_topic, json["mqtt_topic"]); ///device friendly name
+ strcpy(blinds_speed, json["blinds_speed"]);
+ strcpy(blinds_swing_direction, json["blinds_swing_direction"]);
+ strcpy(blinds_servo_install, json["blinds_servo_install"]);
+ strcpy(blinds_trim_adjust, json["blinds_trim_adjust"]);
+ strcpy(blinds_slip_correction, json["blinds_slip_correction"]);
+ strcpy(OTAAuto_path, json["OTAAuto_path"]);
+ strcpy(tele_update_set, json["tele_update_set"]);
+
+ }
+ else
+ {
+ }
+ configFile.close();
+ }
+
+ }
+
+ }
+ else
+ {
+ }
+
+
+
+
+ //end read
+
+ // The extra parameters to be configured (can be either global or just in the setup)
+ // After connecting, parameter.getValue() will get you the configured value
+ // id/name placeholder/prompt default length
+ WiFiManagerParameter custom_text0("Select your wifi network and type in your password, if you do not see your wifi then scroll down to the bottom and press scan to check again.");
+ WiFiManagerParameter custom_text1("
DHCP/Network Device Hostname Name ID ");
+ WiFiManagerParameter custom_text2("Enter a name for this device which will be used as the DHCP/network name e.g. Blindcontrol1.");
+ WiFiManagerParameter custom_host("name", "DHCP/Network Device Name", host, 32);
+ WiFiManagerParameter custom_text30("
Device Friendly Name ");
+ WiFiManagerParameter custom_text31("Enter a Friendly Name can contain space, upper case etc e.g. Kitchen Blind, this will be converted to Unique ID .");
+ WiFiManagerParameter custom_mqtt_topic("topic", "Device Friendly Name", mqtt_topic, 50);
+ WiFiManagerParameter custom_text3("
MQTT ");
+ WiFiManagerParameter custom_text4("Enter the details of your MQTT server and then enter the topic for which the device listens to MQTT commands from. If your server requires authentication then set it to True and enter your server credentials otherwise leave it at false and keep the fields blank.");
+ WiFiManagerParameter custom_mqtt_server("server", "MQTT Server IP", mqtt_server, 40);
+ WiFiManagerParameter custom_mqtt_port("port", "MQTT Server Port", mqtt_port, 5);
+ WiFiManagerParameter custom_mqtt_isAuthentication("isAuthentication", "MQTT Authentication?", mqtt_isAuthentication, 7);
+ WiFiManagerParameter custom_mqtt_username("userMQTT", "Username For MQTT Account", mqtt_username, 40);
+ WiFiManagerParameter custom_mqtt_password("passwordMQTT", "Password For MQTT Account", mqtt_password, 40);
+ WiFiManagerParameter custom_text5("
Web Updater/Reset ");
+ WiFiManagerParameter custom_text6("The web updater allows you to update the firmware of the device or reset the device via a web browser by going to HOST NAME or DEVICE IP ADDRESS/firmware eg. 192.168.0.5/firmware you can change the update path below. The update page and reset optiion is protected so enter a username and password you would like to use to access it.");
+ WiFiManagerParameter custom_update_username("user", "Username For Web Updater", update_username, 40);
+ WiFiManagerParameter custom_update_password("password", "Password For Web Updater", update_password, 40);
+ WiFiManagerParameter custom_battery_system("battery system", "Enable/Disable Battery System", battery_system, 12);
+ WiFiManagerParameter custom_device_path("path", "Updater Path", update_path, 32);
+ WiFiManagerParameter custom_text25("
OTA Path to Firmware Update Server");
+ WiFiManagerParameter custom_OTAAuto_path("OTA Path", "Path to Remote OTA Server?", OTAAuto_path, 90);
+ WiFiManagerParameter custom_text26("
Telemetry Period in Seconds, Default 60s");
+ WiFiManagerParameter custom_tele_update_set("Telemetry Period", "Telemetry Period In Seconds", tele_update_set, 6);
+ WiFiManagerParameter custom_text15("
Custom Blind Control ");
+ WiFiManagerParameter custom_text7("Speed You Want The Blinds To Move? FAST or SLOW?");
+ WiFiManagerParameter custom_blinds_speed("Speed", "Move Blinds Speed?", blinds_speed, 7);
+ WiFiManagerParameter custom_text8("
*To physically reset device settings restart the device and quickly move the jumper from RUN to PGM, wait 10 seconds and put the jumper back to RUN.*");
+ WiFiManagerParameter custom_text9("
*To remote reset device delete all settings via web browser by going to HOST NAME or DEVICE IP ADDRESS/reset .eg. .192.168.0.5/reset ..Wait 10 seconds for reboot*");
+ WiFiManagerParameter custom_text20("
What Side Is The Servo Motor Installed? LEFT/RIGHT, (Default is Left)");
+ WiFiManagerParameter custom_blinds_servo_install("Servo Install", "Servo Motor Installed?", blinds_servo_install, 7);
+ WiFiManagerParameter custom_text21("
Swing direction of blind from Open to Close?, DOWN/UP (Default is DOWN)");
+ WiFiManagerParameter custom_blinds_swing_direction("Swing Direction", "Swing Direction?", blinds_swing_direction, 7);
+ WiFiManagerParameter custom_text17("
To adjust the trim angle of the blinds physical open position against software open position. Between 0-75 Percent Default=0 ");
+ WiFiManagerParameter custom_blinds_trim_adjust("Open Trim Adjustment", "Open Trim Adjustment Percent ? ", blinds_trim_adjust, 3);
+ WiFiManagerParameter custom_text24("
Blinds Weight Slip Adjustment ? Moves Blind to Open Position before Moving to Mid Range Position, ON/OFF , OFF will give incorrect Position 25 percent error, Default is ON)*");
+ WiFiManagerParameter custom_blinds_slip_correction("Slip Correction", "Weight Slip Correction ? ", blinds_slip_correction, 5);
+ WiFiManagerParameter custom_text16("
Setup Notes ");
+
+WiFiManagerParameter custom_text27("*Once you have Configured SSID, PASSWORD, MQTT etc, SAVE, then goto IP/Host name and select Setup to configure extra paramaters, i.e. motor install, swing direction, speed etc *");
+
+ //WiFiManager
+ //Local intialization. Once its business is done, there is no need to keep it around
+ wifi_station_set_hostname(host);
+ WiFi.hostname(host);
+ WiFiManager wifiManager;
+
+ //set config save notify callback
+ wifiManager.setSaveConfigCallback(saveConfigCallback);
+
+ //set static ip
+ //wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
+
+ //add all your parameters here
+ wifiManager.setCustomHeadElement("");
+ wifiManager.addParameter(&custom_text0);
+ wifiManager.addParameter(&custom_text1);
+ wifiManager.addParameter(&custom_text2);
+ wifiManager.addParameter(&custom_host);
+ wifiManager.addParameter(&custom_text30);
+ wifiManager.addParameter(&custom_text31);
+ wifiManager.addParameter(&custom_mqtt_topic);
+ wifiManager.addParameter(&custom_text3);
+ wifiManager.addParameter(&custom_text4);
+ wifiManager.addParameter(&custom_mqtt_server);
+ wifiManager.addParameter(&custom_mqtt_port);
+ wifiManager.addParameter(&custom_mqtt_isAuthentication);
+ wifiManager.addParameter(&custom_mqtt_username);
+ wifiManager.addParameter(&custom_mqtt_password);
+ wifiManager.addParameter(&custom_text16);
+ wifiManager.addParameter(&custom_text27);
+
+ //reset settings - for testing
+ //wifiManager.resetSettings();
+
+ //wifi_station_set_hostname(host);
+ //WiFi.hostname(host);
+ //WiFi.hostname(host);
+ //set minimu quality of signal so it ignores AP's under that quality
+ //defaults to 8%
+ //wifiManager.setMinimumSignalQuality();
+
+ //sets timeout until configuration portal gets turned off
+ //useful to make it all retry or go to sleep
+ //in seconds
+ wifiManager.setTimeout(120);
+ wifiManager.setConfigPortalTimeout(120); ///new code replaces setTimeout()
+ //fetches ssid and pass and tries to connect
+ //if it does not connect it starts an access point with the specified name
+ //here "AutoConnectAP"
+ //and goes into a blocking loop awaiting configuration
+
+ ///check here for possible error leaving AP open
+ ///if (!wifiManager.autoConnect(networkhost.c_str()))
+ if (!wifiManager.autoConnect(ssidAP.c_str()))
+ {
+
+ delay(6000);
+ //reset and try again, or maybe put it to deep sleep
+
+ ESP.reset();
+ delay(5000);
+ }
+
+ //read updated parameters
+ strcpy(host, custom_host.getValue());
+ strcpy(mqtt_server, custom_mqtt_server.getValue());
+ strcpy(mqtt_port, custom_mqtt_port.getValue());
+ strcpy(mqtt_topic, custom_mqtt_topic.getValue()); ////device full friendly name
+ strcpy(mqtt_isAuthentication, custom_mqtt_isAuthentication.getValue());
+ strcpy(mqtt_username, custom_mqtt_username.getValue());
+ strcpy(mqtt_password, custom_mqtt_password.getValue());
+ strcpy(update_username, custom_update_username.getValue());
+ strcpy(update_password, custom_update_password.getValue());
+ strcpy(update_password, custom_update_password.getValue());
+ strcpy(update_path, custom_device_path.getValue());
+ strcpy(blinds_speed, custom_blinds_speed.getValue());
+ strcpy(blinds_swing_direction, custom_blinds_swing_direction.getValue());
+ strcpy(blinds_servo_install, custom_blinds_servo_install.getValue());
+ strcpy(blinds_trim_adjust, custom_blinds_trim_adjust.getValue());
+ strcpy(blinds_slip_correction, custom_blinds_slip_correction.getValue());
+ strcpy(OTAAuto_path, custom_OTAAuto_path.getValue());
+ strcpy(tele_update_set, custom_tele_update_set.getValue());
+
+ //save the custom parameters to FS
+ if (shouldSaveConfig)
+ {
+ // Serial.print("Saving configuration file ");
+
+
+ DynamicJsonDocument json(1024); ////JSON6
+
+ json["host"] = host;
+ json["mqtt_server"] = mqtt_server;
+ json["mqtt_port"] = mqtt_port;
+ json["mqtt_topic"] = mqtt_topic; ////device full friendly name
+ json["mqtt_isAuthentication"] = mqtt_isAuthentication;
+ json["mqtt_username"] = mqtt_username;
+ json["mqtt_password"] = mqtt_password;
+ json["update_username"] = update_username;
+ json["update_password"] = update_password;
+ json["battery_system"] = battery_system;
+ json["remote_switch"] = remote_switch;
+ json["auto_discovery"] = auto_discovery;
+ json["battery_capacity"] = battery_capacity;
+ json["tele_battery_set"] = tele_battery_set;
+ json["system_power"] = system_power;
+ json["update_path"] = update_path;
+ json["blinds_speed"] = blinds_speed;
+ json["blinds_swing_direction"] = blinds_swing_direction;
+ json["blinds_servo_install"] = blinds_servo_install;
+ json["blinds_trim_adjust"] = blinds_trim_adjust;
+ json["blinds_slip_correction"] = blinds_slip_correction;
+ json["OTAAuto_path"] = OTAAuto_path;
+ json["tele_update_set"] = tele_update_set;
+ json["open_limit_set"] = open_limit_set;
+ json["close_limit_set"] = close_limit_set;
+
+ /////save software config.json file///
+ //File configFile = SPIFFS.open("/" + String(software_version) + ".json", "w"); ////old system
+ File configFile = LittleFS.open("/" + String(software_version) + ".json", "w");
+ if (!configFile)
+ {
+ }
+
+ //////JSON6
+ serializeJson(json, Serial); /////JSON6
+ serializeJson(json, configFile); //////JSON6
+ //////////
+
+ configFile.close();
+
+ }
+
+ delay(5000);
+
+ if (digitalRead(0) == LOW || String(host).length() == 0 || String(mqtt_server).length() == 0 || String(mqtt_topic).length() == 0)
+ {
+
+ wifiManager.resetSettings();
+ ESP.reset();
+ }
+
+ mqttDeviceID = host; /////host is the nerwork name
+ /////asign variable from main
+ _name = String(mqtt_topic); ///aka mqtt device ID will change in main program friendly name
+// Id = name to lower case replacing spaces by underscore (ex: name="Kitchen Light" -> id="kitchen_light")
+ _identifier = _name;
+ _identifier.replace(' ', '_');
+ _identifier.toLowerCase();
+////////////////////////////////
+
+
+
+
+/////////////////////////////////
+ client.begin(mqtt_server, atoi(mqtt_port), net);
+ client.onMessage(messageReceived); // existing process MQTT Messages
+
+ connect();
+
+ MDNS.begin(host);
+
+ httpUpdater.setup(&httpServer);
+ httpUpdater.setup(&httpServer, update_path, update_username, update_password);
+
+//////new code
+ //----------------------------------------------------------------------
+
+
+ httpServer.on("/description.xml", HTTP_GET, []() {
+ SSDP.schema(httpServer.client());
+ });
+
+
+
+ ///////////////////////////// Server Commands
+ httpServer.on("/", HomePage);
+ httpServer.on("/download", File_Download);
+ httpServer.on("/upload", File_Upload);
+ httpServer.on("/help", Help);
+ httpServer.on("/fupload", HTTP_POST,[](){ httpServer.send(200);}, handleFileUpload);
+ httpServer.on("/reboot", Device_Reboot);
+ httpServer.on("/delete", File_Delete);
+ httpServer.on("/dir", SPIFFS_dir);
+ httpServer.on("/setup", Config_Setup);
+ httpServer.on("/firmware", Firmware_Update);
+ httpServer.on("/firmwareupdate", Firmware_Update);
+ httpServer.on("/firmwareauto", OTAUpgrade);
+ httpServer.on("/firmwareauto", OTAUpgrade);
+ httpServer.on("/set-servo", Set_Servo);
+ httpServer.on("/set-limits", handleMoveServo);
+
+ //httpServer.on("/servoaction", Servo_Action);
+ httpServer.on("/firmwarecheck", FirmwareCheck);
+ httpServer.on("/filemanager", File_Manager);
+ httpServer.on("/saveconfig", Save_Config);
+ httpServer.on("/submitconfig", Submit_Config);
+ // httpServer.on("/action_page", handleForm);
+ httpServer.on("/exit", HomePage);
+ httpServer.on("/resetcmd", longHoldEvent);
+ httpServer.on("/setPOS", handleServo); //--> Sets servo position from Web request
+ httpServer.on("/SetOpenLimit", SetOpenLimit);
+ httpServer.on("/SetClosedLimit", SetClosedLimit);
+ httpServer.on("/ResetLimits", ResetLimits);
+ ///////////////////////////// End of Request commands
+ // Send web page with input fields to client
+
+
+ //New Code To run Reset Ap And Re Launch WiFiManager Portal
+ httpServer.on("/reset", []() {
+ if (!httpServer.authenticate(update_username, update_password))
+ return httpServer.requestAuthentication();
+ Serial.print("Resetting Devkce... ");
+ SendHTML_Header();
+
+ webpage += F("
Reset Controller ");
+ webpage += F("");
+ webpage += F(" All Settings Will Be Deleted and Set To Defaults ");
+ webpage += F(" File System Will Be Reformated..... ");
+ webpage += F(" You Will Need To Connect Via AP Mode And Setup Device Again ");
+ //webpage += F(" Device Will AUTO Restart In 10 Seconds in AP Setup mode ");
+ webpage += F(" Press Continue to Proceed or Cancel to Exit ");
+ webpage += F("");
+ webpage += F("Continue ");
+ webpage += F("Cancel ");
+ append_page_footer();
+ SendHTML_Content();
+ SendHTML_Stop(); // Stop is needed because no content length was sent
+
+ });
+
+ httpServer.begin();
+
+//////////////////////////////
+ SSDP.setSchemaURL("description.xml");
+ SSDP.setHTTPPort(80);
+ SSDP.setName(host);
+ SSDP.setModelName("Mk-Blindcontrol");
+ SSDP.setURL("/");
+ SSDP.setDeviceType("upnp:rootdevice");
+ SSDP.setSerialNumber(ESP.getChipId());
+ SSDP.setModelNumber("MK-Blindcontrol V7");
+ SSDP.setModelURL("https://mountaineagle-technologies.com.au");
+ SSDP.setManufacturer("MK Smarthouse");
+ SSDP.setManufacturerURL("https://www.mksmarthouse.com");
+SSDP.begin();
+
+////////////////////////////
+ MDNS.addService("http", "tcp", 80);
+ //MDNS.addService("https", "tcp", 443);
+/////////////////////////////////////////
+AutoConfigBlind();
+get_save_state();
+
+moveServo(ServoPos); ///moves servo to set pos as on powerup servo pos defaults to 90 regardless of previous osition
+myservo[0].detach();
+myservo[1].detach();
+
+ }
+///////main loop
+void loop()
+{
+ client.loop();
+ delay(10);
+
+ if (!client.connected())
+ {
+ //connect();
+ client.disconnect();
+ connect();
+
+ }
+
+ httpServer.handleClient();
+ MDNS.update();
+ /////set to 0 to stop telementry update. help power save
+ if (String(tele_update_set).toInt()>0)
+ {
+ //Serial.printlnln("Telementry update...");
+ tele_update();
+ }
+
+
+////Battery Check Monitor
+ if (String(battery_system).equalsIgnoreCase("ON"))
+ {
+ //Serial.println("Checking Battery Status.. ");
+ Battery_Check();
+ }
+
+// Get button event and act accordingly
+ button_result = 0;
+ checkButton();
+if (String(remote_switch).equalsIgnoreCase("YES"))
+ {
+
+
+ if (button_result == 1) {clickEvent();}
+ if (button_result == 2) {doubleClickEvent();}
+ if (button_result == 3) {holdEvent();}
+ if (button_result == 4) {longHoldEvent();} ////allows for reset operation
+ }
+
+
+}
+
+/////end void loop