/
mqtt_object_leonardo_ethernet.ino
301 lines (266 loc) · 11.4 KB
/
mqtt_object_leonardo_ethernet.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
#include <SPI.h>
#include <UIPEthernet.h>
#include <Vector.h>
#include <PubSubClient.h>
enum DeviceType {presenceDetector,button, rele};
class Device {
public:
byte pin; // номер вывода
byte mode = INPUT; // режим работы
// (используем так как по умолчанию RTTI диактивирован и влечёт большые накладные расходы и нет возможности использовать typeid)
DeviceType type; // ключ для определения типа к которому будем приводить
int state = 0; // Состояние устройства
};
class Button : public Device {
public:
int tickAntiBounce = 0; // Счётчик итераций для реализации анти дребезга кнопки
Button(byte _pin);
};
class Rele : public Device {
public:
Rele(byte _pin);
};
class MQTT_Device {
public:
const char* topic_module; // топик с названием модуля
const char* topic_room; // топик с именем комнаты
const char* topic_device; // топик с названием устройства (кнопка, реле, датчик и.т.д)
Device *device; // ссылка на устройство
MQTT_Device(const char* _topic_module, const char* _topic_room, const char* _topic_device, Button *_device);
MQTT_Device(const char* _topic_module, const char* _topic_room, const char* _topic_device, Rele *_device);
};
Button::Button(byte _pin) {
state = 0;
type = button;
pin = _pin;
mode = INPUT;
}
Rele::Rele(byte _pin) {
state = 0;
type = rele;
pin = _pin;
mode = OUTPUT;
}
MQTT_Device::MQTT_Device(const char* _topic_module, const char* _topic_room, const char* _topic_device, Button *_device)
{
topic_module = _topic_module;
topic_room = _topic_room;
topic_device = _topic_device;
device = _device;
}
MQTT_Device::MQTT_Device(const char* _topic_module, const char* _topic_room, const char* _topic_device, Rele *_device)
{
topic_module = _topic_module;
topic_room = _topic_room;
topic_device = _topic_device;
device = _device;
}
// определяем конфигурацию сети
uint8_t mac [6] = {0x00,0x01,0x02,0x03,0x04,0x05};
byte ip[] = {192, 168, 88, 120}; // IP-адрес
byte myDns[] = {192, 168, 88, 1}; // адрес DNS-сервера
byte gateway[] = {192, 168, 88, 1}; // адрес сетевого шлюза
byte subnet[] = {255, 255, 255, 0}; // маска подсети
EthernetClient ethClient; // объект клиент
PubSubClient client;
const char* mqtt_server = "192.168.88.253";
const char* mqtt_login = "";
const char* mqtt_password = "";
Vector<MQTT_Device> mqtt_list;
const int MaxTickAntiBounce = 1000; // Количесто тиков антидребезга для срабатывания кнопки
long lastMsg = 0;
char msg[16];
void setup() {
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Init device");
mqtt_list.push_back(MQTT_Device("/leo", "/Livingroom", "/button1", reinterpret_cast<Button*>(new Button(2))));
mqtt_list.push_back(MQTT_Device("/leo", "/Livingroom", "/button2", reinterpret_cast<Button*>(new Button(3))));
mqtt_list.push_back(MQTT_Device("/leo", "/Hall", "/button1", reinterpret_cast<Button*>(new Button(4))));
mqtt_list.push_back(MQTT_Device("/leo", "/Bedroom", "/button1", reinterpret_cast<Button*>(new Button(5))));
mqtt_list.push_back(MQTT_Device("/leo", "/Livingroom", "/rele1", reinterpret_cast<Rele*>(new Rele(6))));
mqtt_list.push_back(MQTT_Device("/leo", "/Livingroom", "/rele2", reinterpret_cast<Rele*>(new Rele(12))));
mqtt_list.push_back(MQTT_Device("/leo", "/Hall", "/rele1", reinterpret_cast<Rele*>(new Rele(8))));
mqtt_list.push_back(MQTT_Device("/leo", "/Bedroom", "/rele1", reinterpret_cast<Rele*>(new Rele(9))));
Serial.println(memoryFree());
// pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
for (int i = 0; i < mqtt_list.size(); i++){
pinMode(mqtt_list[i].device->pin, mqtt_list[i].device->mode);
// if (mqtt_list[i].device->type == button) digitalWrite(mqtt_list[i].device->pin,HIGH);
}
setup_ethernet();
ethClient.setTimeout(10000);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
const String catStr(const char* str1, const char* str2) {
char result[50];
snprintf(result, sizeof result, "%s%s", str1, str2);
return String (result);
}
void setup_ethernet() {
Ethernet.begin(mac, ip, myDns, gateway, subnet); // инициализация контроллера
Serial.print("My address:");
Serial.println(Ethernet.localIP()); // выводим IP-адрес контроллера
client.setClient (ethClient);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Ищем топик реле (его будем щёлкать если пришло изменение)
int releNumber = -1;
for (int i = 0; i < mqtt_list.size(); i++){
if (mqtt_list[i].device->type == rele) {
Rele *dev = reinterpret_cast<Rele*>(mqtt_list[i].device);
String dev_name(mqtt_list[i].topic_device);
if (strcmp(topic,(catStr(mqtt_list[i].topic_module,mqtt_list[i].topic_room) + dev_name).c_str())==0) releNumber = i;
}
if (releNumber > -1) break;
}
if (releNumber > -1) {
if ((char)payload[0] == '1') setstate(releNumber,1);
if ((char)payload[0] == '0') setstate(releNumber,0);
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "LeonardoClient-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str(), mqtt_login, mqtt_password)) {
Serial.println("connected");
for (int i = 0; i < mqtt_list.size(); i++) {
// String base = catStr(mqtt_list[i].topic_module,mqtt_list[i].topic_room);
Serial.print("Topic add:");
Serial.println(catStr(catStr(mqtt_list[i].topic_module,mqtt_list[i].topic_room).c_str(),mqtt_list[i].topic_device).c_str());
client.subscribe(catStr(catStr(mqtt_list[i].topic_module,mqtt_list[i].topic_room).c_str(),mqtt_list[i].topic_device).c_str());
}
Serial.println(memoryFree());
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 sec");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// Переменные, создаваемые процессом сборки,
// когда компилируется скетч
extern int __bss_end;
extern void *__brkval;
// Функция, возвращающая количество свободного ОЗУ (RAM)
int memoryFree()
{
int freeValue;
if((int)__brkval == 0)
freeValue = ((int)&freeValue) - ((int)&__bss_end);
else
freeValue = ((int)&freeValue) - ((int)__brkval);
return freeValue;
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Опрашиваем устройства (и публикуем состояния в MQTT брокера)
for (int i = 0; i < mqtt_list.size(); i++) {
switch (mqtt_list[i].device->type) {
case button:
// По состоянию выключателей переключаем реле и за одно передаём их состояние
// Всё это в Action
// (как и раньше только передаётся еще и состояние выключателей)
// можно судить будет на стороне Mojordomo кто щёлкнул реле (реальный выключатель или на стороне Mojerdomo программное переключение произошло)
if (PubButtonState(&mqtt_list[i]) == true) Action(i);
break;
case rele:
// Постоянно публиковать походу не нужно, дальше разберёмся может добавлю предыдущее состояние реле и буду публиковать по изменению значения
// PubReleState(&mqtt_list[i]);
break;
}
}
}
void setstate(int id, int state) {
if (state == 0) {
digitalWrite(mqtt_list[id].device->pin,HIGH);
mqtt_list[id].device->state = 0;
} else {
digitalWrite(mqtt_list[id].device->pin,LOW);
mqtt_list[id].device->state = 1;
}
}
// Переключает состояние устройства на противоположное
int swithState(int id){
if (mqtt_list[id].device->state == 0){
setstate(id,1);
return 1;
} else {
setstate(id,0);
return 0;
}
}
// Некий экшен в качестве ID принемаем номер Device , эта функция всегда специфичная
// Пока не очень красиво всё привязано к номерам , но некий HashMap я пока хз как реализовать
void Action(int id){
byte swith = -1;
switch (id) {
case 0: swith = 4;
break;
case 1: swith = 5;
break;
case 2: swith = 6;
break;
case 3: swith = 7;
break;
}
if (swith != -1) {
swithState(swith);
PubReleState(&mqtt_list[swith]);
}
}
int toStandart(int state) {
if (state == HIGH) return 1; else return 0;
}
// Если состояние Кнопки изменилось (и прошло MaxTickAntiBounce тиков анти дребезга) публикует это дело в MQTT сеть (и возвращает true если менялось положение)
boolean PubButtonState(MQTT_Device *mqtt_dev){
MQTT_Device *mqttdev = reinterpret_cast<MQTT_Device*>(mqtt_dev);
Button *dev = reinterpret_cast<Button*>(mqttdev->device);
int current_rele_state = digitalRead(dev->pin);
if (current_rele_state != dev->state) {
if (dev->tickAntiBounce < MaxTickAntiBounce) {
dev->tickAntiBounce++;
} else {
// String base = catStr(mqtt_dev->topic_module,mqtt_dev->topic_room);
snprintf (msg, 16, "%ld", toStandart(dev->state));
Serial.print("Publish message: ");
Serial.print(catStr(catStr(mqtt_dev->topic_module,mqtt_dev->topic_room).c_str(),mqtt_dev->topic_device).c_str()); Serial.print(" - ");
Serial.println(msg);
// Serial.println(toStandart(dev->state));
dev->state = current_rele_state;
dev->tickAntiBounce = 0;
client.publish(catStr(catStr(mqtt_dev->topic_module,mqtt_dev->topic_room).c_str(),mqtt_dev->topic_device).c_str(), msg);
return true;
}
} else dev->tickAntiBounce = 0;
return false;
}
// Публикуем текущее состояние реле
void PubReleState(MQTT_Device *mqtt_dev){
MQTT_Device *mqttdev = reinterpret_cast<MQTT_Device*>(mqtt_dev);
Rele *dev = reinterpret_cast<Rele*>(mqttdev->device);
// String base = catStr(mqtt_dev->topic_module,mqtt_dev->topic_room);
snprintf (msg, 16, "%ld", toStandart(dev->state));
Serial.print("Publish message: ");
Serial.print(catStr(catStr(mqtt_dev->topic_module,mqtt_dev->topic_room).c_str(),mqtt_dev->topic_device).c_str()); Serial.print(" - ");
Serial.println(msg);
client.publish(catStr(catStr(mqtt_dev->topic_module,mqtt_dev->topic_room).c_str(),mqtt_dev->topic_device).c_str(), msg);
}