WiFiSwitch.ino 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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/Switch1/cmd"
  15. #define MQTT_TOPIC_OUT "Test/Switch1/status"
  16. #define BUTTON_DEBOUNCE_TIME 120
  17. #define BUTTON_HOLD_TIME 750
  18. #define BUTTON1_TOPIC_OUT ""
  19. #define BUTTON2_TOPIC_OUT ""
  20. #define BUTTON3_TOPIC_OUT ""
  21. #define BUTTON1_PAYLOAD_OUT ""
  22. #define BUTTON2_PAYLOAD_OUT ""
  23. #define BUTTON3_PAYLOAD_OUT ""
  24. #define BUTTON1_HOLD_TOPIC_OUT ""
  25. #define BUTTON2_HOLD_TOPIC_OUT ""
  26. #define BUTTON3_HOLD_TOPIC_OUT ""
  27. #define BUTTON1_HOLD_PAYLOAD_OUT ""
  28. #define BUTTON2_HOLD_PAYLOAD_OUT ""
  29. #define BUTTON3_HOLD_PAYLOAD_OUT ""
  30. #define DOMOTICZ_IN_TOPIC "domoticz/in"
  31. #define DOMOTICZ_OUT_TOPIC "domoticz/out"
  32. #define DOMOTICZ_IDX_1 0
  33. #define DOMOTICZ_IDX_2 0
  34. #define DOMOTICZ_IDX_3 0
  35. #define CLEARCONF_TOKEN "TUES"
  36. #define MAIN_SLEEP 10
  37. // pin assignments, total relais/button count and default logic levels
  38. // can only be changed at compile time here
  39. // only use GPIO 0, 2, 4, 5, 12, 13, 14 !!
  40. // GPIO 0 and 2 have fixed 10k pullup and must remain high during boot (otherwise flash mode is entered)
  41. // GPIO 2 is also connected to builtin LED (active LOW) on most ESP boards, so don´t care or strip it
  42. // GPIO 15 has 10k pull-down, so could only be used as active-high input
  43. // 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)
  44. // some GPIOs go high for some time at boot, so using only active-low logic is advisable, particularly for switching outputs
  45. #define RELAIS_COUNT 3
  46. #define PIN_RELAIS1 12
  47. //#define PIN_RELAIS2 4
  48. //#define PIN_RELAIS3 5
  49. #define BUTTONS_COUNT 3
  50. #define PIN_BUTTON1 0
  51. //#define PIN_BUTTON2 12
  52. //#define PIN_BUTTON3 13
  53. //#define PIN_LED1 0
  54. //#define PIN_LED2 0
  55. //#define PIN_LED3 0
  56. // default logic levels
  57. #define RELAISONSTATE LOW
  58. #define BUTTONONSTATE LOW
  59. #define LEDONSTATE LOW
  60. #include "PersWiFiManager.h"
  61. #include <ArduinoJson.h>
  62. #include <ESP8266WiFi.h>
  63. #include <WiFiClient.h>
  64. #include <ESP8266WebServer.h>
  65. #include <ESP8266mDNS.h>
  66. #include <ESP8266HTTPUpdateServer.h>
  67. #include "PubSubClient.h"
  68. #include <DNSServer.h>
  69. #include <FS.h>
  70. #ifndef MESSZ
  71. #define MESSZ 405 // Max number of characters in JSON message string (4 x DS18x20 sensors)
  72. #endif
  73. // Max message size calculated by PubSubClient is (MQTT_MAX_PACKET_SIZE < 5 + 2 + strlen(topic) + plength)
  74. #if (MQTT_MAX_PACKET_SIZE -TOPSZ -7) < MESSZ // If the max message size is too small, throw an error at compile time
  75. // See pubsubclient.c line 359
  76. #error "MQTT_MAX_PACKET_SIZE is too small in libraries/PubSubClient/src/PubSubClient.h, increase it to at least 512"
  77. #endif
  78. // config variables - do not change here!
  79. char deviceName[31];
  80. char http_user[31];
  81. char http_pass[31];
  82. char mqtt_server[41];
  83. int mqtt_port = MQTT_PORT;
  84. char mqtt_user[31];
  85. char mqtt_pass[31];
  86. char mqtt_willTopic[51];
  87. int mqtt_willQos = 2;
  88. boolean mqtt_willRetain = false;
  89. char mqtt_willMsg[31];
  90. char domoticz_out_topic[55];
  91. boolean mqtt_outRetain = false;
  92. char mqtt_topic_in[51];
  93. char mqtt_topic_out[51];
  94. boolean mqtt_btnRetain = false;
  95. char mqtt_topic_out_1[51];
  96. char mqtt_topic_out_2[51];
  97. char mqtt_topic_out_3[51];
  98. char mqtt_payload_out_1[31];
  99. char mqtt_payload_out_2[31];
  100. char mqtt_payload_out_3[31];
  101. char mqtt_topic_out_hold_1[51];
  102. char mqtt_topic_out_hold_2[51];
  103. char mqtt_topic_out_hold_3[51];
  104. char mqtt_payload_out_hold_1[31];
  105. char mqtt_payload_out_hold_2[31];
  106. char mqtt_payload_out_hold_3[31];
  107. char mqtt_allOnOffTopic[51];
  108. int domoticzIdx[3] = {DOMOTICZ_IDX_1, DOMOTICZ_IDX_2, DOMOTICZ_IDX_3}; // initially set to 0, must be defined in config
  109. int relais_impulse[3] = {RELAIS1_IMPULSE, RELAIS2_IMPULSE, RELAIS3_IMPULSE};
  110. boolean relais_invert[3] = {false, false, false};
  111. boolean button_invert[3] = {false, false, false};
  112. boolean led_invert[3] = {false, false, false};
  113. int debounceTime = BUTTON_DEBOUNCE_TIME;
  114. int buttonHoldTime = BUTTON_HOLD_TIME;
  115. boolean relais_enabled[3] = {true, false, false};
  116. boolean button_enabled[3] = {true, false, false};
  117. boolean led_enabled[3] = {false, false, false};
  118. int sleep = MAIN_SLEEP;
  119. byte hldToRel[3] = {0, 0, 0};
  120. // global variables
  121. long mqttLastReconnectAttempt = 0;
  122. int mqttReconnects = 0;
  123. boolean relais_state[RELAIS_COUNT];
  124. byte relais_pins[3];
  125. byte buttons_pins[3];
  126. byte leds_pins[3];
  127. boolean useDomoticz = false; // will be set to true in setup() if idx-values other than 0 are configured
  128. boolean domoticzOutParseData = false; // indicates that domoticz/out json data is buffered, will then be parsed in next loop() run
  129. boolean domoticzOutParserBusy = false; // indicates that domoticz/out json data is currently processed - no futher data will be accepted until finished
  130. char domoticzOutPayload[450]; // buffer for domoticz/out data
  131. boolean updateDomoticz[3] = { true, true, true }; // flag to update domoticz for device 1-3 (preventing infinite loop if triggered by domoticz/out via mqtt)
  132. byte lastSwitchSource[3] = {0, 0, 0}; // 0 = button, 1 = serial/mqtt cmd, 2 = web, 3 = domoticz/out
  133. 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]
  134. int dismissUpdateFromDomoticzTimeout = 1500;
  135. char cmdPayload[101]; // buffer for commands
  136. boolean cmdInQueue = false; // command is queued and will be processed next loop() run
  137. bool saveConfigToFlash = false;
  138. bool saveConfig2ToFlash = false;
  139. bool saveConfigHwToFlash = false;
  140. byte mqttMode = 0;
  141. WiFiClient espClient;
  142. void mqttCallback(char* topic, byte* payload, unsigned int length);
  143. PubSubClient mqttclient(espClient);
  144. ESP8266WebServer httpServer(80);
  145. DNSServer dnsServer;
  146. PersWiFiManager persWM(httpServer, dnsServer);
  147. ESP8266HTTPUpdateServer httpUpdater;
  148. void setup() {
  149. Serial.begin(115200);
  150. delay(500);
  151. Serial.println();
  152. Serial.print(FIRMWARE_NAME);
  153. Serial.print(" v");
  154. Serial.print(VERSION);
  155. Serial.println(COPYRIGHT);
  156. Serial.println("starting...");
  157. // set config default parameters
  158. #ifdef PIN_RELAIS1
  159. relais_pins[0] = PIN_RELAIS1;
  160. #endif
  161. #ifdef PIN_RELAIS2
  162. relais_pins[1] = PIN_RELAIS2;
  163. #endif
  164. #ifdef PIN_RELAIS3
  165. relais_pins[2] = PIN_RELAIS3;
  166. #endif
  167. #ifdef PIN_BUTTON1
  168. buttons_pins[0] = PIN_BUTTON1;
  169. #endif
  170. #ifdef PIN_BUTTON2
  171. buttons_pins[1] = PIN_BUTTON2;
  172. #endif
  173. #ifdef PIN_BUTTON3
  174. buttons_pins[2] = PIN_BUTTON3;
  175. #endif
  176. #ifdef PIN_LED1
  177. leds_pins[0] = PIN_LED1;
  178. #endif
  179. #ifdef PIN_LED2
  180. leds_pins[1] = PIN_LED2;
  181. #endif
  182. #ifdef PIN_LED3
  183. leds_pins[2] = PIN_LED3;
  184. #endif
  185. strlcpy(deviceName, DEVICE_NAME, 31);
  186. strlcpy(mqtt_server, MQTT_SERVER, 41);
  187. strlcpy(mqtt_topic_in, MQTT_TOPIC_IN, 51);
  188. strlcpy(mqtt_topic_out, MQTT_TOPIC_OUT, 51);
  189. strlcpy(mqtt_topic_out_1, BUTTON1_TOPIC_OUT, 51);
  190. strlcpy(mqtt_topic_out_2, BUTTON2_TOPIC_OUT, 51);
  191. strlcpy(mqtt_topic_out_3, BUTTON3_TOPIC_OUT, 51);
  192. strlcpy(mqtt_payload_out_1, BUTTON1_PAYLOAD_OUT, 31);
  193. strlcpy(mqtt_payload_out_2, BUTTON2_PAYLOAD_OUT, 31);
  194. strlcpy(mqtt_payload_out_3, BUTTON3_PAYLOAD_OUT, 31);
  195. strlcpy(mqtt_topic_out_hold_1, BUTTON1_HOLD_TOPIC_OUT, 51);
  196. strlcpy(mqtt_topic_out_hold_2, BUTTON2_HOLD_TOPIC_OUT, 51);
  197. strlcpy(mqtt_topic_out_hold_3, BUTTON3_HOLD_TOPIC_OUT, 51);
  198. strlcpy(mqtt_payload_out_hold_1, BUTTON1_HOLD_PAYLOAD_OUT, 31);
  199. strlcpy(mqtt_payload_out_hold_2, BUTTON2_HOLD_PAYLOAD_OUT, 31);
  200. strlcpy(mqtt_payload_out_hold_3, BUTTON3_HOLD_PAYLOAD_OUT, 31);
  201. strlcpy(domoticz_out_topic, DOMOTICZ_OUT_TOPIC, 51); // changeable subscription topic, as domoticz supports different flat/hierarchical out-topics
  202. Serial.println("default config values loaded..");
  203. Serial.println("Mounting FS...");
  204. if (!SPIFFS.begin()) {
  205. Serial.println("Failed to mount file system");
  206. return;
  207. }
  208. //SPIFFS.format();
  209. //Serial.print("Format SPIFFS complete.");
  210. if (!SPIFFS.exists("/formatComplete.txt")) {
  211. Serial.println("Please wait 30 secs for SPIFFS to be formatted");
  212. SPIFFS.format();
  213. Serial.println("Spiffs formatted");
  214. File f = SPIFFS.open("/formatComplete.txt", "w");
  215. if (!f) {
  216. Serial.println("file open failed");
  217. } else {
  218. f.println("Format Complete");
  219. }
  220. f.close();
  221. } else {
  222. Serial.println("SPIFFS is formatted. Moving along...");
  223. }
  224. // // load config from SPIFFS if files exist
  225. if (!loadConfigHw()) {
  226. Serial.println("Failed to load confhw.json");
  227. } else {
  228. Serial.println("confhw.json loaded");
  229. }
  230. if (!loadConfig()) {
  231. Serial.println("Failed to load conf.json");
  232. } else {
  233. Serial.println("conf.json loaded");
  234. }
  235. if (!loadConfig2()) {
  236. Serial.println("Failed to load conf2.json");
  237. } else {
  238. Serial.println("conf2.json loaded");
  239. }
  240. mqttPrepareConnection();
  241. // set relais pin modes
  242. for (int i = 0; i < 3; i++) {
  243. if (relais_enabled[i]) {
  244. if (relais_pins[i] == 0 || relais_pins[i] == 2 || relais_pins[i] == 4 || relais_pins[i] == 5 || relais_pins[i] == 12 || relais_pins[i] == 13 || relais_pins[i] == 14 || relais_pins[i] == 15) {
  245. pinMode(relais_pins[i], OUTPUT);
  246. if (relais_invert[i]) digitalWrite(relais_pins[i], RELAISONSTATE);
  247. else digitalWrite(relais_pins[i], !RELAISONSTATE);
  248. Serial.print("set GPIO ");
  249. Serial.print(relais_pins[i]);
  250. Serial.print(" as Output for Relais ");
  251. Serial.println(i + 1);
  252. }
  253. }
  254. }
  255. // set button pin modes
  256. for (int i = 0; i < 3; i++) {
  257. if (button_enabled[i]) {
  258. if (buttons_pins[i] == 0 || buttons_pins[i] == 2 || buttons_pins[i] == 4 || buttons_pins[i] == 5 || buttons_pins[i] == 12 || buttons_pins[i] == 13 || buttons_pins[i] == 14 || buttons_pins[i] == 15) {
  259. if (button_invert[i]) pinMode(buttons_pins[i], INPUT);
  260. else pinMode(buttons_pins[i], INPUT_PULLUP);
  261. Serial.print("set GPIO ");
  262. Serial.print(buttons_pins[i]);
  263. Serial.print(" as Input for Button ");
  264. Serial.println(i + 1);
  265. }
  266. }
  267. }
  268. // set LED pin modes
  269. for (int i = 0; i < 3; i++) {
  270. if (led_enabled[i]) {
  271. if (leds_pins[i] == 0 || leds_pins[i] == 2 || leds_pins[i] == 4 || leds_pins[i] == 5 || leds_pins[i] == 12 || leds_pins[i] == 13 || leds_pins[i] == 14 || leds_pins[i] == 15) {
  272. pinMode(leds_pins[i], OUTPUT);
  273. if (led_invert[i]) digitalWrite(leds_pins[i], LEDONSTATE);
  274. else digitalWrite(leds_pins[i], !LEDONSTATE);
  275. Serial.print("set GPIO ");
  276. Serial.print(leds_pins[i]);
  277. Serial.print(" as Output for status LED ");
  278. Serial.println(i + 1);
  279. }
  280. }
  281. }
  282. checkUseDomoticz();
  283. delay(500);
  284. //optional code handlers to run everytime wifi is connected...
  285. persWM.onConnect([]() {
  286. Serial.print("wifi connected to ");
  287. Serial.print(WiFi.SSID());
  288. Serial.print(", IP: ");
  289. Serial.println(WiFi.localIP());
  290. });
  291. //...or AP mode is started
  292. persWM.onAp([]() {
  293. Serial.print("AP MODE: ");
  294. Serial.println(persWM.getApSsid());
  295. });
  296. //sets network name for AP mode
  297. persWM.setApCredentials(DEVICE_NAME);
  298. //persWM.setApCredentials(DEVICE_NAME, "password"); optional password
  299. //make connecting/disconnecting non-blocking
  300. persWM.setConnectNonBlock(true);
  301. //in non-blocking mode, program will continue past this point without waiting
  302. persWM.begin();
  303. delay(500);
  304. httpServerInit();
  305. mqttClientInit();
  306. Serial.println("setup complete.");
  307. delay(1000);
  308. } //void setup
  309. void loop() {
  310. checkMillis();
  311. yield();
  312. persWM.handleWiFi(); //in non-blocking mode, handleWiFi must be called in the main loop
  313. yield();
  314. dnsServer.processNextRequest();
  315. yield();
  316. httpServer.handleClient();
  317. yield();
  318. mqttHandleConnection();
  319. yield();
  320. checkButtonStates();
  321. yield();
  322. evalCmd();
  323. yield();
  324. if ( domoticzOutParseData ) {
  325. parseDomoticzOut();
  326. yield();
  327. }
  328. if (Serial.available()) {
  329. serialEvent();
  330. yield();
  331. }
  332. delay(sleep); // save energy by sleeping, 50ms does not affect button and web
  333. } //void loop