forked from 1technophile/OpenMQTTGateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpenMQTTGateway.ino
465 lines (422 loc) · 13.1 KB
/
OpenMQTTGateway.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
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*
OpenMQTTGateway - ESP8266 or Arduino program for home automation
Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker
Send and receiving command by MQTT
This program enables to:
- receive MQTT data from a topic and send RF 433Mhz signal corresponding to the received MQTT data
- publish MQTT data to a different topic related to received 433Mhz signal
- receive MQTT data from a topic and send IR signal corresponding to the received MQTT data
- publish MQTT data to a different topic related to received IR signal
- publish MQTT data to a different topic related to BLE devices rssi signal
Copyright: (c)Florian ROBERT
Contributors:
- 1technophile
- crankyoldgit
- glasruit
- HannesDi
- Landrash
- larsenglund
- ChiefZ
- PatteWi
- jumpalottahigh
- zerinrc
- philfifi
- Spudtater
- prahjister
- rickybrent
- petricaM
- ekim from Home assistant forum
- ronvl from Home assistant forum
This file is part of OpenMQTTGateway.
OpenMQTTGateway is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenMQTTGateway is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "User_config.h"
#include <PubSubClient.h>
// array to store previous received RFs, IRs codes and their timestamps
#ifdef ESP8266
#define array_size 12
unsigned long ReceivedSignal[array_size][2] ={{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}};
#else
#define array_size 4
unsigned long ReceivedSignal[array_size][2] ={{0,0},{0,0},{0,0},{0,0}};
#endif
/*------------------------------------------------------------------------*/
//adding this to bypass the problem of the arduino builder issue 50
void callback(char*topic, byte* payload,unsigned int length);
#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
WiFiClient eClient;
#else
#include <Ethernet.h>
EthernetClient eClient;
#endif
// client parameters
PubSubClient client(mqtt_server, mqtt_port, callback, eClient);
//MQTT last attemps reconnection date
unsigned long lastReconnectAttempt = 0;
//timers for LED indicators
unsigned long timer_led_receive = 0;
unsigned long timer_led_send = 0;
unsigned long timer_led_error = 0;
boolean reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
trc(F("MQTT connection...")); //F function enable to decrease sram usage
#ifdef mqtt_user
if (client.connect(Gateway_Name, mqtt_user, mqtt_password, will_Topic, will_QoS, will_Retain, will_Message)) { // if an mqtt user is defined we connect to the broker with authentication
#else
if (client.connect(Gateway_Name, will_Topic, will_QoS, will_Retain, will_Message)) {
#endif
trc(F("Connected to broker"));
// Once connected, publish an announcement...
client.publish(will_Topic,Gateway_AnnouncementMsg,will_Retain);
// publish version
client.publish(version_Topic,OMG_VERSION,will_Retain);
//Subscribing to topic
if (client.subscribe(subjectMQTTtoX)) {
#ifdef ZgatewayRF
client.subscribe(subjectMultiGTWRF);
#endif
#ifdef ZgatewayIR
client.subscribe(subjectMultiGTWIR);
#endif
trc(F("Subscription OK to the subjects"));
}
} else {
trc(F("failed, rc="));
trc(String(client.state()));
trc(F("try again in 5s"));
// Wait 5 seconds before retrying
delay(5000);
}
}
return client.connected();
}
// Callback function, when the gateway receive an MQTT value on the topics subscribed this function is called
void callback(char* topic, byte* payload, unsigned int length) {
// In order to republish this payload, a copy must be made
// as the orignal payload buffer will be overwritten whilst
// constructing the PUBLISH packet.
trc(F("Hey I got a callback "));
// Allocate the correct amount of memory for the payload copy
byte* p = (byte*)malloc(length + 1);
// Copy the payload to the new buffer
memcpy(p,payload,length);
// Conversion to a printable string
p[length] = '\0';
//launch the function to treat received data
receivingMQTT(topic,(char *) p);
// Free the memory
free(p);
}
void setup()
{
#ifdef ESP8266
//Launch serial for debugging purposes
#ifdef ZgatewaySRFB
Serial.begin(SERIAL_BAUD); // in the case of sonoff RF Bridge the link to the RF emitter/receiver is made by serial and need TX/RX
#else
Serial.begin(SERIAL_BAUD, SERIAL_8N1, SERIAL_TX_ONLY);
#endif
//Begining wifi connection in case of ESP8266
setup_wifi();
// Port defaults to 8266
ArduinoOTA.setPort(ota_port);
// Hostname defaults to esp8266-[ChipID]
ArduinoOTA.setHostname(ota_hostname);
// No authentication by default
ArduinoOTA.setPassword(ota_password);
ArduinoOTA.onStart([]() {
trc(F("Start"));
});
ArduinoOTA.onEnd([]() {
trc(F("\nEnd"));
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) trc(F("Auth Failed"));
else if (error == OTA_BEGIN_ERROR) trc(F("Begin Failed"));
else if (error == OTA_CONNECT_ERROR) trc(F("Connect Failed"));
else if (error == OTA_RECEIVE_ERROR) trc(F("Receive Failed"));
else if (error == OTA_END_ERROR) trc(F("End Failed"));
});
ArduinoOTA.begin();
#else
//Launch serial for debugging purposes
Serial.begin(SERIAL_BAUD);
//Begining ethernet connection in case of Arduino + W5100
setup_ethernet();
//setup LED status, turn all ON for short amount then leave only the RED LED ON
pinMode(led_receive, OUTPUT);
pinMode(led_send, OUTPUT);
pinMode(led_error, OUTPUT);
digitalWrite(led_receive, LOW);
digitalWrite(led_send, LOW);
digitalWrite(led_error, LOW);
delay(500);
digitalWrite(led_receive, HIGH);
digitalWrite(led_send, HIGH);
#endif
delay(1500);
lastReconnectAttempt = 0;
#ifdef ZsensorBME280
setupZsensorBME280();
#endif
#ifdef ZsensorBH1750
setupZsensorBH1750();
#endif
#ifdef ZgatewayIR
setupIR();
#endif
#ifdef ZgatewayRF
setupRF();
#endif
#ifdef ZgatewayRF2
setupRF2();
#endif
#ifdef ZgatewayBT
setupBT();
#endif
#ifdef ZgatewayRFM69
setupRFM69();
#endif
#ifdef ZsensorINA226
setupINA226();
#endif
#ifdef ZsensorHCSR501
setupHCSR501();
#endif
}
#ifdef ESP8266
void setup_wifi() {
delay(10);
WiFi.mode(WIFI_STA);
// We start by connecting to a WiFi network
trc(F("Connecting to "));
trc(wifi_ssid);
IPAddress ip_adress(ip);
IPAddress gateway_adress(gateway);
IPAddress subnet_adress(subnet);
IPAddress dns_adress(Dns);
WiFi.begin(wifi_ssid, wifi_password);
//WiFi.config(ip_adress,gateway_adress,subnet_adress); //Uncomment this line if you want to use advanced network config
trc(F("OpenMQTTGateway mac: "));
Serial.println(WiFi.macAddress());
while (WiFi.status() != WL_CONNECTED) {
delay(500);
trc(F("."));
}
trc(F("OpenMQTTGateway ip: "));
Serial.println(WiFi.localIP());
trc(F("WiFi ok"));
}
#else
void setup_ethernet() {
Ethernet.begin(mac, ip); //Comment and uncomment the following line if you want to use advanced network config
//Ethernet.begin(mac, ip, Dns, gateway, subnet);
trc(F("OpenMQTTGateway ip: "));
Serial.println(Ethernet.localIP());
trc(F("Ethernet ok"));
}
#endif
void loop()
{
unsigned long now = millis();
//MQTT client connexion management
if (!client.connected()) { // not connected
//RED ON
digitalWrite(led_error, LOW);
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
} else { //connected
// MQTT loop
//RED OFF
if (now - timer_led_receive > 300) {
timer_led_receive = now;
digitalWrite(led_receive, HIGH);
}
digitalWrite(led_error, HIGH);
client.loop();
#ifdef ESP8266
ArduinoOTA.handle();
#endif
#ifdef ZsensorBME280
MeasureTempHumAndPressure(); //Addon to measure Temperature, Humidity, Pressure and Altitude with a Bosch BME280
#endif
#ifdef ZsensorBH1750
MeasureLightIntensity(); //Addon to measure Light Intensity with a BH1750
#endif
#ifdef ZsensorDHT
MeasureTempAndHum(); //Addon to measure the temperature with a DHT
#endif
#ifdef ZsensorINA226
MeasureINA226(); //Addon to measure the temperature with a DHT
#endif
#ifdef ZsensorHCSR501
MeasureHCSR501();
#endif
#ifdef ZsensorADC
MeasureADC(); //Addon to measure the analog value of analog pin
#endif
// Receive loop, if data received by RF433 or IR send it by MQTT
#ifdef ZgatewayRF
if(RFtoMQTT()){
trc(F("RFtoMQTT OK"));
//GREEN ON
digitalWrite(led_receive, LOW);
timer_led_receive = millis();
}
#endif
#ifdef ZgatewayRF2
if(RF2toMQTT()){
trc(F("RF2toMQTT OK"));
digitalWrite(led_receive, LOW);
timer_led_receive = millis();
}
#endif
#ifdef ZgatewaySRFB
if(SRFBtoMQTT())
trc(F("SRFBtoMQTT OK"));
#endif
#ifdef ZgatewayIR
if(IRtoMQTT()) {
trc(F("IRtoMQTT OK"));
digitalWrite(led_receive, LOW);
timer_led_receive = millis();
delay(100);
}
#endif
#ifdef ZgatewayBT
if(BTtoMQTT())
trc(F("BTtoMQTT OK"));
#endif
#ifdef ZgatewayRFM69
if(RFM69toMQTT())
trc(F("RFM69toMQTT OK"));
#endif
}
}
void storeValue(long MQTTvalue){
unsigned long now = millis();
// find oldest value of the buffer
int o = getMin();
trc(F("Min ind: "));
trc(String(o));
// replace it by the new one
ReceivedSignal[o][0] = MQTTvalue;
ReceivedSignal[o][1] = now;
trc(F("store code :"));
trc(String(ReceivedSignal[o][0])+"/"+String(ReceivedSignal[o][1]));
trc(F("Col: val/timestamp"));
for (int i = 0; i < array_size; i++)
{
trc(String(i) + ":" + String(ReceivedSignal[i][0])+"/"+String(ReceivedSignal[i][1]));
}
}
int getMin(){
int minimum = ReceivedSignal[0][1];
int minindex=0;
for (int i = 0; i < array_size; i++)
{
if (ReceivedSignal[i][1] < minimum) {
minimum = ReceivedSignal[i][1];
minindex = i;
}
}
return minindex;
}
boolean isAduplicate(long value){
trc(F("isAduplicate"));
// check if the value has been already sent during the last time_avoid_duplicate
for (int i = 0; i < array_size;i++){
if (ReceivedSignal[i][0] == value){
unsigned long now = millis();
if (now - ReceivedSignal[i][1] < time_avoid_duplicate){ // change
trc(F("--don't pub. duplicate--"));
return true;
}
}
}
return false;
}
void receivingMQTT(char * topicOri, char * datacallback) {
if (strstr(topicOri, subjectMultiGTWKey) != NULL) // storing received value so as to avoid publishing this value if it has been already sent by this or another OpenMQTTGateway
{
trc(F("Storing signal"));
unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295
storeValue(data);
trc(F("Data stored"));
}
//YELLOW ON
digitalWrite(led_send, LOW);
#ifdef ZgatewayRF
MQTTtoRF(topicOri, datacallback);
#endif
#ifdef ZgatewayRF2
MQTTtoRF2(topicOri, datacallback);
#endif
#ifdef ZgatewaySRFB
MQTTtoSRFB(topicOri, datacallback);
#endif
#ifdef ZgatewayIR
MQTTtoIR(topicOri, datacallback);
#endif
#ifdef ZgatewayRFM69
MQTTtoRFM69(topicOri, datacallback);
#endif
//YELLOW OFF
digitalWrite(led_send, HIGH);
}
void extract_char(char * token_char, char * subset, int start ,int l, boolean reverse, boolean isNumber){
char tmp_subset[l+1];
memcpy( tmp_subset, &token_char[start], l );
tmp_subset[l] = '\0';
if (isNumber){
char tmp_subset2[l+1];
if (reverse) revert_hex_data(tmp_subset, tmp_subset2, l+1);
else strncpy( tmp_subset2, tmp_subset , l+1);
long long_value = strtoul(tmp_subset2, NULL, 16);
sprintf(tmp_subset2, "%d", long_value);
strncpy( subset, tmp_subset2 , l+1);
}else{
if (reverse) revert_hex_data(tmp_subset, subset, l+1);
else strncpy( subset, tmp_subset , l+1);
}
}
void revert_hex_data(char * in, char * out, int l){
//reverting array 2 by 2 to get the data in good order
int i = l-2 , j = 0;
while ( i != -2 ) {
if (i%2 == 0) out[j] = in[i+1];
else out[j] = in[i-1];
j++;
i--;
}
out[l-1] = '\0';
}
//trace
void trc(String msg){
if (TRACE) {
Serial.println(msg);
}
}