**NO problem with WiFi but problem persists on GSM **
#include <PubSubClient.h>
PubSubClient mqtt;
// ----------------------------------------- Sim800L ------------------------------------------- //
const int simResetPin = 16;
bool enable_GSM = true;
HardwareSerial sim800l(1); // Use Hardware Serial (Serial1) for SIM800L
String get_sim800L_response(uint16_t timeout_period = 1500, int print_response = false);
String get_network_provider_name(bool print_debug = false);
void dialRechargeQuery(const char* query);
void sim800l_startup_sequence();
bool initializeSim800L();
// Verify Device connection to Network
bool network_connected = false;
String network_provider_name = "";
bool checkNetworkStatus(uint16_t timeout_seconds = 10, bool print_debug = false);
// RSSI
uint8_t network_rssi;
int getNetworkRSSI();
// Check Balance of SIM
float check_SIM_balance(String ussdCode);
bool low_network_balance = false;
float network_balance;
//GPRS Connection
bool connectGPRS(int16_t timeout_seconds = 30);
bool checkGPRSStatus();
void blink_led(int interval = 100);
bool gprsConnected = false;
const char network_apn[] = "web"; //ntnet for NTC
const char network_user[] = "";
const char network_pass[] = "";
//------------- MQTT connection -----------------//
#define TINY_GSM_MODEM_SIM800
#define SerialAT sim800l
#include "libraries/TinyGsmClient.h"
#include <ArduinoHttpClient.h> // for HTPPS networks
TinyGsm modem(SerialAT);
TinyGsmClient gsmClient(modem);
// Define custom RX and TX pins for SIM800L
const int sim800lRXPin = 47; //43;
const int sim800lTXPin = 48; //44;
const char server1[] = "script.google.com";
const int port = 443;
This handles the MQTT
// ------------------- MQTT communication init, data receiving processing and data publishing ---------------------------------//
bool connectToMQTT(){
// Debugging information to trace where the function might fail
Serial.println("[Debug] Starting connectToMQTT");
// Ensure any previous connection is disconnected safely
if (mqtt.connected()) {
Serial.println("[Debug] MQTT client was connected, disconnecting...");
mqtt.disconnect();
delay(10); // Small delay to ensure disconnection
Serial.println("[Debug] MQTT client disconnected");
}
if (WiFi.status() == WL_CONNECTED){
// mqtt.disconnect();
Serial.println("[Info] Connecting to MQTT Via Wifi...");
mqtt.setClient(mqtt_client);
} else if(gprsConnected){
// mqtt.disconnect();
gsmClient.setTimeout(10);
gsmClient.stop(10000);
mqtt.setClient(gsmClient);
Serial.println("[Info] Connecting to MQTT Via (GSM)...");
}
else {
Serial.println("[Warning] No Connection to MQTT, WiFi or GPRS not connected...");
return false;
}
mqtt.setServer(mqttServer, mqttPort);
mqtt.setCallback(mqttCallback);
mqtt.setKeepAlive(5000);
mqtt.setSocketTimeout(20);
Serial.println(".");
String online_stat;
online_stat = "LDAS_V0.3, Device:" + mqttClientId + ", Online..";
mqttLastWillMessage = "Device: " + mqttClientId + mqttLastWillMessage;
const char* mqttID = mqttClientId.c_str();
const char* mqttLastWillMESSAGE = mqttLastWillMessage.c_str();
const char* sub_topic = mqttSubscribeTopic.c_str();
const char* pub_topic = mqttPublishTopic.c_str();
mqttLastWillTopic = pub_topic;
Serial.print("[Info] Connecting to MQTT Broker....\n");
Serial.print("[Info] MQTT Server IP: "); Serial.println(mqttServer);
Serial.print("[Info] MQTT Server Port: "); Serial.println(mqttPort);
Serial.print("[Info] MQTT Client ID: "); Serial.println(mqttClientId);
const int maxRetries = 3;
const int retryDelay = 2000; // 2 seconds
int retryCount = 1;
while (!mqtt.connect(mqttID, mqttUsername, mqttPassword, mqttLastWillTopic, /*QOS1 */0, /*lastWil Retain*/true, mqttLastWillMESSAGE, true) ) {
Serial.print("[Warning] MQTT connection failed, MQTT State: ");
Serial.println(mqtt.state());
retryCount++;
if (retryCount >= maxRetries) {
Serial.println("[Error] Maximum MQTT connection attempts reached.");
return false;
}
Serial.print("[Info] Attempting to reconnect MQTT, try ");
Serial.println(retryCount);
delay(retryDelay); // Wait before retrying
esp_task_wdt_reset();
// return false;
}
//delay(1000);
online_stat = String(mqttClientId) + "Online..\t balance:"+ String(network_balance);
Serial.println("[Info] Connected to broker.");
mqtt.publish(pub_topic, online_stat.c_str(), true);
mqtt.subscribe(sub_topic);
esp_task_wdt_reset();
return true;
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
// Handle MQTT message received here
Serial.println("[Info] MQTT Message Received:");
Serial.print("[Info] Topic: ");
Serial.println(topic);
String payload_message;
// Handle the payload data as needed
for (int i = 0; i < length; i++) {
payload_message += (char)payload[i];
}
Serial.println("[Info] Payload Message: " + payload_message);
if(payload_message.indexOf(mqttClientId + "+RST") != -1)
ESP.restart();
if(/*payload_message.equalsIgnoreCase("AT") || payload_message.equalsIgnoreCase("HELLO") || payload_message.equalsIgnoreCase("RAMLAXMAN") || */ payload_message.equalsIgnoreCase(mqttClientId)){
String return_payload;
return_payload = "MQTT Device ID: " + mqttClientId;
return_payload += "Transmitters Info: ";
for(int i=0; i<transmitter_count; i++ ){
return_payload += device_names[i];
return_payload += ", ";
}
return_payload += "\n";
return_payload += "-------Device Configuration instructions-------\n";
return_payload += "mqttClientId is the ID of the receiver Device eg: GORKHA_982F67FA....";
return_payload += "Calibrate Tx Accelerometer to zero: mqttClientId+TxName+'CAL0'";
return_payload += "mqttClientId'+RST' to Reset receiver device";
Serial.print("\n[Info] Trying Posting Cal Instruction to MQTT");
Serial.println(return_payload);
publishToMQTT(mqttSubscribeTopic, return_payload);
}
}
void publishToMQTT(String topic, String message) {
message = mqttClientId + ", " + message;
const char* pubtopic = topic.c_str();
const char* pubmessage = message.c_str();
if (WiFi.status() == WL_CONNECTED) // Tun off LED if connection fails
{
Serial.println("WiFi Connected!! Trying to publish to MQTT");
if (mqtt.publish(pubtopic, pubmessage, true)) {
Serial.println("\n[Info] WiFi MQTT Message Published successfully");
} else {
Serial.println("\n[Warning] WiFi MQTT Message publication failed");
}
// free((void*)pubtopic);
// free((void*)pubmessage);
}else if(gprsConnected) {
//Serial.println(F("[Alert] Publish Failed, MQTT not Connected..."));
Serial.println("[INFO] GPRS connected!! Trying to publish to MQTT.");
if (mqtt.publish(pubtopic, pubmessage, true)) {
Serial.println("[Info] GSM MQTT Message Published successfully");
} else {
Serial.println("[Warning] GSM MQTT Message publication failed");
}
}
else {
Serial.println("[Warning] Publishing Failed, No GPRS and Wifi Connection...");
}
}
this handles google sheet posting using http client
void https_post_to_sheets(){
// Build the JSON document
#define TINY_GSM_USE_GPRS true
TinyGsmClientSecure httpclient(modem);
HttpClient http(httpclient, server1, port);
http.setHttpResponseTimeout(10000);
Serial.print(F("\n[Info] Performing HTTPS GET request... \n"));
String url;
url.reserve(350);
Serial.println("[CORE-1][Info] connecting to server ... ");
if(http.connect(server1, port)){
Serial.println("[CORE-1][Success] Server Connected");
}
else {
Serial.println("[CORE-1][Warning] Server Connection Failed !!! ");
}
String value_description = "";
// Registered Mobile nubmber should also be sent in future
url = "/macros/s/" + Sheets_GAS_ID + "/exec?_device_id=" + Device_ID + "&";
for (int i = 0; i < numof_Parameter; i++)
{
value_description += column_names[i] + "=" + Server_Sensor_values[i];
if (i != numof_Parameter - 1)
value_description = value_description + "&";
url = url + value_description;
}
http.connectionKeepAlive(); // Currently, this is needed for HTTPS
for(int i =0; i<3; i++){ // try 3 times
Serial.print("[Info] Https Request URL: ");
Serial.print(server1);
Serial.println(url);
if(http.connected()){ // check server connectivity
Serial.println("[CORE-1][Info] Server is Connected");
continue; // skip this iteration
}else {
Serial.println("[CORE-1][Warning] Server not Connected !!! ");
http.connect(server1, port);
}
int err = http.get(url);
if (err != 0) {
Serial.println(F("[Warning] failed to connect ... "));
Serial.println(F("[Info] Reconnecting !!! "));
http.stop();
} else {
int status = http.responseStatusCode();
Serial.print(F("[Info] Response status code: "));
Serial.println(status);
if (status == 302 || status == 200) {
Serial.println("[CORE-1][Info] Data Posting to Sheets Successful");
http.stop();
return;
} else {
Serial.println("[CORE-1][Warning] Data Posting to Sheets Failed!!!");
http.stop();
}
int length = http.contentLength();
if (length >= 0) {
Serial.print(F("Content length is: "));
Serial.println(length);
}
Serial.println(F("[Alert] Server disconnected"));
}
}
}
i am using the heltec wireless stick lite v3. it uses esp32s3 chip. the sim module gets initialized, gprs get connected but it can connect to mqtt as well as http and i can't find the error in my code. i checked replacing the modules also but same problem persists.