├── THE433 Control Android demo app ├── THE433Control.aia ├── THE433Control.apk ├── THE433ControlScreenshot800.png └── README.md ├── espWiFi2eeprom.h ├── NKNTP.h ├── .travis.yml ├── NKNTP.ino ├── README.md ├── espWiFi2eeprom.ino ├── LICENSE └── THE433.ino /THE433 Control Android demo app/THE433Control.aia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/go-ut/ESP8266-RF433-Interface/HEAD/THE433 Control Android demo app/THE433Control.aia -------------------------------------------------------------------------------- /THE433 Control Android demo app/THE433Control.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/go-ut/ESP8266-RF433-Interface/HEAD/THE433 Control Android demo app/THE433Control.apk -------------------------------------------------------------------------------- /THE433 Control Android demo app/THE433ControlScreenshot800.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/go-ut/ESP8266-RF433-Interface/HEAD/THE433 Control Android demo app/THE433ControlScreenshot800.png -------------------------------------------------------------------------------- /THE433 Control Android demo app/README.md: -------------------------------------------------------------------------------- 1 | 2 | Demo Android app for the "THE433 Control" for *MIT App Inventor 2* http://ai2.appinventor.mit.edu/ 3 | 4 | 5 | You can import the \*.aia file to app inventor in order to edit it to fit your needs. 6 | 7 | The demo \*.apk file works with the main code provided with esp8266 IP set to 192.168.1.101 8 | 9 | ![THE433 Android app demo screenshot](https://github.com/nikant/THE433/raw/master/THE433%20Control%20Android%20demo%20app/THE433ControlScreenshot800.png) 10 | -------------------------------------------------------------------------------- /espWiFi2eeprom.h: -------------------------------------------------------------------------------- 1 | // you should change the following two to something of your own to remember 2 | #define AP_RESTART "esprestart" 3 | #define AP_CLEAREEPROM "cleareeprom" 4 | #define AP_WIFICFGPORT 8266 5 | //-- 6 | // password for the esp8266 softAP creates when it doesn't find info in the eeprom 7 | // or when something else goes wrong and can't connect 8 | const char AP_password[] = "esp8266control"; 9 | //-- 10 | 11 | #define ESPWIFI2EEPROM_VERSION "0.4" 12 | void espNKWiFiconnect(); 13 | void handle_APrestart(); 14 | void handle_clearAPeeprom(); 15 | extern const char* restartcommand; 16 | extern const char* cleareepromcommand; 17 | -------------------------------------------------------------------------------- /NKNTP.h: -------------------------------------------------------------------------------- 1 | // You can edit NKNTP.h in order to change to your Timezone and DST 2 | // check https://github.com/JChristensen/Timezone/blob/master/ReadMe.md for examples. 3 | 4 | #include //https://github.com/JChristensen/Timezone 5 | 6 | //Eastern European Time Zone 7 | // http://www.epochconverter.com/timezones 8 | extern TimeChangeRule myDST = {"EEST", Last, Sun, Mar, 3, 180}; //Daylight time = UTC + 3 hours 9 | extern TimeChangeRule mySTD = {"EET", Last, Sun, Oct, 4, 120}; //Standard time = UTC + 2 hours 10 | extern Timezone myTZ(myDST, mySTD); 11 | 12 | extern boolean NTPsuccess; 13 | 14 | void NTP2localTime(); 15 | void getTheNTPTime(); 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | before_install: 3 | - "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16" 4 | - sleep 3 5 | - export DISPLAY=:1.0 6 | - wget http://downloads.arduino.cc/arduino-1.6.5-linux64.tar.xz 7 | - tar xf arduino-1.6.5-linux64.tar.xz 8 | - sudo mv arduino-1.6.5 /usr/local/share/arduino 9 | - sudo ln -s /usr/local/share/arduino/arduino /usr/local/bin/arduino 10 | install: 11 | - ln -s $PWD /usr/local/share/arduino/THE433 12 | # boards manager not working on 1.6.7 - 1.6.8 13 | - arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json" --save-prefs 14 | # install lib arduino json not working in 1.6.5 15 | # - arduino --install-library "ArduinoJson" 16 | - git clone https://github.com/sui77/rc-switch /usr/local/share/arduino/libraries/rc-switch 17 | - git clone https://github.com/pimatic/RFControl /usr/local/share/arduino/libraries/RFControl 18 | - git clone https://github.com/PaulStoffregen/Time /usr/local/share/arduino/libraries/Time 19 | - git clone https://github.com/PaulStoffregen/TimeAlarms /usr/local/share/arduino/libraries/TimeAlarms 20 | - git clone https://github.com/JChristensen/Timezone /usr/local/share/arduino/libraries/Timezone 21 | - arduino --install-boards esp8266:esp8266:2.4.1 22 | - arduino --board esp8266:esp8266:generic --save-prefs 23 | # - arduino --pref "compiler.warning_level=all" --save-prefs 24 | - arduino --pref "compiler.warning_level=default" --save-prefs 25 | script: 26 | - "echo $PWD" 27 | - "echo $HOME" 28 | - "ls $PWD" 29 | # - source $TRAVIS_BUILD_DIR/travis/common.sh 30 | # - build_examples 31 | # - "cat $PWD/examples/AutoConnect/AutoConnect.ino" 32 | - arduino -v --verbose-build --verify $PWD/THE433.ino 33 | #after_success: 34 | # - bash <(curl -s https://codecov.io/bash) 35 | notifications: 36 | email: 37 | on_success: change 38 | on_failure: change 39 | -------------------------------------------------------------------------------- /NKNTP.ino: -------------------------------------------------------------------------------- 1 | /* 2 | "Get time (epoch) and local time through an NTP server" 3 | 4 | modified from https://github.com/sandeepmistry/esp8266-Arduino/blob/master/esp8266com/esp8266/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | 19 | ---------------- 20 | 21 | You can edit NKNTP.h in order to change to your Timezone and DST 22 | check https://github.com/JChristensen/Timezone/blob/master/ReadMe.md for examples. 23 | 24 | -------------------------------------------------------------------------------- 25 | */ 26 | 27 | #include 28 | #include 29 | // the Timezone library is modified by nikant to remove eeprom access, check Timezone.h and Timezone.cpp for commented out sections 30 | #include //https://github.com/JChristensen/Timezone 31 | 32 | 33 | unsigned int localPort = 2390; // local port to listen for UDP packets 34 | 35 | /* Don't hardwire the IP address or we won't get the benefits of the pool. 36 | * Lookup the IP address for the host name instead */ 37 | //IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server 38 | IPAddress timeServerIP; // time.nist.gov NTP server address 39 | const char* ntpServerName = "time.nist.gov"; 40 | 41 | const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message 42 | 43 | byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 44 | 45 | // A UDP instance to let us send and receive packets over UDP 46 | WiFiUDP udp; 47 | 48 | boolean NTPsuccess = false; 49 | 50 | void getTheNTPTime() { 51 | Serial.println(F("Starting UDP")); 52 | udp.begin(localPort); 53 | Serial.print(F("Local port: ")); 54 | Serial.println(udp.localPort()); 55 | 56 | //get a random server from the pool 57 | WiFi.hostByName(ntpServerName, timeServerIP); 58 | 59 | sendNTPpacket(timeServerIP); // send an NTP packet to a time server 60 | // wait to see if a reply is available 61 | delay(1000); 62 | 63 | int cb = udp.parsePacket(); 64 | if (!cb) { 65 | Serial.println(F("no packet yet")); 66 | } 67 | else { 68 | Serial.print(F("packet received, length=")); 69 | Serial.println(cb); 70 | // We've received a packet, read the data from it 71 | udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer 72 | 73 | //the timestamp starts at byte 40 of the received packet and is four bytes, 74 | // or two words, long. First, esxtract the two words: 75 | 76 | unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); 77 | unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); 78 | // combine the four bytes (two words) into a long integer 79 | // this is NTP time (seconds since Jan 1 1900): 80 | unsigned long secsSince1900 = highWord << 16 | lowWord; 81 | //Serial.print("Seconds since Jan 1 1900 = " ); 82 | //Serial.println(secsSince1900); 83 | 84 | // now convert NTP time into everyday time: 85 | Serial.print(F("Unix time = ")); 86 | // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: 87 | const unsigned long seventyYears = 2208988800UL; 88 | // subtract seventy years: 89 | unsigned long epoch = secsSince1900 - seventyYears; 90 | 91 | // print Unix time: 92 | Serial.println(epoch); 93 | 94 | // set time to local timezone 95 | setTime(myTZ.toLocal(epoch)); 96 | 97 | NTPsuccess = true; 98 | } 99 | } 100 | 101 | // send an NTP request to the time server at the given address 102 | unsigned long sendNTPpacket(IPAddress& address) 103 | { 104 | Serial.println(F("sending NTP packet...")); 105 | // set all bytes in the buffer to 0 106 | memset(packetBuffer, 0, NTP_PACKET_SIZE); 107 | // Initialize values needed to form NTP request 108 | // (see URL above for details on the packets) 109 | packetBuffer[0] = 0b11100011; // LI, Version, Mode 110 | packetBuffer[1] = 0; // Stratum, or type of clock 111 | packetBuffer[2] = 6; // Polling Interval 112 | packetBuffer[3] = 0xEC; // Peer Clock Precision 113 | // 8 bytes of zero for Root Delay & Root Dispersion 114 | packetBuffer[12] = 49; 115 | packetBuffer[13] = 0x4E; 116 | packetBuffer[14] = 49; 117 | packetBuffer[15] = 52; 118 | 119 | // all NTP fields have been given values, now 120 | // you can send a packet requesting a timestamp: 121 | udp.beginPacket(address, 123); //NTP requests are to port 123 122 | udp.write(packetBuffer, NTP_PACKET_SIZE); 123 | udp.endPacket(); 124 | } 125 | 126 | 127 | void NTP2localTime() { 128 | int gettimestamp = 0; 129 | getTheNTPTime(); 130 | while (year() == 1970) { 131 | delay(1000); 132 | getTheNTPTime(); 133 | gettimestamp += 1; 134 | if (gettimestamp == 19) { 135 | NTPsuccess = false; 136 | break; 137 | } 138 | } 139 | gettimestamp = 0; 140 | } 141 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # THE433 2 | 3 | ## ESP8266 RF433 Interface 4 | ## "control 433MHz (compatible with Arduino libs) sockets/devices through web and time rules" 5 | 6 | [![Build Status](https://travis-ci.org/nikant/THE433.svg?branch=master)](https://travis-ci.org/nikant/THE433) 7 | 8 | ---------------- 9 | (esp8266 + RF 433 transmitter + Arduino IDE) 10 | 11 | This is a sketch for controlling RF remote control sockets or relays that operate at the 433MHz frequency 12 | and are compatible with the Arduino/esp8266 RCSwitch libraries. 13 | The main feature is that you can schedule events (up to 10) to turn ON/OFF your devices that repeat daily/weekly 14 | or that actuate once only within a week from setting the command. 15 | A web interface is used to control the RF devices directly given a relative command at the main form and also 16 | scheduling the time events by giving at the same form the keyword ENTERTIMECOMMANDS (can be changed). 17 | 18 | In the whole sketch these scheduled events are named Time Commands. 19 | 20 | Time Commands are based on the TimeAlarms library. 21 | 22 | Time Commands (up to 10) execute your functions that fire 23 | the 433MHz sockets operating devices and can be set: 24 | 25 | * Alarm Once ! up to 7 days ahead.. no more ! 26 | (once when the time next reaches the given hour, minute) 27 | i.e. now it's Monday 18:10. If you set an Alarm Once for 18:15 it will fire today. 28 | If you set it for 18:05 it will fire the next day (Tuesday) at 18:05. 29 | 30 | * Daily Alarm Repeat 31 | (every day at the given hour, minute) 32 | 33 | * Weekly Alarm Once ! up to 7 days ahead.. no more ! 34 | (once only on the next DayOfWeek, hour, minute) 35 | If you set as day the running day and hour after the current hour 36 | the alarm will fire today. 37 | 38 | * Weekly Alarm Repeat 39 | (every week on the given DayOfWeek, hour, minute) 40 | 41 | 42 | A cleanup function that runs every 33 minutes checks if any of the *Once commands 43 | are executed and deletes them from the SPIFFS save file. 44 | ! You will continue to see them in the list until your next esp8266 reboot ! 45 | 46 | **! Please WAIT between refreshing the web interface if you have restarted the esp8266 !** 47 | (a 3 second delay is added to every server responce on purpose) 48 | 49 | **! If your esp8266 can't get the NTP time then Time Commands are not available !** 50 | 51 | **! The esp8266 does not have an RTC. This sketch is based in software time keeping 52 | with the Time library and it will have some drift overtime. A restart of the device will update time !** 53 | 54 | ---------------- 55 | 56 | used/tested Arduino IDE: 1.6.5-r5 57 | 58 | Files: 59 | * THE433.ino // main sketch 60 | * NKTP.h & NKNTP.ino // get NTP time and convert to local time 61 | * espWiFi2eeprom.h & espWiFi2eeprom.ino // esp8266 WiFi configuration to eeprom manager for Arduino IDE, check espWiFi2eeprom.h 62 | 63 | Libraries needed: 64 | * ESP/Arduino core (used working version 2.3.0) 65 | * RCSwitch library for 433MHz RF control // https://github.com/sui77/rc-switch/ 66 | * RFControl library for 433MHz too.. // https://github.com/pimatic/RFControl 67 | * (not a library) espWiFi2eeprom // https://github.com/nikant/espWiFi2eeprom 68 | * Time library // https://github.com/PaulStoffregen/Time 69 | * TimeAlarms library modified dtNBR_ALARMS from 6 to 20, NO NEED WITH THE NEW LIBRARY // https://github.com/PaulStoffregen/TimeAlarms 70 | * TimeZone library // https://github.com/JChristensen/Timezone 71 | 72 | \------------ Thanks goes to fivosv for his patience to help me \------------ 73 | 74 | ### Preparing the code for your needs: 75 | 76 | To use this you have to know how to work with RF 433MHz switches/sockets and have 77 | the needed transmitters/receivers for your esp8266 or NodeMCU dev kit. 78 | 79 | **1. In order to connect to WiFi this uses the espWiFi2eeprom added files. You can read an example of how they work here: https://github.com/nikant/espWiFi2eeprom and see some screenshots here: https://nobugsjustfeatures.wordpress.com/2016/03/27/esp8266-yet-another-esp-wifi-config-to-eeprom/** 80 | 81 | **2. Set your own time zone in the NKNTP.h file.** 82 | 83 | **3. Set the appropriate 433 MHz RCSwitch codes to the "*433 functions*" section add new functions if needed** 84 | 85 | Code to edit for your RF 433 sockets or other devices: 86 | Find the *// -------------------------------- START 433 functions ---------------------------------* 87 | and edit *switchon1()* and *switchoff1()* functions according to your data sniffed from RCSwitch library 88 | 89 | // -------------------------------- with RCSwitch library ------------- 90 | . 91 | . 92 | . 93 | void switchon1() { 94 | RCSwitchCall(260, "010001111000101001010101", "

RC switch 1 ON

"); 95 | //Pulse Length-^^ 96 | //Binary Code-------------^^^^ 97 | //HTML string for web page------------------------------^^^^^ 98 | } 99 | 100 | void switchoff1() { 101 | RCSwitchCall(260, "000010000000100101010100", "

RC switch 1 OFF

"); 102 | } 103 | 104 | or with RFControl library 105 | 106 | // -------------------------------- with RFControl library ------------- 107 | . 108 | . 109 | . 110 | void switchon2() { 111 | unsigned long nsigbuckets[] = {1256, 496, 2984, 6256, 0, 0, 0, 0}; 112 | RFControlCall(nsigbuckets, "01101010010000000101011111011001101001000100101024", "

RC2-1

"); 113 | } 114 | 115 | void switchoff2() { 116 | unsigned long nsigbuckets[] = {1256, 492, 2984, 6258, 0, 0, 0, 0}; 117 | RFControlCall(nsigbuckets, "01101101100100000110011111011010011001001010101024", "

RC2-0

"); 118 | } 119 | 120 | The names of the above functions or others you have created must be entered also on the part of the code that enumerates the Time Commands which is the *TcommandsFunctions* array. 121 | 122 | // Available commands for all the 433MHz devices to be controled 123 | // All functions available at the "433 functions" section below 124 | // Function names 125 | void (*TCommandsFunctions[])() = {switchon1, switchoff1, switchon2, switchoff2}; 126 | 127 | Also the equal number of names to the *TcommandsFNames* array. Those last strings are also used from the main form of the web interface to command an RF switch. 128 | 129 | // Keywords that fire the 433MHz functions from the HTML start page 130 | char* TCommandsFNames[] = {"SWITCH-1-ON", "SWITCH-1-OFF", "SWITCH-2-ON", "SWITCH-2-OFF"}; 131 | 132 | 133 | **4.Other parts of the code to edit** 134 | 135 | Your esp8266 local network IP and port 136 | 137 | // Update these with values suitable for your network. 138 | IPAddress nkip(192, 168, 1, 101); //Node static IP 139 | IPAddress nkgateway(192, 168, 1, 1); 140 | IPAddress nksubnet(255, 255, 255, 0); 141 | 142 | // Port of esp8266 webserver 143 | ESP8266WebServer server(80); 144 | 145 | The GPIO of the 433MHz transmitter 146 | 147 | // 433MHz RF pins for esp8266 and the onboard led 148 | // pin 4 is GPIO4 which is D2 in the NodeMCU v1.0 board. 149 | #define RCSwitchPin 4 150 | 151 | If you have a NodeMCU devboard you can use the onboard led to blink when a signal is trasmitted 152 | or add your own led. 153 | 154 | // set this to 1 for the NodeMCU devboard on board LED 155 | #define HASONBOARDLED 0 156 | 157 | The keyword to enter the Time Commands interface from the main web form 158 | 159 | // Keyword to enter the Time Commands center from the start page 160 | #define TCOMMANDWORD "ENTERTIMECOMMANDS" 161 | 162 | 163 | 164 | 165 | ---------------- 166 | 167 | ### Example: 168 | 169 | ESP8266 in the source is set as a WiFi station with a static IP 192.168.1.101 170 | 171 | - navigate with your browser at this IP 172 | - here you can enter either a command to activate a connected device (you must edit the source code) i.e. SWITCH-1-ON 173 | or you can enter the provided keyword to enter the Time Commands interface i.e. ENTERTIMECOMMANDS 174 | - at the Time Commands interface you can select a function you want to be executed at a specific time 175 | - select the time to activate and submit 176 | - you'll have to restart your esp8266 and you'll be informed about this 177 | - after esp8266 restarts and reconnects you'll find the saved Time Command at the bottom of the web interface (from there you can also delete it) 178 | 179 | You can see some screenshots and a video here: https://nobugsjustfeatures.wordpress.com/2016/04/02/the433-home-automation-with-esp8266-nodemcu/ 180 | 181 | ---------------- 182 | 183 | ### LICENSE 184 | 185 | This program is free software: you can redistribute it and/or modify 186 | it under the terms of the GNU General Public License as published by 187 | the Free Software Foundation, either version 3 of the License, or 188 | (at your option) any later version. 189 | 190 | This program is distributed in the hope that it will be useful, 191 | but WITHOUT ANY WARRANTY; without even the implied warranty of 192 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 193 | GNU General Public License for more details. 194 | 195 | You should have received a copy of the GNU General Public License 196 | along with this program. If not, see . 197 | -------------------------------------------------------------------------------- /espWiFi2eeprom.ino: -------------------------------------------------------------------------------- 1 | /* 2 | "esp8266 WiFi configuration to eeprom manager for Arduino IDE" 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | 17 | - idea and some code parts from chriscook8 esp-arduino-apboot https://github.com/chriscook8/esp-arduino-apboot 18 | - sort by RSSI by tablatronix https://github.com/esp8266/Arduino/issues/1355 19 | - thanks goes to fivosv for his patience to help me 20 | 21 | ---------------- 22 | 23 | Check example-espWiFi2eeprom.ino for an example of usage along with another server. 24 | 25 | You can edit espWiFi2eeprom.h in order to change parameters. 26 | 27 | -------------------------------------------------------------------------------- 28 | */ 29 | 30 | 31 | 32 | #include 33 | #include 34 | #include 35 | 36 | // defined in espWiFi2eeprom.h , keywords to restart or clear eeprom 37 | const char* restartcommand = "/" AP_RESTART; 38 | const char* cleareepromcommand = "/" AP_CLEAREEPROM; 39 | 40 | ESP8266WebServer APserver(AP_WIFICFGPORT); 41 | 42 | // web page parts 43 | const char APwebPage1[] PROGMEM = "\n" 44 | "esp8266 WiFi setup control\n" 45 | "\n" 46 | "\n" 47 | "\n" 48 | "

esp8266 WiFi setup control

\n
" 49 | "" 50 | "" 51 | "


"; 52 | 53 | String APwebPage2 = "
\n" 54 | "

\n" 55 | "

\n" 56 | "

\n" 57 | "

- version: " ESPWIFI2EEPROM_VERSION " -\n" 58 | ""; 59 | 60 | 61 | String APwebstring = ""; // String to display 62 | 63 | 64 | // clear first bytes of eeprom 65 | void handle_clearAPeeprom() { 66 | Serial.println(F("! Clearing eeprom !")); 67 | for (int i = 0; i < 96; ++i) { 68 | EEPROM.write(i, 0); 69 | } 70 | EEPROM.commit(); 71 | delay(1000); 72 | ESP.restart(); 73 | } 74 | 75 | // restart esp8266 76 | void handle_APrestart() { 77 | Serial.println(F("! Restarting in 1 sec! !")); 78 | delay(1000); 79 | ESP.restart(); 80 | } 81 | 82 | // responds to local server / call 83 | void handle_AProot() { 84 | getAPlist(); 85 | String SServerSend; 86 | SServerSend = FPSTR(APwebPage1); 87 | SServerSend += APwebstring + APwebPage2; 88 | APserver.send(200, "text/html", SServerSend); 89 | delay(100); 90 | } 91 | 92 | // when the form with ssid and pass is submited write them to eeprom 93 | void handle_APsubmit() { 94 | String thenewssid = APserver.arg("newssid"); 95 | String thenewpass = APserver.arg("newpass"); 96 | if (thenewssid != "") { 97 | Serial.println(F("! Clearing eeprom !")); 98 | for (int i = 0; i < 96; ++i) { 99 | EEPROM.write(i, 0); 100 | } 101 | 102 | Serial.println(F("Writing SSID to EEPROM")); 103 | for (int i = 0; i < thenewssid.length(); ++i) 104 | { 105 | EEPROM.write(i, thenewssid[i]); 106 | //Serial.print("Wrote: "); 107 | //Serial.println(thenewssid[i]); 108 | } 109 | Serial.println(F("Writing password to EEPROM")); 110 | for (int i = 0; i < thenewpass.length(); ++i) 111 | { 112 | EEPROM.write(32 + i, thenewpass[i]); 113 | //Serial.print("Wrote: "); 114 | //Serial.println(thenewpass[i]); 115 | } 116 | 117 | if (EEPROM.commit()) { 118 | APwebstring = F("

Saved to eeprom... restart to boot into new wifi

\n"); 119 | } else { 120 | APwebstring = F("

Couldn't write to eeprom. Please try again.

\n"); 121 | } 122 | delay(10); 123 | String SServerSend; 124 | SServerSend = FPSTR(APwebPage1); 125 | SServerSend += APwebstring + APwebPage2; 126 | APserver.send(200, "text/html", SServerSend); 127 | delay(100); 128 | } 129 | } 130 | 131 | // return the connection type for the AP list 132 | String printConnectionType(int thisType) { 133 | String con_type = ""; 134 | // read connection type and print out the name: 135 | switch (thisType) { 136 | case 255: 137 | return con_type = "WL_NO_SHIELD"; 138 | case 0: 139 | return con_type = "WL_IDLE_STATUS"; 140 | case 1: 141 | return con_type = "WL_NO_SSID_AVAIL"; 142 | case 2: 143 | return con_type = "WL_SCAN_COMPLETED"; 144 | case 3: 145 | return con_type = "WL_CONNECTED"; 146 | case 4: 147 | return con_type = "WL_CONNECT_FAILED"; 148 | case 5: 149 | return con_type = "WL_CONNECTION_LOST"; 150 | case 6: 151 | return con_type = "WL_DISCONNECTED"; 152 | default: 153 | return con_type = "?"; 154 | } 155 | } 156 | 157 | // return the connection type for the AP list 158 | String printEncryptionType(int thisType) { 159 | String enc_type = ""; 160 | // read the encryption type and print out the name: 161 | switch (thisType) { 162 | case ENC_TYPE_WEP: 163 | return enc_type = "WEP"; 164 | case ENC_TYPE_TKIP: 165 | return enc_type = "WPA"; 166 | case ENC_TYPE_CCMP: 167 | return enc_type = "WPA2"; 168 | case ENC_TYPE_NONE: 169 | return enc_type = "None"; 170 | case ENC_TYPE_AUTO: 171 | return enc_type = "Auto"; 172 | default: 173 | return enc_type = "?"; 174 | } 175 | } 176 | 177 | // test if we are connected 178 | boolean testWiFi() { 179 | int c = 0; 180 | Serial.print(F("Waiting for Wifi to connect")); 181 | // c at 60 with delay 500 is for 30 seconds ;) 182 | while ( c < 360 ) { 183 | Serial.print("."); 184 | if (WiFi.status() == WL_CONNECTED) { 185 | Serial.println(""); 186 | Serial.println(printConnectionType(WiFi.status())); 187 | return 1; 188 | } 189 | delay(500); 190 | c++; 191 | } 192 | Serial.println(""); 193 | Serial.println(printConnectionType(WiFi.status())); 194 | return 0; 195 | } 196 | 197 | // get available AP to connect + HTML list to display 198 | void getAPlist() { 199 | WiFi.disconnect(); 200 | delay(100); 201 | int n = WiFi.scanNetworks(); 202 | Serial.println(F("Scan done")); 203 | if (n == 0) { 204 | Serial.println(F("No networks found :(")); 205 | APwebstring = F("No networks found :("); 206 | return; 207 | } 208 | 209 | // sort by RSSI 210 | int indices[n]; 211 | for (int i = 0; i < n; i++) { 212 | indices[i] = i; 213 | } 214 | for (int i = 0; i < n; i++) { 215 | for (int j = i + 1; j < n; j++) { 216 | if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) { 217 | std::swap(indices[i], indices[j]); 218 | } 219 | } 220 | } 221 | 222 | Serial.println(""); 223 | // HTML Print SSID and RSSI for each network found 224 | APwebstring = F("
    "); 225 | for (int i = 0; i < n; ++i) 226 | { 227 | APwebstring += F("
  • "); 228 | APwebstring += i + 1; 229 | APwebstring += F(":  "); 230 | APwebstring += F(""); 233 | APwebstring += WiFi.SSID(indices[i]); 234 | APwebstring += F(""); 235 | APwebstring += F("   ("); 236 | APwebstring += WiFi.RSSI(indices[i]); 237 | APwebstring += F(" dBm)   "); 238 | APwebstring += printEncryptionType(WiFi.encryptionType(indices[i])); 239 | APwebstring += F("
  • "); 240 | } 241 | APwebstring += F("
"); 242 | delay(100); 243 | } 244 | 245 | // setup a soft AP for the user to connect to esp8266 and give a new ssid and pass 246 | void setupWiFiAP() { 247 | WiFi.mode(WIFI_AP); 248 | // Do a little work to get a unique-ish name for the soft AP. Append the 249 | // last two bytes of the MAC (HEX'd): 250 | uint8_t mac[WL_MAC_ADDR_LENGTH]; 251 | WiFi.softAPmacAddress(mac); 252 | String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) + 253 | String(mac[WL_MAC_ADDR_LENGTH - 1], HEX); 254 | macID.toUpperCase(); 255 | String AP_NameString = F("esp8266 control "); 256 | AP_NameString += macID; 257 | 258 | char AP_NameChar[AP_NameString.length() + 1]; 259 | memset(AP_NameChar, 0, AP_NameString.length() + 1); 260 | 261 | for (int i = 0; i < AP_NameString.length(); i++) 262 | AP_NameChar[i] = AP_NameString.charAt(i); 263 | 264 | getAPlist(); 265 | 266 | APserver.on("/", handle_AProot); 267 | APserver.on("/APsubmit", handle_APsubmit); 268 | APserver.on(restartcommand, handle_APrestart); 269 | APserver.on(cleareepromcommand, handle_clearAPeeprom); 270 | 271 | WiFi.softAP(AP_NameChar, AP_password); 272 | 273 | APserver.begin(); 274 | 275 | Serial.print(F("SoftAP IP address: ")); 276 | Serial.println(WiFi.softAPIP()); 277 | 278 | while (WiFi.status() != WL_CONNECTED) { 279 | APserver.handleClient(); 280 | } 281 | } 282 | 283 | // main function called externally 284 | void espNKWiFiconnect() { 285 | 286 | WiFi.mode(WIFI_STA); 287 | 288 | EEPROM.begin(512); 289 | Serial.println(""); 290 | // read eeprom for ssid and pass 291 | Serial.println(F("Reading EEPROM SSID")); 292 | String esid = ""; 293 | for (int i = 0; i < 32; ++i) 294 | { 295 | esid += char(EEPROM.read(i)); 296 | } 297 | //Serial.print("SSID: "); 298 | //Serial.println(esid); 299 | Serial.println(F("Reading EEPROM password")); 300 | String epass = ""; 301 | for (int i = 32; i < 96; ++i) 302 | { 303 | epass += char(EEPROM.read(i)); 304 | } 305 | //Serial.print("PASS: "); 306 | //Serial.println(epass); 307 | 308 | // if ssid not empty try to connect 309 | if (esid != "") { 310 | // test esid 311 | WiFi.begin(esid.c_str(), epass.c_str()); 312 | 313 | boolean testWiFiAP = testWiFi(); 314 | 315 | if (testWiFiAP) { 316 | return; 317 | } else if (!testWiFiAP) { 318 | Serial.println(F("Could not connect to SSID!")); 319 | if (WiFi.status() == WL_CONNECT_FAILED) { 320 | // we found the AP but connection failed. maybe pass is wrong. 321 | // clear eeprom and restart esp so we can try again 322 | Serial.println(F("Connection failed! Maybe SSID/password are wrong.")); 323 | Serial.println(F("Clearing EEPROM and restarting!")); 324 | delay(500); 325 | handle_clearAPeeprom(); 326 | delay(100); 327 | handle_APrestart(); 328 | } else { 329 | // could not connect to ssid so starting soft AP 330 | Serial.println("Starting AP at port: " + String(AP_WIFICFGPORT)); 331 | setupWiFiAP(); 332 | } 333 | } 334 | } else { 335 | // ssid not found in eeprom so starting soft AP 336 | Serial.println("SSID empty! Starting AP at port: " + String(AP_WIFICFGPORT)); 337 | setupWiFiAP(); 338 | } 339 | } 340 | 341 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /THE433.ino: -------------------------------------------------------------------------------- 1 | /* 2 | "THE433" 3 | "ESP8266 RF433 Interface" 4 | "control 433MHz (compatible with Arduino libs) sockets/devices through web and time rules" 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | 19 | - thanks goes to fivosv for his patience to help me 20 | 21 | ---------------- 22 | 23 | used Arduino IDE: 1.6.5-r5 24 | 25 | /* 26 | "THE433" 27 | "control 433MHz (compatible with Arduino libs) sockets/devices through web and time rules" 28 | 29 | This program is free software: you can redistribute it and/or modify 30 | it under the terms of the GNU General Public License as published by 31 | the Free Software Foundation, either version 3 of the License, or 32 | (at your option) any later version. 33 | 34 | This program is distributed in the hope that it will be useful, 35 | but WITHOUT ANY WARRANTY; without even the implied warranty of 36 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 37 | GNU General Public License for more details. 38 | 39 | You should have received a copy of the GNU General Public License 40 | along with this program. If not, see . 41 | 42 | - thanks goes to fivosv for his patience to help me 43 | 44 | ---------------- 45 | 46 | used Arduino IDE: 1.6.5-r5 47 | 48 | Files: 49 | - THE433.ino // main sketch 50 | - NKTP.h & NKNTP.ino // get NTP time and convert to local time. 51 | - espWiFi2eeprom.h & espWiFi2eeprom.ino // esp8266 WiFi configuration to eeprom manager for Arduino IDE, check espWiFi2eeprom.h 52 | 53 | Libraries needed: 54 | - ESP/Arduino core (used working version 2.3.0) 55 | - RCSwitch library for 433MHz RF control // https://github.com/sui77/rc-switch/ 56 | - RFControl library for 433MHz too.. // https://github.com/pimatic/RFControl 57 | - (not a library) espWiFi2eeprom // https://github.com/nikant/espWiFi2eeprom 58 | - Time library // https://github.com/PaulStoffregen/Time 59 | - TimeAlarms library modified dtNBR_ALARMS from 6 to 20, NO NEED WITH THE NEW LIBRARY // https://github.com/PaulStoffregen/TimeAlarms 60 | - TimeZone library // https://github.com/JChristensen/Timezone 61 | 62 | ---------------- 63 | 64 | To use this you have to know how to work with RF 433MHz switches/sockets and have 65 | the needed transmitters/receivers for your esp8266 or NodeMCU dev kit. 66 | 67 | In order to connect to WiFi this uses the espWiFi2eeprom added files. 68 | You can read an example of how they work here: https://github.com/nikant/espWiFi2eeprom 69 | and see some screenshots here: https://nobugsjustfeatures.wordpress.com/2016/03/27/esp8266-yet-another-esp-wifi-config-to-eeprom/ 70 | 71 | You must also set your own time zone in the NKNTP.h file. 72 | 73 | Remember to set the appropriate 433 MHz RCSwitch codes to the "433 functions" section add new functions if needed 74 | and their names to the TcommandsFunctions array. 75 | Also the equal number of names to the TcommandsFNames array. Those last strings are also used from the main form of the web interface 76 | to command an RF switch. 77 | 78 | -------------------------------------------------------------------------------- 79 | */ 80 | 81 | #include "FS.h" // https://github.com/esp8266/Arduino/blob/master/doc/filesystem.md 82 | #include 83 | #include 84 | #include 85 | #include 86 | #include 87 | #include "espWiFi2eeprom.h" // https://github.com/nikant/espWiFi2eeprom 88 | #include "NKNTP.h" 89 | #include 90 | #include // https://www.pjrc.com/teensy/td_libs_TimeAlarms.html 91 | 92 | #define THE433_VERSION "0.8 NTP" 93 | 94 | // Initialize the 433MHz RF switch 95 | RCSwitch mySwitch = RCSwitch(); 96 | 97 | // Update these with values suitable for your network. 98 | IPAddress nkip(192, 168, 1, 101); //Node static IP 99 | IPAddress nkgateway(192, 168, 1, 1); 100 | IPAddress nksubnet(255, 255, 255, 0); 101 | 102 | // Port of esp8266 webserver 103 | ESP8266WebServer server(80); 104 | 105 | // 433MHz RF pins for esp8266 and the onboard led 106 | // pin 4 is GPIO4 which is D2 in the NodeMCU v1.0 board. 107 | #define RCSwitchPin 4 108 | #define RFrepeatTimes 30 109 | 110 | // set this to 1 for the NodeMCU devboard on board LED 111 | #define HASONBOARDLED 0 112 | #define ONBOARDLED 2 113 | 114 | 115 | // Filename of SPIFFS savefile with TimeCommands 116 | // ! Always with a / at the beginning of the filename ! 117 | #define TCSaveFile "/TCconfig.ini" 118 | // Delimiter used in TimeCommands savefile: 1 character 119 | #define TCSaveFileDelimiter "," 120 | 121 | // Keyword to enter the Time Commands center from the start page 122 | #define TCOMMANDWORD "ENTERTIMECOMMANDS" 123 | 124 | // The number of alarms can be changed in the TimeAlarms header file TimeAlarms.h set by the constant dtNBR_ALARMS 125 | // note that the RAM used equals dtNBR_ALARMS * 11 bytes 126 | // right now for THE433 project it is set to #define dtNBR_ALARMS 20 127 | // for 10 Time Alarms possible + spares for other internal functions 128 | #define MAXTCommands 10 129 | 130 | // Array that holds the Time Commands that are executed Once in RAM so they can be deleted from SPIFFS save file in the future 131 | String alarmepochs[MAXTCommands][2]; 132 | int countTCommands = 0;; 133 | 134 | // NTPInterval is how long we wait until NTP next NTP server poll 135 | #define NTPinterval 1 * 24 * 3600000 // days * hours * milliseconds (1 day) 136 | int NTPcountdown = 0; 137 | #define NTPreboot 2 138 | // Tracks the time since last NTP check 139 | unsigned long NTPpreviousMillis = 0; 140 | 141 | // ----------------------------------------------------------------------------------------- 142 | 143 | String webPageHeader(String webtitle, String webpagetitle, String backcolor, String fontcolor); 144 | String TCommandsCall(); 145 | void RCSwitchCall(int PulseL, char* RCSCode, String thepinstate); 146 | void switchon1(); 147 | void switchoff1(); 148 | void RFControlCall(unsigned long RFCbuckets[], char* RFCTimings, String thepinstate ); 149 | void switchon2(); 150 | void switchoff2(); 151 | String calcDigits(int digits); 152 | time_t tmConvert_t(int YYYY, byte MM, byte DD, byte hh, byte mm, byte ss); 153 | void nullFillalarmepochs(); 154 | void CleanupTC(); 155 | void SetupCleanTimer(String inTC, String OnceTCepoch, int inLine); 156 | void SetupAlarms(int tmpTCommand, String tmpAlarmType, String tmpDOW, int tmpTChour, int tmpTCminute); 157 | void parseTC(String inTC, int inLine); 158 | String parseTC2HTML(String inTC, int inLine); 159 | String timestamp(); 160 | void handle_restart(); 161 | void handle_timecommands(); 162 | void handle_TCsubmit(); 163 | void handle_TCsubmitRemove(); 164 | void handle_root(); 165 | void handle_submit(); 166 | void formatspiffs(); 167 | void removeTCSaveFile(); 168 | void readSpiffsTC(); 169 | void writeSpiffsTC(String inputline); 170 | void RemoveLinesSpiffsTC(String Line2Remove); 171 | 172 | // ----------------------------------------------------------------------------------------- 173 | 174 | // Available commands for all the 433MHz devices to be controled 175 | // All functions available at the "433 functions" section below 176 | // Function names 177 | void (*TCommandsFunctions[])() = {switchon1, switchoff1, switchon2, switchoff2}; 178 | // Keywords that fire the 433MHz functions from the start page 179 | char* TCommandsFNames[] = {"SWITCH-1-ON", "SWITCH-1-OFF", "SWITCH-2-ON", "SWITCH-2-OFF"}; 180 | // Calculate number of functions 181 | #define numAvailFuncs (sizeof(TCommandsFNames)/sizeof(char *)) 182 | 183 | // ----------------------------------------------------------------------------------------- 184 | 185 | // -------------------------------- setup & loop --------------------------------- 186 | 187 | void setup(void) { 188 | WiFi.persistent(false); 189 | 190 | if (HASONBOARDLED) pinMode(ONBOARDLED, OUTPUT); 191 | byte ledStatus = HIGH; 192 | 193 | mySwitch.enableTransmit(RCSwitchPin); 194 | mySwitch.setRepeatTransmit(RFrepeatTimes); 195 | 196 | Serial.begin(57600); 197 | 198 | WiFi.mode(WIFI_STA); 199 | // uncomment the following if you set a static IP in the begining 200 | WiFi.config(nkip, nkgateway, nksubnet); 201 | WiFi.setOutputPower(20.5); 202 | 203 | // call espWiFi2eeprom to connect to saved to eeprom AP or 204 | // to create an AP to store new values for SSID and password 205 | espNKWiFiconnect(); 206 | //-- 207 | 208 | Serial.print(F("IP address: ")); 209 | Serial.println(WiFi.localIP()); 210 | 211 | // espWiFi2eeprom: with the two following you can restart or clear eeprom 212 | // from your main esp8266 server 213 | server.on(restartcommand, handle_APrestart); 214 | server.on(cleareepromcommand, handle_clearAPeeprom); 215 | //-- 216 | 217 | // get NTP time and convert it to local 218 | // NKNTP.h and NKNTP.ino files must be present 219 | // in NKNTP.h you can set your time zone and DST 220 | NTP2localTime(); 221 | 222 | if (HASONBOARDLED) digitalWrite(ONBOARDLED, HIGH); 223 | 224 | delay(100); 225 | 226 | // Empty array of Time Commands at boot 227 | nullFillalarmepochs(); 228 | 229 | delay(100); 230 | 231 | // If we got NTP time then Time Commands are available 232 | if (NTPsuccess) { 233 | readSpiffsTC(); 234 | server.on("/TCsubmit", handle_TCsubmit); 235 | server.on("/removeTCSaveFile", removeTCSaveFile); 236 | server.on("/formatspiffs", formatspiffs); 237 | server.on("/TClistdelline", handle_TCsubmitRemove); 238 | } 239 | server.on("/esp433restart", handle_restart); 240 | 241 | server.on("/", handle_root); 242 | server.on("/submit", handle_submit); 243 | 244 | server.begin(); 245 | 246 | delay(100); 247 | // Set up the cleanup function of Once only executed Time Commands and poll NTP server 248 | Alarm.timerRepeat(33 * 59, CleanupTC); // (minutes * seconds) that must have passed in order to clean the alarm events, also poll NTP server 249 | Alarm.delay(0); 250 | Serial.println("Cleanup set"); 251 | 252 | Serial.println(F("HTTP server started")); 253 | //debug 254 | //for (int i = 0; i <= 10; i++) Serial.println(Alarm.read(i)); 255 | } 256 | 257 | void loop(void) { 258 | server.handleClient(); 259 | // the following is needed for the TimeAlarms libray 260 | Alarm.delay(0); 261 | } 262 | 263 | // -------------------------------- START WEB and MESSAGES --------------------------------- 264 | // HTML Strings etc. 265 | String TCsubmitResult = ""; 266 | 267 | String SPIFFSstatus; 268 | 269 | String SPIFFSTCommandsList; 270 | 271 | String pinstate = "

-

"; 272 | 273 | const char webPageClearTCButton[] PROGMEM = "
\n"; 274 | 275 | const char webPageHomeButton[] PROGMEM = "
\n"; 276 | 277 | const char webPage433form[] PROGMEM = "\n

\n"; 278 | 279 | const char webPageTC_0[] PROGMEM = "" 280 | "
 
"; 281 | 282 | const char webPageTC_1[] PROGMEM = "

Time Command: 


Schedule: 

" 283 | " Alarm Once
(once when the time next reaches the given hour, minute)

 Daily Alarm Repeat
(every day at the given hour, minute)

" 284 | " Weekly Alarm Once
(once only on the next DayOfWeek, hour, minute)

 Weekly Alarm Repeat
(every week on the given DayOfWeek, hour, minute)



Time: 

" 285 | "Day:   Hour:   Minutes:   


" 297 | "
 

"; 298 | 299 | const char webPageTC_2[] PROGMEM = "

\n"; 300 | 301 | const char NTPfail[] PROGMEM = "

NTP Time failure. TimeCommands are not available!

\n"; 302 | const char SPIFFSTCommandsList_1[] PROGMEM = "

--- TimeCommands in SPIFFS ---"; 303 | const char SPIFFSTCommandsList_2[] PROGMEM = "
--- - ---

"; 304 | const char SPIFFSTCommandsList_3[] PROGMEM = "
    "; 305 | const char SPIFFSTCommandsList_4[] PROGMEM = "
  • \n"; 307 | const char esprestartmsg[] PROGMEM = "
    Restart esp in order to activate TimeCommands!"; 308 | const char webPageRestartButton[] PROGMEM = "
    \n"; 309 | 310 | String webPageFooter = "\n
    - version: " THE433_VERSION " -\n
    ESP Free Heap: " + String(ESP.getFreeHeap()) + "\n"; 311 | 312 | String webPageHeader(String webtitle, String webpagetitle, String backcolor, String fontcolor) { 313 | return "\n" 314 | "" + webtitle + "\n" 315 | "\n" 316 | "\n" 317 | "\n" 318 | "

    " + webpagetitle + "

    \n"; 319 | } 320 | 321 | // Lists the available Time Commands for the web interface 322 | String TCommandsCall() { 323 | String TCwebstring = "
      "; 324 | for (int i = 0; i < numAvailFuncs; ++i) { 325 | String thetcommand = TCommandsFNames[i]; 326 | TCwebstring += "
    • "; 327 | TCwebstring += i + 1; 328 | TCwebstring += ":  "; 329 | TCwebstring += ""; 330 | TCwebstring += thetcommand; 331 | TCwebstring += ""; 332 | TCwebstring += "  

      "; 333 | TCwebstring += "
    • "; 334 | } 335 | TCwebstring += "
    "; 336 | return TCwebstring; 337 | } 338 | 339 | // -------------------------------- END WEB --------------------------------- 340 | 341 | // -------------------------------- START 433 functions --------------------------------- 342 | // Main 433MHz RF functions. Can be called from main page of the web interface with the keyowrds at the top. 343 | 344 | // -------------------------------- with RCSwitch library ------------- 345 | 346 | void RCSwitchCall(int PulseL, char* RCSCode, String thepinstate) { 347 | if (HASONBOARDLED) digitalWrite(ONBOARDLED, LOW); 348 | mySwitch.setPulseLength(PulseL); 349 | mySwitch.send(RCSCode); 350 | //Serial.println(F("RF SEND")); 351 | pinstate = thepinstate; 352 | if (HASONBOARDLED) digitalWrite(ONBOARDLED, HIGH); 353 | } 354 | 355 | void switchon1() { 356 | RCSwitchCall(260, "010001111000101001010101", "

    RC switch 1 ON

    "); 357 | //Pulse Length-^^ 358 | //Binary Code-------------^^^^ 359 | //HTML string for web page------------------------------^^^^^ 360 | } 361 | 362 | void switchoff1() { 363 | RCSwitchCall(260, "000010000000100101010100", "

    RC switch 1 OFF

    "); 364 | } 365 | 366 | 367 | // -------------------------------- with RFControl library ------------- 368 | void RFControlCall(unsigned long RFCbuckets[], char* RFCTimings, String thepinstate ) { 369 | if (HASONBOARDLED) digitalWrite(ONBOARDLED, LOW); 370 | RFControl::sendByCompressedTimings(RCSwitchPin, RFCbuckets, RFCTimings, RFrepeatTimes); 371 | //Serial.println(F("RF SEND")); 372 | pinstate = thepinstate; 373 | if (HASONBOARDLED) digitalWrite(ONBOARDLED, HIGH); 374 | } 375 | 376 | void switchon2() { 377 | unsigned long nsigbuckets[] = {1256, 496, 2984, 6256, 0, 0, 0, 0}; 378 | RFControlCall(nsigbuckets, "01101010010000000101011111011001101001000100101024", "

    RC2-1

    "); 379 | } 380 | 381 | void switchoff2() { 382 | unsigned long nsigbuckets[] = {1256, 492, 2984, 6258, 0, 0, 0, 0}; 383 | RFControlCall(nsigbuckets, "01101101100100000110011111011010011001001010101024", "

    RC2-0

    "); 384 | } 385 | 386 | 387 | // -------------------------------- END 433 functions --------------------------------- 388 | 389 | // -------------------------------- START general functions --------------------------------- 390 | 391 | // Pad time digits with zeros for HTML 392 | String calcDigits(int digits) { 393 | // utility function for digital clock display: prints preceding colon and leading 0 394 | String stringDigi = ""; 395 | if (digits < 10) stringDigi = "0" + String(digits); 396 | else stringDigi = String(digits); 397 | return stringDigi; 398 | } 399 | 400 | // Time.h (library) function to convert given time to seconds 401 | time_t tmConvert_t(int YYYY, byte MM, byte DD, byte hh, byte mm, byte ss) 402 | { 403 | tmElements_t tmSet; 404 | tmSet.Year = YYYY - 1970; 405 | tmSet.Month = MM; 406 | tmSet.Day = DD; 407 | tmSet.Hour = hh; 408 | tmSet.Minute = mm; 409 | tmSet.Second = ss; 410 | return makeTime(tmSet); //convert to time_t 411 | } 412 | 413 | // -------------------------------- END general functions --------------------------------- 414 | 415 | // -------------------------------- START ALARM functions --------------------------------- 416 | 417 | // Empty array of Time Commands at boot 418 | void nullFillalarmepochs() { 419 | for (int i = 0; i < MAXTCommands; i++) 420 | for (int j = 0; j < 2; j++) { 421 | alarmepochs[i][j] = ""; 422 | } 423 | } 424 | 425 | // Function to delete Time Commands that have been executed and where set to execute Once only from SPIFFS save file 426 | void CleanupTC() { 427 | //debug 428 | //Serial.print("tic "); Serial.println(second()); 429 | if (NTPsuccess) { 430 | for (int i = 0; i < MAXTCommands; i++) { 431 | if ((alarmepochs[i][0] != "") && (alarmepochs[i][1] != "")) { 432 | unsigned long chcktm = alarmepochs[i][0].toInt(); 433 | if (chcktm > 0) { 434 | // No need to set it here. It is set at main setup function at the end. 435 | //chcktm = chcktm + (2 * 60); // (minutes * seconds) that must have passed in order to clean the alarm event 436 | if (now() > chcktm) { 437 | RemoveLinesSpiffsTC(alarmepochs[i][1]); 438 | delay(100); 439 | for (int j = 0; j < 2; j++) { 440 | alarmepochs[i][j] = ""; 441 | } 442 | Serial.println(F("periodic cleanup: TimeCommand removed!")); 443 | } 444 | } 445 | } 446 | } 447 | } 448 | // NTP time poll every NTPinterval 449 | unsigned long NTPcurrentMillis = millis(); 450 | if ((unsigned long)(NTPcurrentMillis - NTPpreviousMillis) >= NTPinterval) { 451 | NTP2localTime(); 452 | Alarm.delay(0); 453 | NTPpreviousMillis = NTPcurrentMillis; 454 | if (!NTPsuccess) { 455 | NTPcountdown++; 456 | if (NTPcountdown = NTPreboot) handle_restart(); 457 | } 458 | } 459 | } 460 | 461 | // Add Time Commands that are set to execute Once only to an array to be cleaned from SPIFFS save file 462 | void SetupCleanTimer(String inTC, String OnceTCepoch, int inLine) { 463 | inTC.replace("\n", ""); 464 | inTC.trim(); 465 | alarmepochs[inLine - 1][0] = OnceTCepoch; 466 | alarmepochs[inLine - 1][1] = inTC; 467 | } 468 | 469 | // Set Time Commands to Alarms from TimeAlarms library at boot 470 | void SetupAlarms(int tmpTCommand, String tmpAlarmType, String tmpDOW, int tmpTChour, int tmpTCminute) { 471 | if (tmpAlarmType == "AlarmRepeatDaily") { 472 | Alarm.alarmRepeat(tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 473 | Serial.println(F("Alarm set!")); 474 | } else if (tmpAlarmType == "AlarmOnce") { 475 | Alarm.alarmOnce(tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 476 | Serial.println(F("Alarm set!")); 477 | } else { 478 | //dowSunday, dowMonday, dowTuesday, dowWednesday, dowThursday, dowFriday, or dowSaturday 479 | if (tmpAlarmType == "AlarmRepeatDOW") { 480 | if (tmpDOW == "1") { 481 | Alarm.alarmRepeat(dowSunday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 482 | } else if (tmpDOW == "2") { 483 | Alarm.alarmRepeat(dowMonday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 484 | } else if (tmpDOW == "3") { 485 | Alarm.alarmRepeat(dowTuesday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 486 | } else if (tmpDOW == "4") { 487 | Alarm.alarmRepeat(dowWednesday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 488 | } else if (tmpDOW == "5") { 489 | Alarm.alarmRepeat(dowThursday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 490 | } else if (tmpDOW == "6") { 491 | Alarm.alarmRepeat(dowFriday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 492 | } else if (tmpDOW == "7") { 493 | Alarm.alarmRepeat(dowSaturday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 494 | } 495 | Serial.println(F("Alarm set!")); 496 | } else if (tmpAlarmType == "AlarmOnceDOW") { 497 | if (tmpDOW == "1") { 498 | Alarm.alarmOnce(dowSunday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 499 | } else if (tmpDOW == "2") { 500 | Alarm.alarmOnce(dowMonday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 501 | } else if (tmpDOW == "3") { 502 | Alarm.alarmOnce(dowTuesday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 503 | } else if (tmpDOW == "4") { 504 | Alarm.alarmOnce(dowWednesday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 505 | } else if (tmpDOW == "5") { 506 | Alarm.alarmOnce(dowThursday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 507 | } else if (tmpDOW == "6") { 508 | Alarm.alarmOnce(dowFriday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 509 | } else if (tmpDOW == "7") { 510 | Alarm.alarmOnce(dowSaturday, tmpTChour, tmpTCminute, 0, TCommandsFunctions[tmpTCommand]); 511 | } 512 | Serial.println(F("Alarm set!")); 513 | } 514 | } 515 | // Alarm.delay to feed the TimeAlarms library 516 | Alarm.delay(100); 517 | } 518 | 519 | // Parse lines from the SPIFFS save file into SetupAlarms function above 520 | // and also to the commands to be cleaned array 521 | void parseTC(String inTC, int inLine) { 522 | int tmpTCommand, tmpTChour, tmpTCminute, ind1, ind2, ind3, ind4, ind5, ind6; 523 | String tmpAlarmType, TCcc, TChh, TCmm, tmpDOW, tmpOnceTCepoch, tmpisOnce; 524 | 525 | ind1 = inTC.indexOf(TCSaveFileDelimiter); 526 | ind2 = inTC.indexOf(TCSaveFileDelimiter, ind1 + 1); 527 | ind3 = inTC.indexOf(TCSaveFileDelimiter, ind2 + 1); 528 | ind4 = inTC.indexOf(TCSaveFileDelimiter, ind3 + 1); 529 | ind5 = inTC.indexOf(TCSaveFileDelimiter, ind4 + 1); 530 | ind6 = inTC.indexOf(TCSaveFileDelimiter, ind5 + 1); 531 | 532 | TCcc = inTC.substring(0, ind1); 533 | tmpTCommand = TCcc.toInt(); 534 | tmpAlarmType = inTC.substring(ind1 + 1, ind2); 535 | tmpDOW = inTC.substring(ind2 + 1, ind3); 536 | TChh = inTC.substring(ind3 + 1, ind4); 537 | tmpTChour = TChh.toInt(); 538 | TCmm = inTC.substring(ind4 + 1, ind5); 539 | tmpTCminute = TCmm.toInt(); 540 | tmpOnceTCepoch = inTC.substring(ind5 + 1, ind6); 541 | tmpisOnce = inTC.substring(ind6 + 1); 542 | SetupAlarms(tmpTCommand, tmpAlarmType, tmpDOW, tmpTChour, tmpTCminute); 543 | // set commands that are Once only to an array to be cleaned from SPIFFS save file 544 | if (tmpisOnce == "1") SetupCleanTimer(inTC, tmpOnceTCepoch, inLine); 545 | //Serial.println(inLine); Serial.println(tmpOnceTCepoch); 546 | } 547 | 548 | // Parse lines from the SPIFFS save file for HTML show 549 | String parseTC2HTML(String inTC, int inLine) { 550 | String tmpAlarmType, TCcc, tmpTChour, tmpTCminute, TCdd, parsed2html; 551 | int ind1, ind2, ind3, ind4, ind5, ind6, tmpTCommand, tmpDOW; 552 | 553 | ind1 = inTC.indexOf(TCSaveFileDelimiter); 554 | ind2 = inTC.indexOf(TCSaveFileDelimiter, ind1 + 1); 555 | ind3 = inTC.indexOf(TCSaveFileDelimiter, ind2 + 1); 556 | ind4 = inTC.indexOf(TCSaveFileDelimiter, ind3 + 1); 557 | ind5 = inTC.indexOf(TCSaveFileDelimiter, ind4 + 1); 558 | ind6 = inTC.indexOf(TCSaveFileDelimiter, ind5 + 1); 559 | 560 | TCcc = inTC.substring(0, ind1); 561 | tmpTCommand = TCcc.toInt(); 562 | tmpAlarmType = inTC.substring(ind1 + 1, ind2); 563 | TCdd = inTC.substring(ind2 + 1, ind3); 564 | tmpDOW = TCdd.toInt(); 565 | tmpTChour = inTC.substring(ind3 + 1, ind4); 566 | tmpTCminute = inTC.substring(ind4 + 1, ind5); 567 | //tmpOnceTCepoch = inTC.substring(ind5 + 1, ind6); 568 | //tmpisOnce = inTC.substring(ind6 + 1); 569 | parsed2html = "" + String(inLine) + ". type:" + tmpAlarmType + "  command:"; 570 | parsed2html += String(TCommandsFNames[tmpTCommand]); 571 | if (tmpDOW > 0) parsed2html += "  day:" + String(dayStr(tmpDOW)); 572 | parsed2html += "  hour:" + String(tmpTChour) + "  minute:" + tmpTCminute + "

    "; 573 | return parsed2html; 574 | } 575 | 576 | // -------------------------------- END ALARM functions --------------------------------- 577 | 578 | // -------------------------------- START server functions --------------------------------- 579 | // Timestamp function for the web interface 580 | String timestamp() { 581 | if (NTPsuccess) { 582 | String theday = dayStr(weekday()); 583 | String themonth = monthStr(month()); 584 | return "

    local time timestamp: " + theday + ", " + String(day()) + " " + themonth + " " + String(year()) + " -- " + calcDigits(hour()) + ":" + calcDigits(minute()) + ":" + calcDigits(second()) + "

    \n"; 585 | } else return FPSTR(NTPfail); 586 | } 587 | 588 | // When the Restart button is pressed at the web interface 589 | void handle_restart() { 590 | String tmppinstate; 591 | tmppinstate = pinstate; 592 | pinstate = F("Please wait a few seconds.
    ! Device will reboot !


    "); 593 | pinstate += tmppinstate; 594 | delay(100); 595 | handle_root(); 596 | delay(500); 597 | handle_APrestart(); 598 | } 599 | 600 | // Main Time Commands web interface 601 | void handle_timecommands() { 602 | String SServerSend; 603 | SServerSend = webPageHeader("THE433 TimeCommands control", "THE433 TimeCommands control", "#333", "#fff"); 604 | if (NTPsuccess) { 605 | SServerSend += TCsubmitResult + SPIFFSstatus + "
    "; 606 | SServerSend += FPSTR(webPageTC_0); 607 | SServerSend += F("You can add up to "); 608 | SServerSend += MAXTCommands; 609 | SServerSend += F(" Time Commands
    (used Time Command slots: "); 610 | SServerSend += countTCommands; 611 | SServerSend += F(")
    "); 612 | SServerSend += FPSTR(webPageTC_1); 613 | SServerSend += TCommandsCall(); 614 | SServerSend += FPSTR(webPageTC_2); 615 | } 616 | SServerSend += timestamp(); 617 | SServerSend += FPSTR(webPageHomeButton); 618 | if (NTPsuccess) SServerSend += FPSTR(SPIFFSTCommandsList_1); 619 | if (NTPsuccess) SServerSend += SPIFFSTCommandsList; 620 | if (NTPsuccess) SServerSend += FPSTR(SPIFFSTCommandsList_2); 621 | if (NTPsuccess) SServerSend += FPSTR(webPageClearTCButton); 622 | SServerSend += FPSTR(webPageRestartButton); 623 | SServerSend += webPageFooter; 624 | delay(100); 625 | server.send(200, "text/html", SServerSend); 626 | } 627 | 628 | // When a new Time Command is added from the web interface 629 | void handle_TCsubmit() { 630 | String state = server.arg("tmcommand"); 631 | if (countTCommands < MAXTCommands) { 632 | int TCommandPos = -1; 633 | for (int i = 0; i < numAvailFuncs; ++i) { 634 | if (state == TCommandsFNames[i]) { 635 | TCommandPos = i; 636 | } 637 | } 638 | if (TCommandPos == -1) { 639 | TCsubmitResult = F("Command not found!"); 640 | } else { 641 | if ((server.arg("AlarmType") == "") || (server.arg("tchour") == "") || (server.arg("tcminutes") == "")) { 642 | TCsubmitResult = F("Wrong or no selection in Schedule or Time!"); 643 | } else if (((server.arg("tcdow") == "") || (server.arg("tcdow") == "nodow")) && ((server.arg("AlarmType") == "AlarmRepeatDOW") || (server.arg("AlarmType") == "AlarmOnceDOW"))) { 644 | TCsubmitResult = F("You have to select a Day with that alarm type!"); 645 | } else if (((server.arg("tchour").toInt() >= 0) && (server.arg("tchour").toInt() < 24)) || ((server.arg("tcminutes").toInt() >= 0) && (server.arg("tcminutes").toInt() < 59))) { 646 | String S2Write; 647 | int s2d, s2h, s2m; 648 | s2d = server.arg("tcdow").toInt(); 649 | s2h = server.arg("tchour").toInt(); 650 | s2m = server.arg("tcminutes").toInt(); 651 | S2Write = String(TCommandPos) + TCSaveFileDelimiter; 652 | S2Write += server.arg("AlarmType") + TCSaveFileDelimiter; 653 | if ((server.arg("AlarmType") == "AlarmRepeatDaily") || (server.arg("AlarmType") == "AlarmOnce")) { 654 | S2Write += "nodow"; 655 | S2Write += TCSaveFileDelimiter; 656 | } else S2Write += server.arg("tcdow") + TCSaveFileDelimiter; 657 | S2Write += server.arg("tchour") + TCSaveFileDelimiter; 658 | S2Write += server.arg("tcminutes") + TCSaveFileDelimiter; 659 | time_t s_tm; 660 | if (server.arg("AlarmType") == "AlarmOnce") { 661 | if (s2h > hour()) { 662 | s_tm = tmConvert_t(year(), month(), day(), s2h, s2m, 0); 663 | } else if ((s2h == hour()) && (s2m > minute())) { 664 | s_tm = tmConvert_t(year(), month(), day(), s2h, s2m, 0); 665 | } else { 666 | s_tm = tmConvert_t(year(), month(), day() + 1, s2h, s2m, 0); 667 | } 668 | S2Write += String(s_tm) + String(TCSaveFileDelimiter) + "1"; 669 | } else if (server.arg("AlarmType") == "AlarmOnceDOW") { 670 | if (s2d == weekday()) { 671 | if (s2h > hour()) { 672 | s_tm = tmConvert_t(year(), month(), day(), s2h, s2m, 0); 673 | } else if ((s2h == hour()) && (s2m > minute())) { 674 | s_tm = tmConvert_t(year(), month(), day(), s2h, s2m, 0); 675 | } else { 676 | s_tm = tmConvert_t(year(), month(), day() + 7, s2h, s2m, 0); 677 | } 678 | } else { 679 | int s2dd = s2d - weekday(); 680 | if (s2dd < 0) { 681 | s2dd = s2dd + 7; 682 | } 683 | s_tm = tmConvert_t(year(), month(), day() + s2dd, s2h, s2m, 0); 684 | } 685 | S2Write += String(s_tm) + String(TCSaveFileDelimiter) + "1"; 686 | } else S2Write += "0" + String(TCSaveFileDelimiter) + "0"; 687 | writeSpiffsTC(S2Write); 688 | } 689 | } 690 | } else { 691 | TCsubmitResult = F("Up to "); 692 | TCsubmitResult += MAXTCommands; 693 | TCsubmitResult += F(" TimeCommands are allowed!"); 694 | } 695 | delay(100); 696 | handle_timecommands(); 697 | } 698 | 699 | // Execute Time Command remove from save file from web interface 700 | void handle_TCsubmitRemove() { 701 | delay(100); 702 | if (server.arg("TC2Remove") != "") { 703 | RemoveLinesSpiffsTC(server.arg("TC2Remove")); 704 | } else TCsubmitResult = F("No Time Command selected to delete!"); 705 | delay(100); 706 | handle_timecommands(); 707 | } 708 | 709 | // Main web page for controling 433MHz switches directly 710 | void handle_root() { 711 | String SServerSend; 712 | SServerSend = webPageHeader("THE433 control", "THE433 control", "#000", "#fff") + pinstate; 713 | SServerSend += FPSTR(webPage433form); 714 | SServerSend += timestamp(); 715 | SServerSend += SPIFFSstatus; 716 | SServerSend += FPSTR(webPageHomeButton); 717 | SServerSend += webPageFooter; 718 | server.send(200, "text/html", SServerSend); 719 | } 720 | 721 | // Form of the main web page, activates a 433MHz switch or enters Time Commands interface 722 | void handle_submit() { 723 | String state = server.arg("pin"); 724 | if (state == TCOMMANDWORD) { //"ENTERTIMECOMMANDS" 725 | delay(1000); 726 | handle_timecommands(); 727 | } else { 728 | int TCommandPos = -1; 729 | for (int i = 0; i < numAvailFuncs; ++i) { 730 | if (state == TCommandsFNames[i]) { 731 | TCommandPos = i; 732 | } 733 | } 734 | if (TCommandPos != -1) { 735 | TCommandsFunctions[TCommandPos](); 736 | delay(3000); 737 | handle_root(); 738 | } else { 739 | pinstate = F("

    -

    "); 740 | if (HASONBOARDLED) digitalWrite(ONBOARDLED, HIGH); 741 | delay(3000); 742 | handle_root(); 743 | } 744 | } 745 | } 746 | 747 | // -------------------------------- END server functions --------------------------------- 748 | 749 | // -------------------------------- START SPIFFS functions --------------------------------- 750 | // Format SPIFFS of esp8266, not accessible from the web interface 751 | void formatspiffs() { 752 | String SServerSend; 753 | SServerSend = webPageHeader("THE433 control", "THE433 control", "#000", "#fff"); 754 | SServerSend += F("

    ! formatting SPIFFS !
    Please wait 30 seconds.
    ! Device will reboot then !

    "); 755 | SServerSend += timestamp(); 756 | SServerSend += webPageFooter; 757 | server.send(200, "text/html", SServerSend); 758 | SPIFFS.begin(); 759 | SPIFFS.format(); 760 | delay(30000); 761 | Serial.println(F("SPIFFS formatted!")); 762 | handle_APrestart(); 763 | } 764 | 765 | // Deletes the TCSaveFile that Time Commands are stored in from SPIFFS 766 | void removeTCSaveFile() { 767 | SPIFFS.remove(TCSaveFile); 768 | delay(1000); 769 | Serial.println(TCSaveFile " removed."); 770 | //handle_APrestart(); 771 | handle_restart(); 772 | } 773 | 774 | // Reads the TCSaveFile that Time Commands are stored in from SPIFFS 775 | // at boot and sets the needed Alarm timers. 776 | // Also lists stored Time Commands for the web interface 777 | void readSpiffsTC() { 778 | SPIFFSstatus = ""; 779 | SPIFFSTCommandsList = ""; 780 | if (SPIFFS.begin()) { 781 | SPIFFSstatus = F("SPIFFS mounted.\n"); 782 | Serial.println(SPIFFSstatus); 783 | if (SPIFFS.exists(TCSaveFile)) { 784 | Serial.println("reading " TCSaveFile); 785 | File TCconfigFile = SPIFFS.open(TCSaveFile, "r"); 786 | if (TCconfigFile) { 787 | SPIFFSTCommandsList = FPSTR(SPIFFSTCommandsList_3); 788 | Serial.println("opened " TCSaveFile); 789 | while (TCconfigFile.available()) { 790 | String line = TCconfigFile.readStringUntil('\n'); 791 | line.replace("\n", ""); 792 | line.trim(); 793 | Serial.println(line); 794 | countTCommands++; 795 | parseTC(line, countTCommands); 796 | delay(100); 797 | SPIFFSTCommandsList += FPSTR(SPIFFSTCommandsList_4); 798 | SPIFFSTCommandsList += line + "\">  "; 799 | SPIFFSTCommandsList += parseTC2HTML(line, countTCommands); 800 | SPIFFSTCommandsList += ""; 801 | delay(100); 802 | } 803 | SPIFFSstatus += " " + String(countTCommands) + " commands read.\n"; 804 | SPIFFSTCommandsList += FPSTR(SPIFFSTCommandsList_5); 805 | } else { 806 | Serial.println("Error opening " TCSaveFile "!"); 807 | SPIFFSstatus = "Error opening " TCSaveFile "!\n"; 808 | } 809 | TCconfigFile.close(); 810 | } else { 811 | Serial.println(TCSaveFile " not found!"); 812 | SPIFFSstatus += F(" TimeCommands file not found!\n"); 813 | } 814 | } else { 815 | SPIFFSstatus = F("SPIFFS mount failed!\n"); 816 | } 817 | SPIFFSstatus = "

    " + SPIFFSstatus + "

    \n"; 818 | } 819 | 820 | // Writes a newly entered Time Command in TCSaveFile stored in SPIFFS 821 | void writeSpiffsTC(String inputline) { 822 | TCsubmitResult = ""; 823 | File TCconfigFile = SPIFFS.open(TCSaveFile, "a"); 824 | if (!TCconfigFile) { 825 | Serial.println(TCSaveFile " doesn't exist yet. Creating it"); 826 | File TCconfigFile = SPIFFS.open(TCSaveFile, "w"); 827 | if (!TCconfigFile) { 828 | Serial.println(TCSaveFile "file creation failed!!!"); 829 | TCsubmitResult = TCSaveFile "file creation failed!!!"; 830 | return; 831 | } 832 | } 833 | TCconfigFile.println(inputline); 834 | delay(100); 835 | TCconfigFile.close(); 836 | TCsubmitResult = "TimeCommand written in " TCSaveFile; 837 | TCsubmitResult += FPSTR(esprestartmsg); 838 | TCsubmitResult += FPSTR(webPageRestartButton); 839 | } 840 | 841 | // Removes a given line from TCSaveFile 842 | void RemoveLinesSpiffsTC(String Line2Remove) { 843 | TCsubmitResult = ""; 844 | if (SPIFFS.begin()) { 845 | SPIFFSstatus = F("SPIFFS mounted.\n"); 846 | Serial.println(SPIFFSstatus); 847 | if (SPIFFS.exists(TCSaveFile)) { 848 | Serial.println("reading " TCSaveFile); 849 | File TCconfigFile = SPIFFS.open(TCSaveFile, "r"); 850 | File tempTCconfigFile = SPIFFS.open("/TCconfig.temp", "w"); 851 | if (!TCconfigFile || !tempTCconfigFile) { 852 | Serial.println(F("/TCconfig.temp file creation failed!!! Aborting!")); 853 | TCsubmitResult = F("/TCconfig.temp file creation failed!!! Aborting!"); 854 | return; 855 | } 856 | Serial.println("opened " TCSaveFile); 857 | Serial.println(F("opened /TCconfig.temp")); 858 | while (TCconfigFile.available()) { 859 | String line = TCconfigFile.readStringUntil('\n'); 860 | line.replace("\n", ""); 861 | line.trim(); 862 | if (Line2Remove != line) { 863 | Serial.println(line); 864 | tempTCconfigFile.println(line); 865 | } 866 | delay(100); 867 | } 868 | Serial.println(F("/TCconfig.temp written.")); 869 | delay(10); 870 | // close files 871 | tempTCconfigFile.close(); 872 | TCconfigFile.close(); 873 | // replace config file 874 | if (SPIFFS.exists("/TCconfig.temp")) { 875 | SPIFFS.remove(TCSaveFile); 876 | delay(100); 877 | Serial.println(TCSaveFile " removed."); 878 | SPIFFS.rename("/TCconfig.temp", TCSaveFile); 879 | if (SPIFFS.exists(TCSaveFile)) { 880 | Serial.println(TCSaveFile " replaced."); 881 | TCsubmitResult = "TimeCommand removed!"; 882 | TCsubmitResult += FPSTR(esprestartmsg); 883 | TCsubmitResult += FPSTR(webPageRestartButton); 884 | } 885 | } 886 | } else { 887 | Serial.println(TCSaveFile " not found!"); 888 | SPIFFSstatus += F(" TimeCommands file not found!\n"); 889 | } 890 | } else { 891 | SPIFFSstatus = F("SPIFFS mount failed!\n"); 892 | } 893 | SPIFFSstatus = "

    " + SPIFFSstatus + "

    \n"; 894 | } 895 | 896 | // -------------------------------- END SPIFFS functions --------------------------------- 897 | --------------------------------------------------------------------------------