Skip to content

Commit

Permalink
Added MqttsBuiltlnWill example
Browse files Browse the repository at this point in the history
  • Loading branch information
lewisxhe committed Oct 25, 2024
1 parent ec0b412 commit ef77da2
Show file tree
Hide file tree
Showing 3 changed files with 500 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
| MqttsBuiltlnAWS |||||||
| MqttsBuiltlnHivemq |||||||
| MqttsBuiltlnEMQX |||||||
| MqttsBuiltlnWill |||||||
| HttpsBuiltlnGet |||||||
| HttpsBuiltlnPost |||||||
| HttpsOTAUpgrade |||||||
Expand Down
256 changes: 256 additions & 0 deletions examples/MqttsBuiltlnWill/MqttsBuiltlnWill.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
/**
* @file MqttsBuiltlnWill.ino
* @author Lewis He ([email protected])
* @license MIT
* @copyright Copyright (c) 2024 Shenzhen Xin Yuan Electronic Technology Co., Ltd
* @date 2024-10-25
* @note
* * * Example is suitable for A7670X/A7608X/SIM7672 series
* * MQTT will message example, use a private server for testing, please prepare your own MQTT server,
* * and only support MQTT3.1.1 version, and set up the will message function
* * Example uses a forked TinyGSM <https://github.com/lewisxhe/TinyGSM>, which will not compile successfully using the mainline TinyGSM.
*/
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb

// See all AT commands, if wanted
#define DUMP_AT_COMMANDS

#include "utilities.h"
#include <TinyGsmClient.h>

#ifdef DUMP_AT_COMMANDS // if enabled it requires the streamDebugger lib
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, Serial);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif

// It depends on the operator whether to set up an APN. If some operators do not set up an APN,
// they will be rejected when registering for the network. You need to ask the local operator for the specific APN.
// APNs from other operators are welcome to submit PRs for filling.
// #define NETWORK_APN "CHN-CT" //CHN-CT: China Telecom

// MQTT details
const char *broker = "Your mqtt server address";
const uint16_t broker_port = 1883;
const char *broker_username = "broker_username";
const char *broker_password = "broker_password";
const char *clien_id = "clien_id";

// Will topic , Change to the channel you want to post to
const char *will_topic = "esp32-00000-04/status";
// Will message , Change to the content you need to publish
const char *will_msg = "offline";
// Will message qos
uint8_t qos = 1;

// Current connection index, range 0~1
const uint8_t mqtt_client_id = 0;
uint32_t check_connect_millis = 0;

void mqtt_callback(const char *topic, const uint8_t *payload, uint32_t len)
{
Serial.println();
Serial.println("======mqtt_callback======");
Serial.print("Topic:"); Serial.println(topic);
Serial.println("Payload:");
for (int i = 0; i < len; ++i) {
Serial.print(payload[i], HEX); Serial.print(",");
}
Serial.println();
Serial.println("=========================");
}

bool mqtt_connect()
{
Serial.print("Connecting to ");
Serial.print(broker);

// Set will topic and message
modem.setWillMessage(will_topic, will_msg, qos);

bool ret = modem.mqtt_connect(mqtt_client_id, broker, broker_port, clien_id, broker_username, broker_password);
if (!ret) {
Serial.println("Failed!"); return false;
}
Serial.println("successes.");

if (modem.mqtt_connected()) {
Serial.println("MQTT has connected!");
} else {
return false;
}
// Set MQTT processing callback
modem.mqtt_set_callback(mqtt_callback);

return true;
}


void setup()
{
Serial.begin(115200); // Set console baud rate

while (!Serial);

Serial.println("Start Sketch");

SerialAT.begin(115200, SERIAL_8N1, MODEM_RX_PIN, MODEM_TX_PIN);

#ifdef BOARD_POWERON_PIN
pinMode(BOARD_POWERON_PIN, OUTPUT);
digitalWrite(BOARD_POWERON_PIN, HIGH);
#endif

// Set modem reset pin ,reset modem
pinMode(MODEM_RESET_PIN, OUTPUT);
digitalWrite(MODEM_RESET_PIN, !MODEM_RESET_LEVEL); delay(100);
digitalWrite(MODEM_RESET_PIN, MODEM_RESET_LEVEL); delay(2600);
digitalWrite(MODEM_RESET_PIN, !MODEM_RESET_LEVEL);

pinMode(BOARD_PWRKEY_PIN, OUTPUT);
digitalWrite(BOARD_PWRKEY_PIN, LOW);
delay(100);
digitalWrite(BOARD_PWRKEY_PIN, HIGH);
delay(100);
digitalWrite(BOARD_PWRKEY_PIN, LOW);

// Check if the modem is online
Serial.println("Start modem...");

int retry = 0;
while (!modem.testAT(1000)) {
Serial.println(".");
if (retry++ > 10) {
digitalWrite(BOARD_PWRKEY_PIN, LOW);
delay(100);
digitalWrite(BOARD_PWRKEY_PIN, HIGH);
delay(1000);
digitalWrite(BOARD_PWRKEY_PIN, LOW);
retry = 0;
}
}
Serial.println();

// Check if SIM card is online
SimStatus sim = SIM_ERROR;
while (sim != SIM_READY) {
sim = modem.getSimStatus();
switch (sim) {
case SIM_READY:
Serial.println("SIM card online");
break;
case SIM_LOCKED:
Serial.println("The SIM card is locked. Please unlock the SIM card first.");
// const char *SIMCARD_PIN_CODE = "123456";
// modem.simUnlock(SIMCARD_PIN_CODE);
break;
default:
break;
}
delay(1000);
}

//SIM7672G Can't set network mode
#ifndef TINY_GSM_MODEM_SIM7672
if (!modem.setNetworkMode(MODEM_NETWORK_AUTO)) {
Serial.println("Set network mode failed!");
}
String mode = modem.getNetworkModes();
Serial.print("Current network mode : ");
Serial.println(mode);
#endif

#ifdef NETWORK_APN
Serial.printf("Set network apn : %s\n", NETWORK_APN);
modem.sendAT(GF("+CGDCONT=1,\"IP\",\""), NETWORK_APN, "\"");
if (modem.waitResponse() != 1) {
Serial.println("Set network apn error !");
}
#endif

// Check network registration status and network signal status
int16_t sq ;
Serial.print("Wait for the modem to register with the network.");
RegStatus status = REG_NO_RESULT;
while (status == REG_NO_RESULT || status == REG_SEARCHING || status == REG_UNREGISTERED) {
status = modem.getRegistrationStatus();
switch (status) {
case REG_UNREGISTERED:
case REG_SEARCHING:
sq = modem.getSignalQuality();
Serial.printf("[%lu] Signal Quality:%d\n", millis() / 1000, sq);
delay(1000);
break;
case REG_DENIED:
Serial.println("Network registration was rejected, please check if the APN is correct");
return ;
case REG_OK_HOME:
Serial.println("Online registration successful");
break;
case REG_OK_ROAMING:
Serial.println("Network registration successful, currently in roaming mode");
break;
default:
Serial.printf("Registration Status:%d\n", status);
delay(1000);
break;
}
}
Serial.println();


Serial.printf("Registration Status:%d\n", status);
delay(1000);

String ueInfo;
if (modem.getSystemInformation(ueInfo)) {
Serial.print("Inquiring UE system information:");
Serial.println(ueInfo);
}

if (!modem.enableNetwork()) {
Serial.println("Enable network failed!");
}

delay(5000);

String ipAddress = modem.getLocalIP();
Serial.print("Network IP:"); Serial.println(ipAddress);

// Initialize MQTT, use SSL, skip authentication server
modem.mqtt_begin(false);

if (!mqtt_connect()) {
return ;
}

Serial.println("Please manually disconnect the USB-C to simulate an unexpected power outage."
"The MQTT server will send a will message to the relevant subscribers."
"If you have not subscribed to the will message, you will not see any effect.");
while (1) {
// Check the connection every ten seconds
if (millis() > check_connect_millis) {
check_connect_millis = millis() + 10000UL;
if (!modem.mqtt_connected()) {
mqtt_connect();
}
}
// MQTT handling
modem.mqtt_handle();
delay(5);
}
}

void loop()
{
// Debug AT
if (SerialAT.available()) {
Serial.write(SerialAT.read());
}
if (Serial.available()) {
SerialAT.write(Serial.read());
}
delay(1);
}
Loading

0 comments on commit ef77da2

Please sign in to comment.