WiFiSwitch.ino 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // pre compiletime config
  2. #define SPIFFS_DBG
  3. #define SPIFFS_USE_MAGIC
  4. #define FIRMWARE_NAME "WiFi Switch"
  5. #define VERSION "0.1"
  6. #define COPYRIGHT " by Flo Kra"
  7. // default values, can later be overridden via configuration
  8. #define DEVICE_NAME "WiFi-Switch-1"
  9. #define RELAIS1_IMPULSE 0
  10. #define RELAIS2_IMPULSE 0
  11. #define RELAIS3_IMPULSE 0
  12. #define MQTT_SERVER "10.1.1.11"
  13. #define MQTT_PORT 1883
  14. #define MQTT_TOPIC_IN "Test/Switch/cmd"
  15. #define MQTT_TOPIC_OUT "Test/Switch/status"
  16. #define BUTTON1_HOLD_TOPIC_OUT "Test/Switch/hold/1"
  17. #define BUTTON2_HOLD_TOPIC_OUT "Test/Switch/hold/2"
  18. #define BUTTON3_HOLD_TOPIC_OUT "Test/Switch/hold/3"
  19. #define BUTTON1_HOLD_PAYLOAD_OUT "TOGGLE"
  20. #define BUTTON2_HOLD_PAYLOAD_OUT "TOGGLE"
  21. #define BUTTON3_HOLD_PAYLOAD_OUT "TOGGLE"
  22. #define DOMOTICZ_IN_TOPIC "domoticz/in"
  23. #define DOMOTICZ_OUT_TOPIC "domoticz/out"
  24. #define DOMOTICZ_IDX_1 0
  25. #define DOMOTICZ_IDX_2 0
  26. #define DOMOTICZ_IDX_3 0
  27. // pin assignments, total relais/button count and default logic levels
  28. // can only be changed at compile time here
  29. // only use GPIO 0, 2, 4, 5, 12, 13, 14 !!
  30. // GPIO 0 and 2 have fixed 10k pullup and must remain high during boot (otherwise flash mode is entered)
  31. // GPIO 2 is also connected to builtin LED (active LOW) on most ESP boards, so don´t care or strip it
  32. // GPIO 15 has 10k pull-down, so could only be used as active-high input
  33. // GPIO 1 = TX and 3=RX, so could only be used when no UART is needed (using only TX for debug output and RX as GPIO3 is possible)
  34. // some GPIOs go high for some time at boot, so using only active-low logic is advisable, particularly for switching outputs
  35. #define RELAIS_COUNT 1
  36. #define PIN_RELAIS1 12
  37. #define PIN_RELAIS2 4
  38. #define PIN_RELAIS3 5
  39. #define BUTTONS_COUNT 1
  40. #define PIN_BUTTON1 0
  41. #define PIN_BUTTON2 2
  42. #define PIN_BUTTON3 13
  43. #define RELAISONSTATE HIGH
  44. #define BUTTONONSTATE LOW
  45. #include "PersWiFiManager.h"
  46. #include <ArduinoJson.h>
  47. #include <ESP8266WiFi.h>
  48. #include <WiFiClient.h>
  49. #include <ESP8266WebServer.h>
  50. #include <ESP8266mDNS.h>
  51. #include <ESP8266HTTPUpdateServer.h>
  52. #include <PubSubClient.h>
  53. #include <DNSServer.h>
  54. #include <FS.h>
  55. #ifndef MESSZ
  56. #define MESSZ 405 // Max number of characters in JSON message string (4 x DS18x20 sensors)
  57. #endif
  58. // Max message size calculated by PubSubClient is (MQTT_MAX_PACKET_SIZE < 5 + 2 + strlen(topic) + plength)
  59. #if (MQTT_MAX_PACKET_SIZE -TOPSZ -7) < MESSZ // If the max message size is too small, throw an error at compile time
  60. // See pubsubclient.c line 359
  61. #error "MQTT_MAX_PACKET_SIZE is too small in libraries/PubSubClient/src/PubSubClient.h, increase it to at least 512"
  62. #endif
  63. // config variables - do not change here!
  64. char deviceName[31];
  65. char http_user[31];
  66. char http_pass[31];
  67. char mqtt_server[41];
  68. int mqtt_port = MQTT_PORT;
  69. char mqtt_user[31];
  70. char mqtt_pass[31];
  71. char mqtt_willTopic[51];
  72. int mqtt_willQos;
  73. boolean mqtt_willRetain;
  74. char mqtt_willMsg[31];
  75. int usedRelaisCount = RELAIS_COUNT;
  76. int usedButtonsCount = BUTTONS_COUNT;
  77. char mqtt_topic_in[51];
  78. char mqtt_topic_out[51];
  79. char mqtt_topic_out_hold_1[51];
  80. char mqtt_topic_out_hold_2[51];
  81. char mqtt_topic_out_hold_3[51];
  82. char mqtt_payload_out_hold_1[31];
  83. char mqtt_payload_out_hold_2[31];
  84. char mqtt_payload_out_hold_3[31];
  85. int domoticzIdx[3] = {DOMOTICZ_IDX_1, DOMOTICZ_IDX_2, DOMOTICZ_IDX_3}; // initially set to 0, must be defined in config
  86. char domoticz_out_topic[55];
  87. int relais_impulse[3] = {RELAIS1_IMPULSE, RELAIS2_IMPULSE, RELAIS3_IMPULSE};
  88. // global variables
  89. long mqttLastReconnectAttempt = 0;
  90. bool relais_state[RELAIS_COUNT];
  91. bool relais_setState[RELAIS_COUNT];
  92. byte relais_pins[] = {PIN_RELAIS1
  93. #ifdef PIN_RELAIS2
  94. , PIN_RELAIS2
  95. #endif
  96. #ifdef PIN_RELAIS3
  97. , PIN_RELAIS3
  98. #endif
  99. };
  100. byte buttons_pins[] = {PIN_BUTTON1
  101. #ifdef PIN_BUTTON2
  102. , PIN_BUTTON2
  103. #endif
  104. #ifdef PIN_BUTTON3
  105. , PIN_BUTTON3
  106. #endif
  107. };
  108. boolean useDomoticz = false; // will be set to true in setup() if idx-values other than 0 are configured
  109. boolean domoticzOutParseData = false; // indicates that domoticz/out json data is buffered, will then be parsed in next loop() run
  110. boolean domoticzOutParserBusy = false; // indicates that domoticz/out json data is currently processed - no futher data will be accepted until finished
  111. char domoticzOutPayload[450]; // buffer for domoticz/out data
  112. boolean updateDomoticz[3] = { true, true, true }; // flag to update domoticz for device 1-3 (preventing infinite loop if triggered by domoticz/out via mqtt)
  113. byte lastSwitchSource[3] = {0, 0, 0}; // 0 = button, 1 = serial/mqtt cmd, 2 = web, 3 = domoticz/out
  114. unsigned long lastSwitchTime[3] = { 0, 0, 0 }; // this is set to millis() when relais was toggled by button or web. domoticz/out updates for this Idx are then filtered out for [dismissUpdateFromDomoticzTimeout]
  115. int dismissUpdateFromDomoticzTimeout = 1500;
  116. char cmdPayload[101]; // buffer for commands
  117. boolean cmdInQueue = false; // command is queued and will be processed next loop() run
  118. bool saveConfigToFlash = false;
  119. bool saveConfig2ToFlash = false;
  120. WiFiClient espClient;
  121. PubSubClient mqttclient(espClient);
  122. ESP8266WebServer httpServer(80);
  123. DNSServer dnsServer;
  124. PersWiFiManager persWM(httpServer, dnsServer);
  125. ESP8266HTTPUpdateServer httpUpdater;
  126. void setup() {
  127. Serial.begin(115200);
  128. delay(500);
  129. Serial.println();
  130. Serial.print(FIRMWARE_NAME);
  131. Serial.print(" v");
  132. Serial.print(VERSION);
  133. Serial.println(COPYRIGHT);
  134. Serial.println("starting...");
  135. // set config default parameters
  136. strlcpy(deviceName, DEVICE_NAME, 31);
  137. strlcpy(mqtt_server, MQTT_SERVER, 41);
  138. strlcpy(mqtt_topic_in, MQTT_TOPIC_IN, 51);
  139. strlcpy(mqtt_topic_out, MQTT_TOPIC_OUT, 51);
  140. strlcpy(mqtt_topic_out_hold_1, BUTTON1_HOLD_TOPIC_OUT, 51);
  141. strlcpy(mqtt_topic_out_hold_2, BUTTON2_HOLD_TOPIC_OUT, 51);
  142. strlcpy(mqtt_topic_out_hold_3, BUTTON3_HOLD_TOPIC_OUT, 51);
  143. strlcpy(mqtt_payload_out_hold_1, BUTTON1_HOLD_PAYLOAD_OUT, 31);
  144. strlcpy(mqtt_payload_out_hold_2, BUTTON2_HOLD_PAYLOAD_OUT, 31);
  145. strlcpy(mqtt_payload_out_hold_3, BUTTON3_HOLD_PAYLOAD_OUT, 31);
  146. strlcpy(domoticz_out_topic, DOMOTICZ_OUT_TOPIC, 51); // changeable subscription topic, as domoticz supports different flat/hierarchical out-topics
  147. Serial.println("default config values loaded..");
  148. Serial.println("Mounting FS...");
  149. if (!SPIFFS.begin()) {
  150. Serial.println("Failed to mount file system");
  151. return;
  152. }
  153. //SPIFFS.format();
  154. if (!SPIFFS.exists("/formatComplete.txt")) {
  155. Serial.println("Please wait 30 secs for SPIFFS to be formatted");
  156. SPIFFS.format();
  157. Serial.println("Spiffs formatted");
  158. File f = SPIFFS.open("/formatComplete.txt", "w");
  159. if (!f) {
  160. Serial.println("file open failed");
  161. } else {
  162. f.println("Format Complete");
  163. }
  164. f.close();
  165. } else {
  166. Serial.println("SPIFFS is formatted. Moving along...");
  167. }
  168. // // load config from SPIFFS file if exists
  169. if (!loadConfig()) {
  170. Serial.println("Failed to load config");
  171. } else {
  172. Serial.println("Config loaded");
  173. }
  174. if (!loadConfig2()) {
  175. Serial.println("Failed to load config2");
  176. } else {
  177. Serial.println("Config2 loaded");
  178. }
  179. // set relais pin modes
  180. for (int i = 0; i < RELAIS_COUNT; i++) {
  181. pinMode(relais_pins[i], OUTPUT);
  182. digitalWrite(relais_pins[i], !RELAISONSTATE);
  183. }
  184. // set button pin modes
  185. pinMode(PIN_BUTTON1, INPUT_PULLUP);
  186. #ifdef PIN_BUTTON2
  187. pinMode(PIN_BUTTON2, INPUT_PULLUP);
  188. #endif
  189. #ifdef PIN_BUTTON3
  190. pinMode(PIN_BUTTON3, INPUT_PULLUP);
  191. #endif
  192. checkUseDomoticz();
  193. delay(500);
  194. //optional code handlers to run everytime wifi is connected...
  195. persWM.onConnect([]() {
  196. Serial.print("wifi connected to ");
  197. Serial.print(WiFi.SSID());
  198. Serial.print(", IP: ");
  199. Serial.println(WiFi.localIP());
  200. });
  201. //...or AP mode is started
  202. persWM.onAp([]() {
  203. Serial.print("AP MODE: ");
  204. Serial.println(persWM.getApSsid());
  205. });
  206. //sets network name for AP mode
  207. persWM.setApCredentials(DEVICE_NAME);
  208. //persWM.setApCredentials(DEVICE_NAME, "password"); optional password
  209. //make connecting/disconnecting non-blocking
  210. persWM.setConnectNonBlock(true);
  211. //in non-blocking mode, program will continue past this point without waiting
  212. persWM.begin();
  213. //persWM.begin("KS61T5SH", "Gurken651salat");
  214. httpServerInit();
  215. mqttClientInit();
  216. Serial.println("setup complete.");
  217. delay(1000);
  218. } //void setup
  219. void loop() {
  220. checkSaveConfigTriggered();
  221. relais_handleImpulseTimeout();
  222. //everySecond();
  223. persWM.handleWiFi(); //in non-blocking mode, handleWiFi must be called in the main loop
  224. dnsServer.processNextRequest();
  225. httpServer.handleClient();
  226. mqttHandleConnection();
  227. checkButtonStates();
  228. evalCmd();
  229. //handleRelaisSwitching();
  230. if ( domoticzOutParseData ) parseDomoticzOut();
  231. if (Serial.available()) serialEvent();
  232. delay(50); // save energy by sleeping
  233. } //void loop