Add user and pass

This commit is contained in:
Partick Balsiger
2019-04-07 17:17:44 +02:00
parent 7363e03b74
commit e58e7b3727
25 changed files with 35 additions and 6 deletions

8
src/MqttConfig.h Normal file → Executable file
View File

@@ -7,6 +7,8 @@
#define JSON_MQTT_BROKER_HOST "mqttBrokerHost"
#define JSON_MQTT_BROKER_PORT "mqttBrokerPort"
#define JSON_MQTT_TOPIC_ROOT "mqttRootTopic"
#define JSON_MQTT_USER "mqttUser"
#define JSON_MQTT_PASS "mqttPass"
struct MqttConfig
{
@@ -14,6 +16,8 @@ struct MqttConfig
const char *brokerHost;
int brokerPort;
const char *topicRoot;
const char *user;
const char *pass;
};
struct MqttConfigJson : public MqttConfig, public JsonStruct
@@ -24,6 +28,8 @@ struct MqttConfigJson : public MqttConfig, public JsonStruct
root[JSON_MQTT_BROKER_HOST] = brokerHost;
root[JSON_MQTT_BROKER_PORT] = brokerPort;
root[JSON_MQTT_TOPIC_ROOT] = topicRoot;
root[JSON_MQTT_USER] = user;
root[JSON_MQTT_PASS] = pass;
}
void fromJsonObject(JsonObject &json)
{
@@ -37,6 +43,8 @@ struct MqttConfigJson : public MqttConfig, public JsonStruct
brokerHost = getAttr(json, JSON_MQTT_BROKER_HOST);
brokerPort = getIntAttrFromJson(json, JSON_MQTT_BROKER_PORT);
topicRoot = getAttr(json, JSON_MQTT_TOPIC_ROOT);
user = getAttr(json, JSON_MQTT_USER);
pass = getAttr(json, JSON_MQTT_PASS);
valid = 1;
};
};

10
src/MqttPlugin.cpp Normal file → Executable file
View File

@@ -12,6 +12,8 @@ void MqttPlugin::applyConfig(MqttConfig cfg) {
brokerPort = cfg.brokerPort;
clientName = String(cfg.clientName);
topicRoot = String(cfg.topicRoot);
user = String(cfg.user);
pass = String(cfg.pass);
}
void MqttPlugin::applyConfigFromFile(const char* fileName) {
@@ -51,7 +53,13 @@ void MqttPlugin::connect()
if (!client->connected())
{
PRINT_MSG(Serial, "MQTT", "try connect");
if (client->connect(clientName.c_str()))
int connected = 0;
if(user.length() > 0 && pass.length() > 0){
connected = client->connect(clientName.c_str(), user.c_str(), pass.c_str());
} else {
client->connect(clientName.c_str());
}
if (connected)
{
// bind handlers to all local subscriptions
if (!subscribed)

2
src/MqttPlugin.h Normal file → Executable file
View File

@@ -37,6 +37,8 @@ private:
int brokerPort;
String clientName;
String topicRoot;
String user;
String pass;
int connectTries = 0;
int maxConnectTries = 5; // TODO add to config

0
src/examples/basic/config.h Normal file → Executable file
View File

2
src/examples/basic/main.cpp Normal file → Executable file
View File

@@ -26,7 +26,7 @@ void setup()
});
sprocket->addTask(publishHeap);
sprocket->addPlugin(
new MqttPlugin({"mqttSprocket", "192.168.1.2", 1883, "wirelos/mqttSprocket/"}));
new MqttPlugin({"clientId", "192.168.1.2", 1883, "some/topic", "myuser", "mypass"}));
network = new WiFiNet(
SPROCKET_MODE,

0
src/examples/chat/config.h Normal file → Executable file
View File

0
src/examples/chat/main.cpp Normal file → Executable file
View File