WiFiSwitch.ino 8.7 KB

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