Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added MQTT Support #1

Open
wants to merge 4 commits into
base: v1/main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions ActionAccessPointCli.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ static void az_scopeid_command(int argc, char **argv);
static void az_deviceid_command(int argc, char **argv);
static void az_saskey_command(int argc, char **argv);
static void az_iothub_command(int argc, char **argv);
static void mqtt_server_command(int argc, char **argv);
static void mqtt_port_command(int argc, char **argv);
static void mqtt_topic_command(int argc, char **argv);
static void mqtt_client_command(int argc, char **argv);
static void mqtt_user_command(int argc, char **argv);
static void mqtt_password_command(int argc, char **argv);
static void apmode_ssid_command(int argc, char **argv);
static void apmode_pwd_Command(int argc, char **argv);

Expand All @@ -59,6 +65,12 @@ static const struct console_command cmds[] =
{"set_az_deviceid" , "Set device id of Azure IoT Central" , false, az_deviceid_command },
{"set_az_saskey" , "Set SAS key of Azure IoT Central" , true , az_saskey_command },
{"set_az_iothub" , "Set the connection string of Azure IoT Hub" , true , az_iothub_command },
{"set_mqtt_server" , "Set the MQTT server address" , false, mqtt_server_command },
{"set_mqtt_port" , "Set the MQTT port" , false, mqtt_port_command },
{"set_mqtt_topic" , "Set the MQTT topic" , false, mqtt_topic_command },
{"set_mqtt_client" , "Set the MQTT client" , false, mqtt_client_command },
{"set_mqtt_user" , "Set the MQTT user" , false, mqtt_user_command },
{"set_mqtt_password" , "Set the MQTT port" , true , mqtt_password_command },
{"set_apmodessid" , "Set AP mode SSID" , false, apmode_ssid_command },
{"set_apmodepwd" , "Set AP mode password" , true , apmode_pwd_Command },
};
Expand Down Expand Up @@ -263,6 +275,126 @@ static void az_iothub_command(int argc, char **argv)
Serial.printf("INFO: Set Azure Iot hub connection string successfully.\r\n");
}

static void mqtt_server_command(int argc, char **argv)
{
if (argc == 1 || argv[1] == NULL)
{
Serial.printf("Usage: set_mqtt_server <url or ip address>. Please provide the server address of the MQTT server.\r\n");
return;
}
int len = strlen(argv[1]);
if (len == 0 || len > CONFIG_MQTT_SERVER_MAX_LEN)
{
Serial.printf("Invalid MQTT server address.\r\n");
return;
}

strncpy(Config.MQTTServer, argv[1], CONFIG_MQTT_SERVER_MAX_LEN + 1);

ConfigWrite();
Serial.printf("INFO: Set MQTT Server address successfully.\r\n");
}

static void mqtt_port_command(int argc, char **argv)
{
if (argc == 1 || argv[1] == NULL)
{
Serial.printf("Usage: set_mqtt_port <port>. Please provide the MQTT port.\r\n");
return;
}
int len = strlen(argv[1]);
if (len == 0 || len > CONFIG_MQTT_PORT_MAX_LEN)
{
Serial.printf("Invalid MQTT port.\r\n");
return;
}

strncpy(Config.MQTTPort, argv[1], CONFIG_MQTT_PORT_MAX_LEN + 1);

ConfigWrite();
Serial.printf("INFO: Set MQTT port successfully.\r\n");
}

static void mqtt_topic_command(int argc, char **argv)
{
if (argc == 1 || argv[1] == NULL)
{
Serial.printf("Usage: set_mqtt_topic <topic>. Please provide the MQTT topic.\r\n");
return;
}
int len = strlen(argv[1]);
if (len == 0 || len > CONFIG_MQTT_TOPIC_MAX_LEN)
{
Serial.printf("Invalid MQTT topic.\r\n");
return;
}

strncpy(Config.MQTTPort, argv[1], CONFIG_MQTT_TOPIC_MAX_LEN + 1);

ConfigWrite();
Serial.printf("INFO: Set MQTT topic successfully.\r\n");
}

static void mqtt_client_command(int argc, char **argv)
{
if (argc == 1 || argv[1] == NULL)
{
Serial.printf("Usage: set_mqtt_client <client id>. Please provide the MQTT client id.\r\n");
return;
}
int len = strlen(argv[1]);
if (len == 0 || len > CONFIG_MQTT_CLIENT_MAX_LEN)
{
Serial.printf("Invalid MQTT client id.\r\n");
return;
}

strncpy(Config.MQTTPort, argv[1], CONFIG_MQTT_CLIENT_MAX_LEN + 1);

ConfigWrite();
Serial.printf("INFO: Set MQTT client id successfully.\r\n");
}

static void mqtt_user_command(int argc, char **argv)
{
if (argc == 1 || argv[1] == NULL)
{
Serial.printf("Usage: set_mqtt_user <username>. Please provide the MQTT username.\r\n");
return;
}
int len = strlen(argv[1]);
if (len == 0 || len > CONFIG_MQTT_USER_MAX_LEN)
{
Serial.printf("Invalid MQTT username.\r\n");
return;
}

strncpy(Config.MQTTPort, argv[1], CONFIG_MQTT_USER_MAX_LEN + 1);

ConfigWrite();
Serial.printf("INFO: Set MQTT username successfully.\r\n");
}

static void mqtt_password_command(int argc, char **argv)
{
if (argc == 1 || argv[1] == NULL)
{
Serial.printf("Usage: set_mqtt_password <password>. Please provide the MQTT password.\r\n");
return;
}
int len = strlen(argv[1]);
if (len == 0 || len > CONFIG_MQTT_PASSWORD_MAX_LEN)
{
Serial.printf("Invalid MQTT password.\r\n");
return;
}

strncpy(Config.MQTTPort, argv[1], CONFIG_MQTT_PASSWORD_MAX_LEN + 1);

ConfigWrite();
Serial.printf("INFO: Set MQTT password successfully.\r\n");
}

static void apmode_ssid_command(int argc, char **argv)
{
if (argc == 1 || argv[1] == NULL)
Expand Down
179 changes: 115 additions & 64 deletions ActionSendMessage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#include <parson.h>
#include "ReButtonClient.h"
#include <SystemTime.h>
#include "MQTTClient.h"
#include "MQTTNetwork.h"

static String stringformat(const char* format, ...)
{
Expand Down Expand Up @@ -151,75 +153,124 @@ bool ActionSendMessage(ACTION_TYPE action)
IPAddress ip = WiFi.localIP();
Serial.printf("ActionSendMessage() : IP address is %s.\n", ip.get_address());

////////////////////
// Initialize IoTHub client

ReButtonClient client;
if (!client.Connect(&DeviceTwinUpdateCallbackFunc))
{
Serial.println("ActionSendMessage() : IoT Hub Connection failed");
return false;
}

////////////////////
// Make sure we are connected

Serial.println("ActionSendMessage() : Wait for connected.");
while (!client.IsConnected())
{
client.DoWork();
wait_ms(100);
// Check if IoTHub parameters are set
if (strlen(Config.IoTHubConnectionString) > 0 || (strlen(Config.ScopeId) >= 1 && strlen(Config.DeviceId) >= 1 && strlen(Config.SasKey) >= 1)){

////////////////////
// Initialize IoTHub client

ReButtonClient client;
if (!client.Connect(&DeviceTwinUpdateCallbackFunc))
{
Serial.println("ActionSendMessage() : IoT Hub Connection failed");
return false;
}

////////////////////
// Make sure we are connected

Serial.println("ActionSendMessage() : Wait for connected.");
while (!client.IsConnected())
{
client.DoWork();
wait_ms(100);
}

////////////////////
// Make sure we are received Twin Update

Serial.println("ActionSendMessage() : Wait for DeviceTwin received.");
while (!DeviceTwinReceived)
{
client.DoWork();
wait_ms(100);
}

////////////////////
// Send message

String payload = MakeMessageJsonString(action);
if (!client.SendMessageAsync(payload.c_str()))
{
Serial.println("ActionSendMessage() : SendEventAsync failed");
return false;
}

while (!client.IsMessageSent())
{
client.DoWork();
wait_ms(100);
}

while (!client.IsAllEventsSent())
{
client.DoWork();
wait_ms(100);
}

////////////////////
// Report status

client.DeviceTwinReport(MakeReportJsonString().c_str());

while (!client.IsDeviceTwinReported())
{
client.DoWork();
wait_ms(100);
}

////////////////////
// Disconnect IoTHub

client.Disconnect();
}

////////////////////
// Make sure we are received Twin Update

Serial.println("ActionSendMessage() : Wait for DeviceTwin received.");
while (!DeviceTwinReceived)
{
client.DoWork();
wait_ms(100);
// Check if MQTT Parameters are set
if (strlen(Config.MQTTServer) >= 1 && strlen(Config.MQTTPort) >= 1 && strlen(Config.MQTTTopic) >= 1 && strlen(Config.MQTTClient) >= 1){

////////////////////
// Publish MQTT Topic
MQTTNetwork mqttNetwork;
MQTT::Client<MQTTNetwork, Countdown> mqttClient = MQTT::Client<MQTTNetwork, Countdown>(mqttNetwork);

Serial.printf("Connecting to MQTT server %s:%s", Config.MQTTServer, Config.MQTTPort);

int rc = mqttNetwork.connect(Config.MQTTServer, atoi(Config.MQTTPort));
if (rc != 0) {
Serial.println("Connected to MQTT server failed");
} else {
Serial.println("Connected to MQTT server successfully");
}

MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 3;
data.clientID.cstring = Config.MQTTClient;
data.username.cstring = Config.MQTTUser;
data.password.cstring = Config.MQTTPassword;
if ((rc = mqttClient.connect(data)) != 0) {
Serial.println("MQTT client connect to server failed");
}

MQTT::Message message;

// QoS 0
char buf[256];
String payload = MakeMessageJsonString(action);
sprintf(buf, payload.c_str());
message.qos = MQTT::QOS0;
message.retained = false;
message.dup = false;
message.payload = (void*)buf;
message.payloadlen = strlen(buf);
rc = mqttClient.publish(Config.MQTTTopic, message);

if ((rc = mqttClient.disconnect()) != 0) {
Serial.println("MQTT client disconnect from server failed");
}
}

////////////////////
// Send message

String payload = MakeMessageJsonString(action);
if (!client.SendMessageAsync(payload.c_str()))
{
Serial.println("ActionSendMessage() : SendEventAsync failed");
return false;
}

while (!client.IsMessageSent())
{
client.DoWork();
wait_ms(100);
}

while (!client.IsAllEventsSent())
{
client.DoWork();
wait_ms(100);
}

////////////////////
// Report status

client.DeviceTwinReport(MakeReportJsonString().c_str());

while (!client.IsDeviceTwinReported())
{
client.DoWork();
wait_ms(100);
}

////////////////////
// Disconnect IoTHub

client.Disconnect();



Serial.println("Complete");

return true;
Expand Down
9 changes: 8 additions & 1 deletion Config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ void ConfigResetFactorySettings()

strncpy_w_zero(Config.IoTHubConnectionString, "", sizeof(Config.IoTHubConnectionString));

strncpy_w_zero(Config.MQTTServer, "", sizeof(Config.MQTTServer));
strncpy_w_zero(Config.MQTTPort, "", sizeof(Config.MQTTPort));
strncpy_w_zero(Config.MQTTTopic, "", sizeof(Config.MQTTTopic));
strncpy_w_zero(Config.MQTTClient, "", sizeof(Config.MQTTClient));
strncpy_w_zero(Config.MQTTUser, "", sizeof(Config.MQTTUser));
strncpy_w_zero(Config.MQTTPassword, "", sizeof(Config.MQTTPassword));

strncpy_w_zero(Config.APmodeSSID, ssid, sizeof(Config.APmodeSSID));
strncpy_w_zero(Config.APmodePassword, "", sizeof(Config.APmodePassword));
}
Expand Down Expand Up @@ -106,7 +113,7 @@ void ConfigPrint()
Serial.printf("WiFiSSID = %s\n", Config.WiFiSSID);
//Serial.printf("WiFiPassword = %s\n", Config.WiFiPassword);
Serial.printf("TimeServer = %s\n", Config.TimeServer);
Serial.printf("IoTHubConnectionString = %s\n", Config.IoTHubConnectionString);
//Serial.printf("IoTHubConnectionString = %s\n", Config.IoTHubConnectionString);
Serial.printf("APmodeSSID = %s\n", Config.APmodeSSID);
//Serial.printf("APmodePassword = %s\n", Config.APmodePassword);
}
Loading