WiFiSwitch.ino 12 KB

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