Modular ESP Firmware - OTA - Source

From The TinkerNet Wiki
Revision as of 23:20, 26 December 2020 by Tinker (talk | contribs) (Created page with "== platformio.ini == <syntaxhighlight lang="ini" line="1"> [env:esp07] platform = espressif8266 board = esp07 framework = arduino monitor_speed = 115200 build_flags =...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

platformio.ini

 1 [env:esp07]
 2 platform = espressif8266
 3 board = esp07
 4 framework = arduino
 5 monitor_speed = 115200
 6 build_flags =
 7         -D DEBUG
 8 
 9 lib_deps =
10     PubSubClient

main.cpp

  1 /*
  2 	What is this thingy here? Put in your notes for it so others know what it is for...
  3 	Give credit where credit is due
  4 	Etc
  5 	
  6 */
  7 #include <Arduino.h>
  8 #include <ESP8266mDNS.h>
  9 #include <WiFiUdp.h>
 10 #include <ArduinoOTA.h>
 11 #include <PubSubClient.h>
 12 #include "SecretSquirrel.h"
 13 
 14 WiFiClient NameYerSelf;
 15 PubSubClient mqttclient(NameYerSelf);
 16 
 17 unsigned long timer = 0;
 18 unsigned long debounce_timer = 0;
 19 unsigned long blink_timer = 0;
 20 unsigned long beacon_timer = 0;
 21 unsigned long total_reset_timer = 0;
 22 
 23 // Timer Intervals - ALL non-blocking timers
 24 #define BLINK_INTERVAL		500			// Fast blink interval, half second
 25 #define SLOW_BLINK_INTERVAL	1800		// Slow blink interval, 1.8 seconds
 26 #define DEBOUNCE_INTERVAL	1500			// Button Debounce
 27 #define BEACON_INTERVAL		30000		// Timer interval for the "keep-alive" status beacon
 28 //#define RELAY_INTERVAL		6000		// Lock/Unlock relay operation time
 29 
 30 
 31 // I/O - Setup the I/O HERE
 32 #define gateTrigger      	14
 33 
 34 
 35 //Function Prototypes
 36 void callback(char* topic, byte* payload, unsigned int length);
 37 bool getTimer(unsigned long &timer, int interval);
 38 bool TimeReached(uint32_t* tSaved, uint32_t ElapsedTime);
 39 void mqttReconnect(void);
 40 
 41 
 42 /****************************************************************
 43  * Main program setup
 44  ****************************************************************
 45  */
 46 void setup()
 47 {
 48 	Serial.begin(115200);
 49 	WiFi.mode(WIFI_STA);
 50 
 51 	pinMode(gateTrigger, INPUT);
 52 
 53 	//Connecting to MQTT server and setup callback
 54   	mqttclient.setServer(D_MQTTSERVER, D_MQTTPORT);
 55   	mqttclient.setCallback(callback);
 56 
 57 	//Start up Wifi connection
 58 	
 59 	WiFi.begin(D_SSID, D_PASSWORD);
 60 
 61 	while (WiFi.status() != WL_CONNECTED)
 62 	{
 63 		delay(500);
 64 		Serial.println("Connecting to WiFi..");
 65 	}
 66 
 67 	Serial.println("Connected to the WiFi network");
 68 
 69 	//Connecting to MQTT server
 70 	
 71 	while (!mqttclient.connected())
 72 	{
 73 		Serial.println("Hello Skeeter...");
 74 		if (mqttclient.connect(mqtt_client, user, pass ))
 75 		{
 76 			Serial.println("MQTT Connected");
 77 			//Subscribe to appropriate topics on MQTT
 78 			//mqttclient.subscribe("vault/reset");
 79 			//mqttclient.subscribe("vault/retrieve");
 80 		strcpy(MQTTtopic,MQTTtele);
 81 		strcat(MQTTtopic,"/");
 82 		strcat(MQTTtopic,DeviceName);
 83 
 84 		mqttclient.publish( MQTTtopic , "I'm Ready For Doody!");
 85 		}
 86 		else
 87 		{
 88 			Serial.print("Failed with state ");
 89 			Serial.print(mqttclient.state());
 90 			delay(2000);
 91 		}
 92 	}
 93 
 94 
 95     ArduinoOTA.begin();
 96 
 97 #ifdef DEBUG0
 98 	Serial.println("Ready");
 99  	Serial.print("IP address: ");
100   	Serial.println(WiFi.localIP());
101 #endif
102 	
103 }
104 	
105 
106 
107 /*************************************************************************************
108  * Main program loop
109  *************************************************************************************
110  *************************************************************************************
111  */
112 
113 void loop()
114 {
115 	mqttclient.loop();
116 	ArduinoOTA.handle();
117 	
118 	//Keeps MQTT connected
119 	if (!mqttclient.connected())
120 	{
121 		Serial.println("MQTT disconnected for some reason");
122 		mqttReconnect();
123 	}
124 	
125 	/* Beacon signal published at set interval so I can tell that the vault
126 	** is still powered up and actively connected to MQTT... a keepalive of sorts
127 	** also updates state within MQTT so it can be captured for indicator light elsewhere
128 	*/
129 	if (getTimer(beacon_timer, BEACON_INTERVAL))
130 	{
131 		strcpy(MQTTtopic,MQTTtele);
132 		strcat(MQTTtopic,"/");
133 		strcat(MQTTtopic,DeviceName);
134 
135 		mqttclient.publish( MQTTtopic , "beep");
136 		mqttclient.publish( MQTTtopic , "boop");
137 	}
138 
139 	/*
140 	 * Loop Body functions go here																																###Main Loop Body Here###
141 	 * 
142 	 *
143 	if (!digitalRead(gateTrigger) && getTimer(debounce_timer, DEBOUNCE_INTERVAL))
144 			{
145 				mqttclient.publish("gate/trigger", "0");
146 				Serial.println("Gate Alarm Triggered");
147 			}
148 			*/
149 }
150 
151 /****************************************************************************************
152 * This is where the functions live
153 *****************************************************************************************
154 *****************************************************************************************
155 
156 ** MQTT Reconnect
157 *
158 ** Makes sure that MQTT gets reconnected if it is disconnected.
159 ** Randomly sets reset period from 0-10 seconds
160 ** Called near top of void loop()
161 */
162 
163 // Time elapsed function for mqttReconnect() that updates the time when true
164 bool TimeReached(uint32_t* tSaved, uint32_t ElapsedTime){
165   if(abs(millis()-*tSaved)>=ElapsedTime){ *tSaved=millis();
166     return true;
167   }
168   return false;
169 }
170 
171 void mqttReconnect(void){
172 	uint32_t tSavedLoop = millis();
173 	uint32_t tSavedReconnectAttempt = millis(); //tSaved I use for time or "tick" stored
174 	uint32_t rSavedReconnectAttempt = 0;  //rSaved I use r for rate, milliseconds between firing
175 
176     // wait 1-10 seconds before retrying to prevent rush event
177     if((!mqttclient.connected())&&TimeReached(&tSavedReconnectAttempt,rSavedReconnectAttempt)){
178       	
179 		rSavedReconnectAttempt = random(1,20)*500; // random backup period (0:0.5:10 seconds)
180      	mqttclient.connect(mqtt_client, user, pass );
181 	  	Serial.println("MQTT connected again");
182 		//mqttclient.subscribe("vault/reset");
183 		//mqttclient.subscribe("vault/retrieve");
184 	}
185 	else{
186       
187       	if(abs(millis()-tSavedLoop)>100){
188 			tSavedLoop = millis(); 
189     		mqttclient.loop();
190       	}
191 
192     }
193 }
194 /****************************************************************************************
195 * MQTT event listener. Receives message payload
196 *
197 * @param char array topic MQTT topic we're receiving via
198 * @param byte array payload Contents of message
199 * @param int length String length of message
200 * @return void
201 */
202 void callback(char* topic, byte* payload, unsigned int length){
203 	
204 	// Check the topic to determine correct action
205 	mqttclient.setServer(D_MQTTSERVER, D_MQTTPORT);
206 	mqttclient.setCallback(callback);
207 	
208 	// A topic
209 	if (strcmp(topic, "something/here") == 0)
210 	{
211 		//Do something maybe?
212 	}
213 	// Another topic
214 	else if (strcmp(topic, "something/else") == 0)
215 	{
216 	//Do something else
217 	}
218 }
219 
220 /************************************************
221 * Global timer function, used a lot
222 *
223 * @param unisnged long time The current timer
224 * @param int interval Length of time to run timer
225 *
226 * @return bool True when timer is complete
227 * @return bool False when timer is counting
228 */
229 bool getTimer(unsigned long &timer, int interval){
230 	
231 	if (timer < 1)
232 	{
233 		timer = millis();
234 	}
235 
236 	if (millis() - timer >= interval)
237 	{
238 		timer = 0;
239 		return true;
240 	}
241 
242 	return false;
243 }

SecretSquirrel.h

 1 const char* D_MQTTSERVER = "BROKER.YOURDOMAIN.TLD";
 2 
 3 const uint16_t D_MQTTPORT = 1883;
 4 
 5 const char* D_SSID = "YourSSID";
 6 
 7 const char* D_PASSWORD = "YOURpass";
 8 
 9 const char* mqtt_client = "OTAtest";
10 
11 const char* user = "";
12 
13 const char* pass = "";
14 
15 char MQTTtopic[256];
16 const char* DeviceName = "OTA_tester";
17 
18 const char* MQTTtele ="Telemetry";
19 const char* MQTTcmnd ="Command";