Files
IoTManager/mqtt.ino

343 lines
14 KiB
Arduino
Raw Normal View History

2019-12-24 11:53:26 +03:00
//===============================================ИНИЦИАЛИЗАЦИЯ================================================
void MQTT_init() {
2020-03-22 01:50:31 +01:00
ts.add(WIFI_MQTT_CONNECTION_CHECK, wifi_mqtt_reconnecting, [&](void*) {
up_time();
if (WiFi.status() == WL_CONNECTED) {
2020-05-02 12:20:30 +02:00
Serial.println("[VV] WiFi-ok");
if (client_mqtt.connected()) {
Serial.println("[VV] MQTT-ok");
2020-03-22 01:50:31 +01: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);
StartAPMode();
}
}, nullptr, true);
2019-12-24 11:53:26 +03:00
2020-03-22 01:50:31 +01:00
server.on("/mqttSave", HTTP_GET, [](AsyncWebServerRequest * request) {
2019-12-24 11:53:26 +03:00
if (request->hasArg("mqttServer")) {
jsonWriteStr(configSetup, "mqttServer", request->getParam("mqttServer")->value());
2019-12-24 11:53:26 +03:00
}
if (request->hasArg("mqttPort")) {
2020-02-22 03:34:44 +03:00
int port = (request->getParam("mqttPort")->value()).toInt();
jsonWriteInt(configSetup, "mqttPort", port);
2019-12-24 11:53:26 +03:00
}
2020-03-21 18:14:38 +01:00
if (request->hasArg("mqttPrefix")) {
jsonWriteStr(configSetup, "mqttPrefix", request->getParam("mqttPrefix")->value());
2020-03-21 18:14:38 +01:00
}
2019-12-24 11:53:26 +03:00
if (request->hasArg("mqttUser")) {
jsonWriteStr(configSetup, "mqttUser", request->getParam("mqttUser")->value());
2019-12-24 11:53:26 +03:00
}
if (request->hasArg("mqttPass")) {
jsonWriteStr(configSetup, "mqttPass", request->getParam("mqttPass")->value());
2019-12-24 11:53:26 +03:00
}
saveConfig();
2020-04-05 01:52:02 +02:00
mqtt_connection = true;
2020-03-24 19:01:11 +01:00
2020-03-22 01:50:31 +01:00
request->send(200, "text/text", "ok");
});
2019-12-24 11:53:26 +03:00
2020-03-22 01:50:31 +01:00
server.on("/mqttCheck", HTTP_GET, [](AsyncWebServerRequest * request) {
2019-12-24 11:53:26 +03:00
String tmp = "{}";
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>" + stateMQTT());
jsonWriteStr(tmp, "class", "pop-up");
2020-03-18 09:57:46 +01:00
request->send(200, "text/text", tmp);
2019-12-24 11:53:26 +03:00
});
2020-04-05 01:52:02 +02:00
2020-05-02 12:20:30 +02:00
2020-04-05 01:52:02 +02:00
}
void do_mqtt_send_settings_to_udp() {
if (mqtt_send_settings_to_udp) {
mqtt_send_settings_to_udp = false;
send_mqtt_to_udp();
}
2020-03-22 01:50:31 +01:00
}
2019-12-24 11:53:26 +03:00
2020-04-05 01:52:02 +02:00
void do_mqtt_connection() {
if (mqtt_connection) {
mqtt_connection = false;
2020-05-02 12:20:30 +02:00
client_mqtt.disconnect();
2020-03-22 01:50:31 +01:00
MQTT_Connecting();
}
2019-12-24 11:53:26 +03:00
}
//================================================ОБНОВЛЕНИЕ====================================================
void handleMQTT() {
if (WiFi.status() == WL_CONNECTED) {
2020-05-02 12:20:30 +02:00
if (client_mqtt.connected()) {
client_mqtt.loop();
2019-12-24 11:53:26 +03:00
}
}
}
//===============================================ПОДКЛЮЧЕНИЕ========================================================
2020-02-22 03:34:44 +03:00
boolean MQTT_Connecting() {
2019-12-24 11:53:26 +03:00
String mqtt_server = jsonRead(configSetup, "mqttServer");
if ((mqtt_server != "")) {
2020-03-22 01:50:31 +01:00
Serial.println("[E] Lost MQTT connection, start reconnecting");
2019-12-24 11:53:26 +03:00
//ssl//espClient.setCACert(local_root_ca1);
2020-05-02 12:20:30 +02:00
client_mqtt.setServer(mqtt_server.c_str(), jsonReadtoInt(configSetup, "mqttPort"));
2019-12-24 11:53:26 +03:00
if (WiFi.status() == WL_CONNECTED) {
2020-05-02 12:20:30 +02:00
if (!client_mqtt.connected()) {
2019-12-24 11:53:26 +03:00
Serial.println("[V] Connecting to MQTT server commenced");
2020-05-02 12:20:30 +02:00
if (client_mqtt.connect(chipID.c_str(), jsonRead(configSetup, "mqttUser").c_str(), jsonRead(configSetup, "mqttPass").c_str())) {
Serial.println("[VV] MQTT connected");
client_mqtt.setCallback(callback);
client_mqtt.subscribe(jsonRead(configSetup, "mqttPrefix").c_str()); // Для приема получения HELLOW и подтверждения связи
client_mqtt.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/+/control").c_str()); // Подписываемся на топики control
client_mqtt.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/order").c_str()); // Подписываемся на топики order
2019-12-24 11:53:26 +03:00
Serial.println("[V] Callback set, subscribe done");
2020-02-22 03:34:44 +03:00
return true;
2019-12-24 11:53:26 +03:00
} else {
Serial.println("[E] try again in " + String(wifi_mqtt_reconnecting / 1000) + " sec");
2020-02-22 03:34:44 +03:00
return false;
2019-12-24 11:53:26 +03:00
}
}
}
} else {
Serial.println("[E] No date for MQTT connection");
2020-02-22 03:34:44 +03:00
return false;
2019-12-24 11:53:26 +03:00
}
}
//=====================================================ВХОДЯЩИЕ ДАННЫЕ========================================================
2020-04-05 01:52:02 +02:00
void callback(char* topic, byte * payload, unsigned int length) {
2019-12-24 11:53:26 +03:00
Serial.print("[MQTT] ");
Serial.print(topic);
String topic_str = String(topic);
String str;
for (int i = 0; i < length; i++) {
str += (char)payload[i];
}
Serial.println(" => " + str);
2020-05-02 12:20:30 +02:00
if (str == "HELLO") outcoming_date();
//превращает название топика в команду, а значение в параметр команды
if (topic_str.indexOf("control") > 0) { //IoTmanager/800324-1458415/button1/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
2019-12-24 11:53:26 +03:00
order_loop += final_line + ",";
}
2020-05-02 12:20:30 +02:00
2019-12-24 11:53:26 +03:00
if (topic_str.indexOf("order") > 0) {
str.replace("_", " ");
//Serial.println(str);
order_loop += str + ",";
}
}
//данные которые отправляем при подключении или отбновлении страницы
void outcoming_date() {
sendAllWigets();
sendAllData();
choose_log_date_and_send();
2019-12-24 11:53:26 +03:00
Serial.println("[V] Sending all date to iot manager completed");
}
2019-12-24 11:53:26 +03:00
//======================================CONFIG==================================================
boolean sendMQTT(String end_of_topik, String data) {
2020-03-21 18:14:38 +01:00
String topik = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + end_of_topik;
2020-05-02 12:20:30 +02:00
boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false);
client_mqtt.print(data);
client_mqtt.endPublish();
2019-12-24 11:53:26 +03:00
return send_status;
}
2020-03-24 19:01:11 +01:00
boolean sendCHART(String topik, String data) {
topik = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
2020-05-02 12:20:30 +02:00
boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false);
client_mqtt.print(data);
client_mqtt.endPublish();
2020-03-24 19:01:11 +01:00
return send_status;
}
2020-03-30 01:45:42 +02:00
boolean sendCHART_test(String topik, String data) {
topik = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
2020-05-02 12:20:30 +02:00
boolean send_status = client_mqtt.publish (topik.c_str(), data.c_str(), false);
2020-03-30 01:45:42 +02:00
return send_status;
}
2019-12-24 11:53:26 +03:00
//======================================STATUS==================================================
void sendSTATUS(String topik, String state) {
2020-03-21 18:14:38 +01:00
topik = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
2019-12-24 11:53:26 +03:00
String json_ = "{}";
jsonWriteStr(json_, "status", state);
2020-05-02 12:20:30 +02:00
int send_status = client_mqtt.publish (topik.c_str(), json_.c_str(), false);
2019-12-24 11:53:26 +03:00
}
//======================================CONTROL==================================================
void sendCONTROL(String id, String topik, String state) {
2020-03-21 18:14:38 +01:00
String all_line = jsonRead(configSetup, "mqttPrefix") + "/" + id + "/" + topik + "/control";
2020-05-02 12:20:30 +02:00
int send_status = client_mqtt.publish (all_line.c_str(), state.c_str(), false);
2019-12-24 11:53:26 +03:00
}
//=====================================================ОТПРАВЛЯЕМ ВИДЖЕТЫ========================================================
#ifdef layout_in_ram
void sendAllWigets() {
2020-03-24 19:01:11 +01:00
if (all_widgets != "") {
2019-12-24 11:53:26 +03:00
int counter = 0;
String line;
int psn_1 = 0;
int psn_2;
do {
psn_2 = all_widgets.indexOf("\r\n", psn_1); //\r\n
2020-03-24 19:01:11 +01:00
line = all_widgets.substring(psn_1, psn_2);
2020-02-08 02:45:35 +03:00
line.replace("\n", "");
2020-01-12 00:35:15 +03:00
line.replace("\r\n", "");
//jsonWriteStr(line, "id", String(counter));
//jsonWriteStr(line, "pageId", String(counter));
2019-12-24 11:53:26 +03:00
counter++;
2020-02-22 03:34:44 +03:00
sendMQTT("config", line);
2019-12-24 11:53:26 +03:00
Serial.println("[V] " + line);
psn_1 = psn_2 + 1;
2020-03-24 19:01:11 +01:00
} while (psn_2 + 2 < all_widgets.length());
getMemoryLoad("[i] after send all widgets");
2019-12-24 11:53:26 +03:00
}
}
#endif
2020-05-02 12:20:30 +02:00
#ifndef layout_in_ram
void sendAllWigets() {
File configFile = SPIFFS.open("/layout.txt", "r");
if (!configFile) {
return;
}
configFile.seek(0, SeekSet); //поставим курсор в начало файла
while (configFile.position() != configFile.size()) {
String widget_to_send = configFile.readStringUntil('\r\n');
Serial.println("[V] " + widget_to_send);
sendMQTT("config", widget_to_send);
}
}
2020-05-02 12:20:30 +02:00
#endif
2019-12-24 11:53:26 +03:00
//=====================================================ОТПРАВЛЯЕМ ДАННЫЕ В ВИДЖЕТЫ ПРИ ОБНОВЛЕНИИ СТРАНИЦЫ========================================================
void sendAllData() { //берет строку json и ключи превращает в топики а значения колючей в них посылает
2020-04-07 18:06:12 +02:00
String current_config = configJson; //{"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"}
2019-12-24 11:53:26 +03:00
getMemoryLoad("[i] after send all date");
current_config.replace("{", "");
2020-04-07 18:06:12 +02:00
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",
2019-12-24 11:53:26 +03:00
while (current_config.length() != 0) {
String tmp = selectToMarker (current_config, ",");
2020-02-22 03:34:44 +03:00
String topic = selectToMarker (tmp, ":");
2020-02-13 21:18:51 +03:00
topic.replace("\"", "");
String state = selectToMarkerLast (tmp, ":");
2019-12-24 11:53:26 +03:00
state.replace("\"", "");
2020-04-05 01:52:02 +02:00
if (topic != "name" && topic != "lang" && topic != "ip" && topic.indexOf("_in") < 0) {
2019-12-24 11:53:26 +03:00
sendSTATUS(topic, state);
//Serial.println("-->" + topic + " " + state);
}
current_config = deleteBeforeDelimiter(current_config, ",");
}
}
String stateMQTT() {
2020-02-22 03:34:44 +03:00
2020-05-02 12:20:30 +02:00
int state = client_mqtt.state();
2019-12-24 11:53:26 +03:00
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;
}
}
/*void scenario_devices_topiks_subscribe() {
//SCENARIO ANALOG > 5 800324-1458415 rel1 0
if (jsonRead(configSetup, "scenario") == "1") {
2020-03-30 01:45:42 +02:00
//String all_text = readFile("firmware.s.txt", 1024) + "\r\n";
2019-12-24 11:53:26 +03:00
String all_text = scenario + "\r\n";
all_text.replace("\r\n", "\n");
all_text.replace("\r", "\n");
while (all_text.length() != 0) {
String line_ = selectToMarker (all_text, "\n");
String id = selectFromMarkerToMarker(line_, " ", 4);
if (id != "not found") {
2020-05-02 12:20:30 +02:00
client_mqtt.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + id + "/+/status").c_str(), 0);
2019-12-24 11:53:26 +03:00
Serial.println("subscribed to device, id: " + id);
}
all_text = deleteBeforeDelimiter(all_text, "\n");
}
}
}
*/
/*void scenario_devices_test_msg_send() {
if (jsonRead(configSetup, "scenario") == "1") {
String all_text = scenario + "\r\n";
all_text.replace("\r\n", "\n");
all_text.replace("\r", "\n");
while (all_text.length() != 0) {
String line_ = selectToMarker (all_text, "\n");
String id = selectFromMarkerToMarker(line_, " ", 4);
if (id != "not found") {
//Serial.println();
2020-05-02 12:20:30 +02:00
Serial.println(client_mqtt.publish ((jsonRead(configSetup, "mqttPrefix") + "/" + id).c_str(), "CHECK", true));
2019-12-24 11:53:26 +03:00
}
all_text = deleteBeforeDelimiter(all_text, "\n");
}
}
}*/
/*
//-----------------------------------------------------------------------------------------------------------------------------------------------
//jsonWriteStr(tmp, "status", "1");
2019-12-24 11:53:26 +03:00
2020-04-07 18:06:12 +02:00
String current_config = configJson; //{"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"}
2019-12-24 11:53:26 +03:00
current_config.replace("{", "");
2020-04-07 18:06:12 +02:00
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",
2019-12-24 11:53:26 +03:00
while (current_config.length() != 0) {
String tmp = selectToMarker (current_config, ","); //"rel1":"1"
String topic = selectToMarker (tmp, ":"); //"rel1"
topic.replace("\"", ""); //rel1
Serial.println(topic);
String state = selectToMarkerLast (tmp, ":"); //"1"
state.replace("\"", ""); //1
2020-03-24 19:01:11 +01:00
//if (widget.lastIndexOf(topic) > 0) {
jsonWriteStr(tmp, "status", state);
2019-12-24 11:53:26 +03:00
//}
current_config = deleteBeforeDelimiter(current_config, ",");
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
*/