Files
IoTManager/src/Mqtt.cpp

285 lines
11 KiB
C++
Raw Normal View History

2020-06-18 23:43:06 +02:00
#include "Global.h"
2020-06-17 23:30:48 +03:00
2020-06-21 03:43:15 +03:00
//
#include <LittleFS.h>
2020-06-20 14:27:58 +03:00
// Errors
int wifi_lost_error = 0;
int mqtt_lost_error = 0;
2020-06-19 22:14:50 +02:00
2020-06-20 14:27:58 +03:00
void callback(char* topic, uint8_t* payload, size_t length);
2020-06-18 23:43:06 +02:00
String stateMQTT();
void sendAllData();
void sendAllWigets();
void sendSTATUS(String topik, String state);
void outcoming_date();
2020-06-17 23:30:48 +03:00
//===============================================ИНИЦИАЛИЗАЦИЯ================================================
void MQTT_init() {
2020-06-20 14:27:58 +03:00
ts.add(
2020-06-21 03:43:15 +03:00
WIFI_MQTT_CONNECTION_CHECK, MQTT_RECONNECT_INTERVAL, [&](void*) {
2020-06-20 14:27:58 +03:00
if (WiFi.status() == WL_CONNECTED) {
Serial.println("[VV] WiFi-ok");
if (client_mqtt.connected()) {
Serial.println("[VV] MQTT-ok");
2020-06-22 03:11:02 +03:00
setLedStatus(LED_OFF);
2020-06-20 14:27:58 +03:00
} else {
MQTT_Connecting();
if (!just_load) mqtt_lost_error++;
}
} else {
Serial.println("[E] Lost WiFi connection");
wifi_lost_error++;
ts.remove(WIFI_MQTT_CONNECTION_CHECK);
2020-06-22 03:11:02 +03:00
startAPMode();
2020-06-20 14:27:58 +03:00
}
},
nullptr, true);
2020-06-17 23:30:48 +03:00
}
void do_mqtt_connection() {
2020-06-20 14:27:58 +03:00
if (mqtt_connection) {
mqtt_connection = false;
client_mqtt.disconnect();
MQTT_Connecting();
}
2020-06-17 23:30:48 +03:00
}
2020-06-19 22:14:50 +02:00
//================================================ОБНОВЛЕНИЕ====================================================
2020-06-20 14:27:58 +03:00
void handleMQTT() {
if (WiFi.status() == WL_CONNECTED) {
if (client_mqtt.connected()) {
client_mqtt.loop();
}
2020-06-17 23:30:48 +03:00
}
}
boolean MQTT_Connecting() {
bool res = false;
2020-06-19 14:50:34 +02:00
String mqtt_server = jsonReadStr(configSetupJson, "mqttServer");
2020-06-17 23:30:48 +03:00
if ((mqtt_server != "")) {
Serial.println("[E] Lost MQTT connection, start reconnecting");
2020-06-22 03:11:02 +03:00
setLedStatus(LED_FAST);
2020-06-19 14:50:34 +02:00
client_mqtt.setServer(mqtt_server.c_str(), jsonReadInt(configSetupJson, "mqttPort"));
2020-06-17 23:30:48 +03:00
if (WiFi.status() == WL_CONNECTED) {
if (!client_mqtt.connected()) {
Serial.println("[V] Connecting to MQTT server commenced");
2020-06-20 22:51:14 +03:00
if (client_mqtt.connect(chipId.c_str(), jsonReadStr(configSetupJson, "mqttUser").c_str(), jsonReadStr(configSetupJson, "mqttPass").c_str())) {
2020-06-17 23:30:48 +03:00
Serial.println("[VV] MQTT connected");
2020-06-22 03:11:02 +03:00
setLedStatus(LED_OFF);
2020-06-17 23:30:48 +03:00
client_mqtt.setCallback(callback);
2020-06-19 14:50:34 +02:00
client_mqtt.subscribe(jsonReadStr(configSetupJson, "mqttPrefix").c_str()); // Для приема получения HELLOW и подтверждения связи
2020-06-20 22:51:14 +03:00
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/+/control").c_str()); // Подписываемся на топики control
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/order").c_str()); // Подписываемся на топики order
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/update").c_str());
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/devc").c_str());
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/devs").c_str());
2020-06-17 23:30:48 +03:00
Serial.println("[V] Callback set, subscribe done");
res = true;
} else {
2020-06-21 03:43:15 +03:00
Serial.println("[E] try again in " + String(MQTT_RECONNECT_INTERVAL / 1000) + " sec");
2020-06-22 03:11:02 +03:00
setLedStatus(LED_FAST);
2020-06-17 23:30:48 +03:00
}
}
}
} else {
Serial.println("[E] No date for MQTT connection");
}
return res;
}
2020-06-19 22:14:50 +02:00
//=====================================================ВХОДЯЩИЕ ДАННЫЕ========================================================
2020-06-20 14:27:58 +03:00
void callback(char* topic, uint8_t* payload, size_t length) {
Serial.print("[MQTT] ");
Serial.print(topic);
String topic_str = String(topic);
String str;
for (size_t i = 0; i < length; i++) {
str += (char)payload[i];
}
Serial.println(" => " + str);
if (str == "HELLO") outcoming_date();
//превращает название топика в команду, а значение в параметр команды
if (topic_str.indexOf("control") > 0) { //IoTmanager/800324-1458415/button-sw2/control 1 //IoTmanager/800324-1458415/button99/control 1
String topic = selectFromMarkerToMarker(topic_str, "/", 3); //button1 //button99
topic = add_set(topic); //buttonSet1 //buttonSet99
String number = selectToMarkerLast(topic, "Set"); //1 //99
topic.replace(number, ""); //buttonSet //buttonSet
String final_line = topic + " " + number + " " + str; //buttonSet 1 1 //buttonSet 99 1
order_loop += final_line + ",";
}
if (topic_str.indexOf("order") > 0) {
str.replace("_", " ");
//Serial.println(str);
order_loop += str + ",";
}
if (topic_str.indexOf("update") > 0) {
if (str == "1") {
upgrade = true;
}
}
if (topic_str.indexOf("devc") > 0) {
writeFile("firmware.c.txt", str);
Device_init();
}
if (topic_str.indexOf("devs") > 0) {
writeFile("firmware.s.txt", str);
Scenario_init();
2020-06-17 23:30:48 +03:00
}
}
//данные которые отправляем при подключении или отбновлении страницы
void outcoming_date() {
2020-06-20 14:27:58 +03:00
sendAllWigets();
sendAllData();
2020-06-17 23:30:48 +03:00
2020-06-21 03:43:15 +03:00
#ifdef LOGGING_ENABLED
2020-06-20 14:27:58 +03:00
choose_log_date_and_send();
2020-06-17 23:30:48 +03:00
#endif
2020-06-20 14:27:58 +03:00
Serial.println("[V] Sending all date to iot manager completed");
2020-06-17 23:30:48 +03:00
}
2020-06-19 22:14:50 +02:00
//======================================CONFIG==================================================
2020-06-17 23:30:48 +03:00
boolean sendMQTT(String end_of_topik, String data) {
2020-06-20 22:51:14 +03:00
String topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/" + end_of_topik;
2020-06-20 14:27:58 +03:00
boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false);
client_mqtt.print(data);
client_mqtt.endPublish();
return send_status;
2020-06-17 23:30:48 +03:00
}
boolean sendCHART(String topik, String data) {
2020-06-20 22:51:14 +03:00
topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/" + topik + "/" + "status";
2020-06-20 14:27:58 +03:00
boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false);
client_mqtt.print(data);
client_mqtt.endPublish();
return send_status;
2020-06-17 23:30:48 +03:00
}
2020-06-19 22:14:50 +02:00
boolean sendCHART_test(String topik, String data) {
2020-06-20 22:51:14 +03:00
topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/" + topik + "/" + "status";
2020-06-20 14:27:58 +03:00
boolean send_status = client_mqtt.publish(topik.c_str(), data.c_str(), false);
return send_status;
2020-06-19 22:14:50 +02:00
}
//======================================STATUS==================================================
2020-06-17 23:30:48 +03:00
void sendSTATUS(String topik, String state) {
2020-06-20 22:51:14 +03:00
topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/" + topik + "/" + "status";
2020-06-20 14:27:58 +03:00
String json_ = "{}";
jsonWriteStr(json_, "status", state);
client_mqtt.publish(topik.c_str(), json_.c_str(), false);
2020-06-17 23:30:48 +03:00
}
2020-06-19 22:14:50 +02:00
//======================================CONTROL==================================================
2020-06-17 23:30:48 +03:00
void sendCONTROL(String id, String topik, String state) {
2020-06-20 14:27:58 +03:00
String all_line = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id + "/" + topik + "/control";
client_mqtt.publish(all_line.c_str(), state.c_str(), false);
2020-06-17 23:30:48 +03:00
}
//=====================================================ОТПРАВЛЯЕМ ВИДЖЕТЫ========================================================
2020-06-21 03:43:15 +03:00
#ifdef LAYOUT_IN_RAM
2020-06-17 23:30:48 +03:00
void sendAllWigets() {
2020-06-20 14:27:58 +03:00
if (all_widgets != "") {
int counter = 0;
String line;
int psn_1 = 0;
int psn_2;
do {
psn_2 = all_widgets.indexOf("\r\n", psn_1); //\r\n
line = all_widgets.substring(psn_1, psn_2);
line.replace("\n", "");
line.replace("\r\n", "");
//jsonWriteStr(line, "id", String(counter));
//jsonWriteStr(line, "pageId", String(counter));
counter++;
sendMQTT("config", line);
Serial.println("[V] " + line);
psn_1 = psn_2 + 1;
} while (psn_2 + 2 < all_widgets.length());
2020-06-20 22:51:14 +03:00
getMemoryLoad("[I] after send all widgets");
2020-06-20 14:27:58 +03:00
}
2020-06-17 23:30:48 +03:00
}
#endif
2020-06-21 03:43:15 +03:00
#ifndef LAYOUT_IN_RAM
2020-06-17 23:30:48 +03:00
void sendAllWigets() {
2020-06-21 03:43:15 +03:00
auto file = seekFile("/layout.txt");
2020-06-20 22:51:14 +03:00
if (!file) {
2020-06-20 14:27:58 +03:00
return;
}
2020-06-20 22:51:14 +03:00
while (file.position() != file.size()) {
2020-06-21 03:43:15 +03:00
String payload = file.readStringUntil('\n');
Serial.println("[V] " + payload);
sendMQTT("config", payload);
2020-06-20 14:27:58 +03:00
}
2020-06-21 03:43:15 +03:00
file.close();
2020-06-17 23:30:48 +03:00
}
#endif
2020-06-21 03:43:15 +03:00
2020-06-17 23:30:48 +03:00
//=====================================================ОТПРАВЛЯЕМ ДАННЫЕ В ВИДЖЕТЫ ПРИ ОБНОВЛЕНИИ СТРАНИЦЫ========================================================
2020-06-20 14:27:58 +03:00
void sendAllData() { //берет строку json и ключи превращает в топики а значения колючей в них посылает
String current_config = configLiveJson; //{"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"}
2020-06-21 03:43:15 +03:00
printMemoryStatus("[I] after send all date");
2020-06-20 14:27:58 +03:00
current_config.replace("{", "");
current_config.replace("}", ""); //"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"
current_config += ","; //"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1",
while (current_config.length() != 0) {
String tmp = selectToMarker(current_config, ",");
String topic = selectToMarker(tmp, ":");
topic.replace("\"", "");
String state = selectToMarkerLast(tmp, ":");
state.replace("\"", "");
if (topic != "name" && topic != "lang" && topic != "ip" && topic.indexOf("_in") < 0) {
sendSTATUS(topic, state);
//Serial.println("-->" + topic + " " + state);
}
current_config = deleteBeforeDelimiter(current_config, ",");
2020-06-17 23:30:48 +03:00
}
}
String stateMQTT() {
int state = client_mqtt.state();
switch (state) {
case -4:
return "the server didn't respond within the keepalive time";
break;
case -3:
return "the network connection was broken";
break;
case -2:
return "the network connection failed";
break;
case -1:
return "the client is disconnected cleanly";
break;
case 0:
return "the client is connected";
break;
case 1:
return "the server doesn't support the requested version of MQTT";
break;
case 2:
return "the server rejected the client identifier";
break;
case 3:
return "the server was unable to accept the connection";
break;
case 4:
return "the username/password were rejected";
break;
case 5:
return "the client was not authorized to connect";
break;
default:
return "unspecified";
break;
}
}