-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt.ino
77 lines (67 loc) · 1.99 KB
/
mqtt.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#if defined(NEEDMQTT)
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);
int brokerConnect() {
if(config.mqttBroker.length() < 1){
return(-1);
}
Serial.println("Connecting to MQTT Broker");
client.setServer(config.mqttBroker.c_str(), config.mqttPort);
// client.setCallback(callback);
for(int i =0; i < 3;i++) {
if ( !client.connected()){
String client_id = "esp8266-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the mqtt broker %s", client_id.c_str(),config.mqttBroker.c_str());
// If there is a user account
if(config.mqttUser.length() > 1){
Serial.println(" with user/password");
if (client.connect(client_id.c_str(),config.mqttUser.c_str(),config.mqttPasswd.c_str())) {
} else {
Serial.print("failed with state ");
Serial.println(client.state());
delay(2000);
return(-2);
}
} else {
Serial.println(" without user/password");
if (client.connect(client_id.c_str())) {
} else {
Serial.print("failed with state ");
Serial.println(client.state());
delay(2000);
return(-2);
}
}
}
}
return(0);
}
void publishData(){
if(brokerConnect()){
return;
}
if (client.connected()){
char theData[2000];
char tmpstr[100];
int connectedCount = 0;
for ( int i=0; i < RELAYS;i++){
if (batteryConnected[i])
connectedCount++;
}
sprintf(theData,"{\"Connected\":%d,",connectedCount);
for(int i=0; i< RELAYS;i++){
sprintf(tmpstr,"\"%d. %s\":%4.2f,",i+1,config.labelTXT[i].c_str(),batVolts[i]);
strcat(theData,tmpstr);
}
// Replace the trailing, with }
theData[strlen(theData)-1] = '}';
// strcat(theData,"}");
Serial.print(config.mqttTopic);
Serial.print(" = ");
Serial.println(theData);
client.publish(config.mqttTopic.c_str(),theData);
}
}
#endif