WiFiSwitch.ino 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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/out"
  22. #define DOMOTICZ_IDX_1 209
  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. const char* deviceName = DEVICE_NAME;
  63. const char* mqtt_server = MQTT_SERVER;
  64. int mqtt_port = MQTT_PORT;
  65. const char* mqtt_topic_in = MQTT_TOPIC_IN;
  66. const char* mqtt_topic_out = MQTT_TOPIC_OUT;
  67. const char* mqtt_topic_out_hold[3] = { BUTTON1_HOLD_TOPIC_OUT, BUTTON2_HOLD_TOPIC_OUT, BUTTON3_HOLD_TOPIC_OUT };
  68. const char* mqtt_payload_out_hold[3] = { BUTTON1_HOLD_PAYLOAD_OUT, BUTTON2_HOLD_PAYLOAD_OUT, BUTTON3_HOLD_PAYLOAD_OUT };
  69. int domoticzIdx[3] = {DOMOTICZ_IDX_1, DOMOTICZ_IDX_2, DOMOTICZ_IDX_3}; // initially set to 0, must be defined in config
  70. const char* domoticz_out_topic = DOMOTICZ_OUT_TOPIC; // changeable subscription topic, as domoticz supports different flat/hierarchical out-topics
  71. int relais_impulse[3] = {RELAIS1_IMPULSE, RELAIS2_IMPULSE, RELAIS3_IMPULSE};
  72. // global variables
  73. long mqttLastReconnectAttempt = 0;
  74. int usedRelaisCount = RELAIS_COUNT;
  75. bool relais_state[RELAIS_COUNT];
  76. bool relais_setState[RELAIS_COUNT];
  77. byte relais_pins[] = {PIN_RELAIS1
  78. #ifdef PIN_RELAIS2
  79. , PIN_RELAIS2
  80. #endif
  81. #ifdef PIN_RELAIS3
  82. , PIN_RELAIS3
  83. #endif
  84. };
  85. byte buttons_pins[] = {PIN_BUTTON1
  86. #ifdef PIN_BUTTON2
  87. , PIN_BUTTON2
  88. #endif
  89. #ifdef PIN_BUTTON3
  90. , PIN_BUTTON3
  91. #endif
  92. };
  93. boolean useDomoticz = false; // will be set to true in setup() if idx-values other than 0 are configured
  94. boolean domoticzOutParseData = false; // indicates that domoticz/out json data is buffered, will then be parsed in next loop() run
  95. boolean domoticzOutParserBusy = false; // indicates that domoticz/out json data is currently processed - no futher data will be accepted until finished
  96. char domoticzOutPayload[450]; // buffer for domoticz/out data
  97. boolean updateDomoticz[3] = { true, true, true }; // flag to update domoticz for device 1-3 (preventing infinite loop if triggered by domoticz/out via mqtt)
  98. byte lastSwitchSource[3] = {0, 0, 0}; // 0 = button, 1 = serial/mqtt cmd, 2 = web, 3 = domoticz/out
  99. 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]
  100. int dismissUpdateFromDomoticzTimeout = 1500;
  101. char cmdPayload[100]; // buffer for commands
  102. boolean cmdInQueue = false; // command is queued and will be processed next loop() run
  103. WiFiClient espClient;
  104. PubSubClient mqttclient(espClient);
  105. ESP8266WebServer httpServer(80);
  106. DNSServer dnsServer;
  107. PersWiFiManager persWM(httpServer, dnsServer);
  108. ESP8266HTTPUpdateServer httpUpdater;
  109. void setup() {
  110. Serial.begin(115200);
  111. delay(500);
  112. Serial.println();
  113. Serial.print(FIRMWARE_NAME);
  114. Serial.print(" v");
  115. Serial.print(VERSION);
  116. Serial.println(COPYRIGHT);
  117. Serial.println("starting...");
  118. Serial.println("Mounting FS...");
  119. if (!SPIFFS.begin()) {
  120. Serial.println("Failed to mount file system");
  121. return;
  122. }
  123. if (!loadConfig()) {
  124. Serial.println("Failed to load config");
  125. } else {
  126. Serial.println("Config loaded");
  127. }
  128. // set relais pin modes
  129. for (int i = 0; i < RELAIS_COUNT; i++) {
  130. pinMode(relais_pins[i], OUTPUT);
  131. digitalWrite(relais_pins[i], HIGH);
  132. }
  133. // set button pin modes
  134. pinMode(PIN_BUTTON1, INPUT_PULLUP);
  135. #ifdef PIN_BUTTON2
  136. pinMode(PIN_BUTTON2, INPUT_PULLUP);
  137. #endif
  138. #ifdef PIN_BUTTON3
  139. pinMode(PIN_BUTTON3, INPUT_PULLUP);
  140. #endif
  141. checkUseDomoticz();
  142. delay(500);
  143. //optional code handlers to run everytime wifi is connected...
  144. persWM.onConnect([]() {
  145. Serial.print("wifi connected to ");
  146. Serial.print(WiFi.SSID());
  147. Serial.print(", IP: ");
  148. Serial.println(WiFi.localIP());
  149. });
  150. //...or AP mode is started
  151. persWM.onAp([]() {
  152. Serial.print("AP MODE: ");
  153. Serial.println(persWM.getApSsid());
  154. });
  155. //sets network name for AP mode
  156. persWM.setApCredentials(DEVICE_NAME);
  157. //persWM.setApCredentials(DEVICE_NAME, "password"); optional password
  158. //make connecting/disconnecting non-blocking
  159. persWM.setConnectNonBlock(true);
  160. //in non-blocking mode, program will continue past this point without waiting
  161. persWM.begin();
  162. //persWM.begin("KS61T5SH", "Gurken651salat");
  163. httpServerInit();
  164. mqttClientInit();
  165. Serial.println("setup complete.");
  166. } //void setup
  167. void loop() {
  168. relais_handleImpulseTimeout();
  169. //everySecond();
  170. persWM.handleWiFi(); //in non-blocking mode, handleWiFi must be called in the main loop
  171. dnsServer.processNextRequest();
  172. httpServer.handleClient();
  173. mqttHandleConnection();
  174. checkButtonStates();
  175. evalCmd();
  176. //handleRelaisSwitching();
  177. if ( domoticzOutParseData ) parseDomoticzOut();
  178. if (Serial.available()) serialEvent();
  179. delay(50); // save energy by sleeping
  180. } //void loop