Hi, I have been building an ESP32 Arduino based LED display array that connects to Twitch Chat using WebSockets. I am new to software, so please dumb down any replies down for me.
I have an issue where my WebSocket disconnects after some time and wont reconnect. My suspicion is that the delay times I use in just about all my animations for the LED array are interfering with the connection. Is that likely the cause?
I have a function to send PING every 30 seconds, and i do get back the PONG tmi.twitch.tv. I also believe I am successfully replying to PINGs with PONGs.
My ESP32 will reconnect fine with a reboot but not on its own. Am I doing something wrong here? Is there a fix for this?
I tried to copy all the relevant code here:
#include <WiFi.h>
#include <WebSocketsClient.h>
void animateCrab(){
showScene(crab1);
delay(400);
showScene(crab2);
delay(400);
showScene(crab1);
delay(400);
showScene(crab3);
delay(400);
//... etc etc
}
void reconnect(){
WiFi.begin(ssid,password);
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(5000);
webSocket.sendTXT("PASS " + String(twitch_oauth_token) + "\r\n");
webSocket.sendTXT("NICK " + String(twitch_nick) + "\r\n");
webSocket.sendTXT("JOIN " + String(twitch_channel) + "\r\n");
webSocket.sendTXT("CAP REQ " + String(twitch_cap) + "\r\n"); //Tag request
}
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_CONNECTED:
webSocket.sendTXT("PASS " + String(twitch_oauth_token) + "\r\n");
webSocket.sendTXT("NICK " + String(twitch_nick) + "\r\n");
webSocket.sendTXT("JOIN " + String(twitch_channel) + "\r\n");
webSocket.sendTXT("CAP REQ " + String(twitch_cap) + "\r\n");
break;
case WStype_TEXT: {
if (payload_str == "PING :tmi.twitch.tv\r\n"){
webSocket.sendTXT("PONG tmi.twitch.tv\r\n");
}
//Parse text and do animation
break;
}
case WStype_DISCONNECTED:
Serial.printf("[WSc] Disconnected!\n");
webSocket.sendTXT("PART " + String(TWITCH_CHANNEL) + "\r\n");
reconnect();
break;
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid,password);
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
webSocket.begin("irc-ws.chat.twitch.tv", 80, "/");
webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(999); // 999ms if connection has failed (WAS 5000)
}
void loop() {
webSocket.loop();
myTime = millis();
if ((idleTimeCheck(myTime) == true) && (sleepMode == true)){
if(idleScreenSet == true){
displaySetScene(sceneNum); //LED animations that use multiple delay times
webSocket.loop();
delay(5);
}
else{
showScene(userStore); //LED animations that use multiple delay times
webSocket.loop();
delay(5);
}
if (pingTimeCheck(myTime) == true){
webSocket.sendTXT("PING tmi.twitch.tv\r\n");
Serial.println("SENDING PING");
lastPingTime = myTime;
}
}
}