#include <TinyGSM.h>
#include <TinyGsmClient.h>
#include <WebSocketsClient.h>
// Serial2 pins for ESP32 - GSM module communication
#define GSM_RX 16 // ESP32's TX2
#define GSM_TX 17 // ESP32's RX2
// GSM credentials
const char* apn = "YOUR_APN"; // Your cellular APN
const char* gprsUser = ""; // GPRS username (if needed)
const char* gprsPass = ""; // GPRS password (if needed)
// WebSocket server details
const char* websocket_server = "your-websocket-server.com";
const int websocket_port = 8080;
const char* websocket_path = "/";
// Initialize GSM modem
TinyGsm modem(Serial2);
TinyGsmClient gsmClient(modem);
WebSocketsClient webSocket;
// Callback function for WebSocket events
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
Serial.println("WebSocket Disconnected!");
break;
case WStype_CONNECTED:
Serial.println("WebSocket Connected!");
webSocket.sendTXT("Hello from ESP32 + GSM!");
break;
case WStype_TEXT:
Serial.printf("Received text: %s\n", payload);
// Echo back the received message
webSocket.sendTXT(payload);
break;
case WStype_ERROR:
Serial.println("WebSocket Error!");
break;
}
}
void setup() {
// Start Serial Monitor
Serial.begin(115200);
// Start Serial2 for GSM module
Serial2.begin(9600, SERIAL_8N1, GSM_RX, GSM_TX);
Serial.println("Initializing GSM module...");
// Initialize GSM modem
if (!modem.restart()) {
Serial.println("GSM module restart failed");
return;
}
Serial.println("GSM module OK");
Serial.println("Connecting to cellular network...");
// Connect to GPRS
if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
Serial.println("GPRS connection failed");
return;
}
Serial.println("GPRS connected");
Serial.print("IP Address: ");
Serial.println(modem.localIP());
// WebSocket server configuration
webSocket.beginSSL(websocket_server, websocket_port, websocket_path);
webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(5000);
}
void loop() {
// Check if GPRS is still connected
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected!");
// Try to reconnect
modem.gprsConnect(apn, gprsUser, gprsPass);
}
webSocket.loop();
// Example: Send a message every 30 seconds
static unsigned long lastTime = 0;
if (millis() - lastTime > 30000) {
if (webSocket.isConnected()) {
webSocket.sendTXT("Periodic message from ESP32 + GSM");
}
lastTime = millis();
}
}
// Function to handle GSM module power cycling if needed
void resetGSM() {
Serial.println("Resetting GSM module...");
// Add your GSM module's reset procedure here
// This might involve toggling a reset pin or power cycling
delay(1000);
}