-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt.cpp
253 lines (165 loc) · 6.9 KB
/
mqtt.cpp
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#include <stdlib.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#define MQTT_MAX_PACKET_SIZE 2560
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <NtpClientLib.h>
#include "util.h"
#include "udp.h"
#include "device.h"
#include "mqtt.h"
WiFiClient espClient;
PubSubClient mqttclient(espClient);
bool MQTTpublish(String topic, String message) {
//Serial.printf("MQTTpublish1 [%s] conf.MQTT_enable [%d]\n", message.c_str(), conf.MQTT_enable );
if (!WiFi.isConnected() || conf.MQTT_enable == false) return true;
//if (conf.interruptProcess == false)
mqttclient.publish(topic.c_str(), message.c_str());
//Serial.printf("MQTTpublish2 [%s]\n", message.c_str());
return true;
}
bool MQTTpublish(String message) {
// mqttclient.publish("domoticz/in", message.c_str());
return MQTTpublish("domoticz/in", message);
}
bool MQTTLogMessage(String message)
//bool MQTTLogMessage(const char *message)
{
if (conf.interruptProcess == false) Serial.printf("MQTTLog [%s] [%s]\n", NTP.getTimeDateString().c_str(),message.c_str());
//Serial.printf("MQTTLog [%s]\n",message);
//return true;
return MQTTpublish("itzone/device/"+conf.hostName+"/log", NTP.getTimeDateString()+":"+message);
}
bool getDevices(String url) {
HTTPClient httpclient;
//String url =String("http://")+conf.Domoticz_userName+":"+conf.Domoticz_password+"@"+conf.Domoticz_hostName+":"+ conf.Domoticz_port+"/json.htm?type=devices&filter=all&used=true&order=Name";
// Serial.printf("Executing [%s]\n",url.c_str() );
//MQTTLogMessage("getDevices");
httpclient.begin(url); //HTTP
int httpRetCode = httpclient.GET();
String payload;
// Serial.printf("ret code [%d]\n",httpRetCode );
if (httpRetCode == HTTP_CODE_OK) {
int size = httpclient.getSize();
httpServer.setContentLength(size);
httpServer.send(200, "text/html", "");
///////////////////////////////////////////////////////////
/*
// get lenght of document (is -1 when Server sends no Content-Length header)
int len = httpclient.getSize();
// create buffer for read
uint8_t buff[128] = { 0 };
// get tcp stream
WiFiClient * stream = httpclient.getStreamPtr();
// read all data from server
while(httpclient.connected() && (len > 0 || len == -1)) {
// get available data size
size_t size = stream->available();
if(size) {
// read up to 128 byte
int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
// write it to Serial
Serial.write(buff, c);
httpServer.client().write((uint8_t *)buff, c);
if(len > 0) {
len -= c;
}
}
delay(1);
}
*/
//////////////////////////////////////////////////////////
payload = httpclient.getString();
Serial.printf("payload %s\n", payload.c_str());
httpServer.sendContent(payload);
httpclient.end();
//MQTTLogMessage("getDevices end");
return true;
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", httpclient.errorToString(httpRetCode).c_str());
MQTTLogMessage(String("[HTTP] GET... failed, error: ") + httpclient.errorToString(httpRetCode));
httpclient.end();
return false;
}
}
/*
void callback(char * topic, byte * payload, unsigned int length) {
// Serial.print("MQTT message arrived [");
// Serial.print(topic);
// Serial.print("] ");
char json[length];
int i = 0;
for (i = 0; i < length; i++) {
// Serial.print((char)payload[i]);
json[i] = (char) payload[i];
}
// Serial.println();
json[i] = '\n';
//Serial.printf("callback json");
Serial.printf("callback json %s\n", json);
String payloadString = String(json);
//if (strcmp(topic, runtime.pingtopic.c_str()) ==0 ){processUDPMQTTCallback(payloadString );return;}
// StaticJsonBuffer<1000> jsonBuffer;
if (isValidJson(payloadString) == false) return;
DynamicJsonDocument doc(length);
deserializeJson(doc, json);
JsonObject root = doc.to < JsonObject > ();
const char * idx = root["idx"];
const char * nvalue = root["nvalue"];
int idx_int = atoi(idx);
// Serial.printf("status idx %d nvalue [%s]\n", idx_int,nvalue );
int nvalue_int = atoi(nvalue);
for (i = 0; i < 2; i++) {
if (idx_int == conf.relays[i].domoticz_device_idx && nvalue_int != conf.relays[i].relay_state) {
MQTTLogMessage(String("new mqtt message for relay ") + i + " domoticz idx " + idx_int + " value " + nvalue_int);
conf.relays[i].relay_state = nvalue_int;
setRelayStatePermanently(i, nvalue_int);
saveConfig();
} //if
} //for
}
*/
void initMQTT() {
MQTTLogMessage("initMQTT");
mqttclient.setServer(conf.MQTT_hostName.c_str(), 1883);
// mqttclient.setCallback(callback);
MQTTConnect();
sendUDPMessageAsync("REFRESH");
}
long MQTTlastReconnectAttempt = -300000;
void MQTTProcess() {
// return;
// Serial.printf("processMQTT...\n");
if (!mqttclient.connected()) {
long now = millis();
if (abs((long)(millis() - MQTTlastReconnectAttempt)) < 120000) return;
// Serial.printf("processMQTT... MQTTlastReconnectAttempt[%d][%d]\n",abs((long)(millis() - MQTTlastReconnectAttempt)) ,MQTTlastReconnectAttempt);
MQTTlastReconnectAttempt = now;
MQTTConnect();
}
mqttclient.loop();
}
void MQTTConnect() {
MQTTLogMessage("MQTT connecting");
// Serial.printf(".");
int mqttconnected = mqttclient.connect(conf.hostName.c_str());
if (!mqttconnected) {
return;
} //if (!mqttconnected )
//if (conf.serialLogging==true)Serial.printf("MQTT connected\n");
MQTTLogMessage("Device started");
//MQTTLogMessage(String("conf.rgbled.enable loaded ")+String(conf.rgble.enabled) );
//MQTTLogMessage(String("conf.rgbled.state loaded ")+String(conf.rgbled.state) );
// Once connected, publish an announcement...
mqttclient.subscribe("domoticz/out");
mqttclient.subscribe(runtime.pingtopic.c_str());
if (conf.relays[0].domoticz_device_idx > 0) {
String command1 = String("{\"command\": \"getdeviceinfo\", \"idx\": ") + conf.relays[0].domoticz_device_idx + " }";
MQTTpublish(command1.c_str());
} //if
if (conf.relays[1].domoticz_device_idx > 0) {
String command2 = String("{\"command\": \"getdeviceinfo\", \"idx\": ") + conf.relays[1].domoticz_device_idx + " }";
MQTTpublish(command2.c_str());
} //if
}