DebugTrace, Nextion, BrokerMQTT

This commit is contained in:
Mit4el
2024-09-20 11:07:08 +03:00
parent d2a55af97e
commit 3919e5a0ab
12 changed files with 1019 additions and 445 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,17 @@
/**
* @file NexUpload.h
* The definition of class NexUpload.
*
*
* The definition of class NexUpload.
*
* 1 - Removed all the Arduino code and replaced it by ESP-IDF
* 2 - Removed hard-coded UART configuration, see ESPNexUpload constructor
* 3 - Removed statusMessage and the function _printInfoLine
* 4 - Removed call-back functionality
* 5 - Removed one out of two upload functions
* 6 - BugFix in upload function
* @author Machiel Mastenbroek (machiel.mastenbroek@gmail.com)
* @date 2022/08/14
* @version 0.6.0
*
* 1 - BugFix when display baudrate is diffrent from initial ESP baudrate
* 2 - Improved debug information
* 3 - Make delay commands dependent on the baudrate
@@ -10,12 +19,12 @@
* @date 2019/11/04
* @version 0.5.5
*
* Stability improvement, Nextion display doesnt freeze after the seconds 4096 trance of firmware bytes.
* Now the firmware upload process is stabled without the need of a hard Display power off-on intervention.
* Undocumented features (not mentioned in nextion-hmi-upload-protocol-v1-1 specification) are added.
* This implementation is based in on a reverse engineering with a UART logic analyser between
* Stability improvement, Nextion display doesnt freeze after the seconds 4096 trance of firmware bytes.
* Now the firmware upload process is stabled without the need of a hard Display power off-on intervention.
* Undocumented features (not mentioned in nextion-hmi-upload-protocol-v1-1 specification) are added.
* This implementation is based in on a reverse engineering with a UART logic analyser between
* the Nextion editor v0.58 and a NX4024T032_011R Display.
*
*
* @author Machiel Mastenbroek (machiel.mastenbroek@gmail.com)
* @date 2019/10/24
* @version 0.5.0
@@ -24,7 +33,7 @@
* @author Onno Dirkzwager (onno.dirkzwager@gmail.com)
* @date 2018/12/26
* @version 0.3.0
*
*
* Modified to work with ESP8266 and SoftwareSerial
* @author Ville Vilpas (psoden@gmail.com)
* @date 2018/2/3
@@ -33,44 +42,46 @@
* Original version (a part of https://github.com/itead/ITEADLIB_Arduino_Nextion)
* @author Chen Zengpeng (email:<zengpeng.chen@itead.cc>)
* @date 2016/3/29
* @copyright
* @copyright
* Copyright (C) 2014-2015 ITEAD Intelligent Systems Co., Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* This program 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, version 3.
*
* This program 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
* This program 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
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __ESPNEXUPLOAD_H__
#define __ESPNEXUPLOAD_H__
#include <functional>
//#include <iostream>
#include <string.h> /* printf, scanf, NULL */
//#include <inttypes.h>
#include "esp_log.h"
//#include "freertos/FreeRTOS.h"
//#include "freertos/task.h"
//#include "driver/gpio.h"
#include "driver/uart.h"
//#include "hal/uart_types.h"
#include <Arduino.h>
#include <StreamString.h>
#ifdef ESP8266
#include <SoftwareSerial.h>
#else
#include <HardwareSerial.h>
#include <SoftwareSerial.h>
#endif
#define CONFIG_NEX_UART_RECV_BUFFER_SIZE 256
/**
* @addtogroup CoreAPI
* @{
* @addtogroup CoreAPI
* @{
*/
// callback template definition
typedef std::function<void(void)> THandlerFunction;
/**
*
* Provides the API for nextion to upload the ftf file.
@@ -78,81 +89,68 @@ typedef std::function<void(void)> THandlerFunction;
class ESPNexUpload
{
public: /* methods */
// callback template definition
typedef std::function<void(void)> THandlerFunction;
/**
* Constructor.
*
* @param uint32_t upload_baudrate - set upload baudrate.
* Constructor.
*
*/
ESPNexUpload(uint32_t upload_baudrate, int line, int rx, int tx);
ESPNexUpload(uart_port_t uart_num, uint32_t baud_rate, gpio_num_t tx_io_num, gpio_num_t rx_io_num);
/**
* destructor.
*
* destructor.
*
*/
~ESPNexUpload() {}
~ESPNexUpload(){}
/**
* Connect to Nextion over serial
*
* @return true or false.
*/
bool connect();
/**
* prepare upload. Set file size & Connect to Nextion over serial
*
* @return true if success, false for failure.
*/
bool prepareUpload(uint32_t file_size);
bool prepareUpload(uint32_t file_size, bool prot);
/**
* set Update Progress Callback. (What to do during update progress)
*
* @return none
*/
void setUpdateProgressCallback(THandlerFunction value);
/**
* start update tft file to nextion.
*
* start update tft file to nextion.
*
* @param const uint8_t *file_buf
* @param size_t buf_size
* @return true if success, false for failure.
*/
bool upload(const uint8_t *file_buf, size_t buf_size);
/**
* start update tft file to nextion.
*
* @param Stream &myFile
* @return true if success, false for failure.
*/
bool upload(Stream &myFile);
/**
* Send reset command to Nextion over serial
*
* @return none.
*/
void softReset(void);
void softReset(void);
/**
* Send reset, end serial, reset _sent_packets & update status message
*
* @return none.
*/
void end(void);
public: /* data */
String statusMessage = "";
void end(void);
private: /* methods */
/*
* get communicate baudrate.
* Semaphore construction to prevent double UART actions
*
*/
void uart_mutex_lock(void) {do {} while (xSemaphoreTake(_upload_uart_lock, portMAX_DELAY) != pdPASS);};
void uart_mutex_unlock(void) {xSemaphoreGive(_upload_uart_lock);};
/*
* get communicate baudrate.
*
* @return communicate baudrate.
*
*/
@@ -162,127 +160,167 @@ private: /* methods */
* search communicate baudrate.
*
* @param baudrate - communicate baudrate.
*
* @return true if success, false for failure.
*
* @return true if success, false for failure.
*/
bool _searchBaudrate(uint32_t baudrate);
bool _searchBaudrate(int baudrate);
/*
* set download baudrate.
*
* @param baudrate - set download baudrate.
*
* @return true if success, false for failure.
*
* @return true if success, false for failure.
*/
bool _setPrepareForFirmwareUpdate(uint32_t upload_baudrate);
/*
* set Nextion running mode.
*
* Undocumented feature of the Nextion protocol.
* It's used by the 'upload to Nextion device' feature of the Nextion Editor V0.58
*
* The nextion display doesn't send any response
*
* Undocumented feature of the Nextion protocol.
* It's used by the 'upload to Nextion device' feature of the Nextion Editor V0.58
*
* The nextion display doesn't send any response
*
*/
void _setRunningMode(void);
/*
* Test UART nextion connection availability
*
* @param input - echo string,
*
* @return true when the 'echo string' that is send is equal to the received string
*
* This test is used by the 'upload to Nextion device' feature of the Nextion Editor V0.58
* Test UART nextion connection availability
*
* @param input - echo string,
*
* @return true when the 'echo string' that is send is equal to the received string
*
* This test is used by the 'upload to Nextion device' feature of the Nextion Editor V0.58
*
*/
bool _echoTest(String input);
bool _echoTest(std::string input);
/*
* This function get the sleep and dim value from the Nextion display.
*
* If sleep = 1 meaning: sleep is enabled
* If sleep = 1 meaning: sleep is enabled
* action : sleep will be disabled
* If dim = 0, meaning: the display backlight is turned off
* action : dim will be set to 100 (percent)
*
* If dim = 0, meaning: the display backlight is turned off
* action : dim will be set to 100 (percent)
*
*/
bool _handlingSleepAndDim(void);
/*
* This function (debug) print the Nextion response to a human readable string
*
* @param esp_request - true: request message from esp to nextion
* false: response message from nextion to esp
*
* @param input - string to print
*
* @param esp_request - true: request message from esp to nextion
* false: response message from nextion to esp
*
* @param input - string to print
*
*/
void _printSerialData(bool esp_request, String input);
/*
* This function print a prefix debug line
*
* @param line: optional debug/ info line
*/
void _printInfoLine(String line = "");
void _printSerialData(bool esp_request, std::string input);
/*
* Send command to Nextion.
*
* @param cmd - the string of command.
* @param tail - end the string with tripple 0xFF byte
* @param null_head - start the string with a single 0x00 byte
* @param tail - end the string with tripple 0xFF byte
* @param null_head - start the string with a single 0x00 byte
*
* @return none.
*/
void sendCommand(const char *cmd, bool tail = true, bool null_head = false);
void sendCommand(const char* cmd, bool tail = true, bool null_head = false);
/*
* Receive string data.
*
* @param buffer - save string data.
* @param timeout - set timeout time.
* Receive string data.
*
* @param buffer - save string data.
* @param timeout - set timeout time.
* @param recv_flag - if recv_flag is true,will braak when receive 0x05.
*
* @return the length of string buffer.
*
*/
uint16_t recvRetString(String &string, uint32_t timeout = 500, bool recv_flag = false);
*/
uint16_t recvRetString(std::string &string, uint32_t timeout = 500,bool recv_flag = false);
/*
*
* This function calculates the transmission time, the transmission time
*
* This function calculates the transmission time, the transmission time
* is based on the length of the message and the baudrate.
*
* @param message - only used to determine the length of the message
*
* @param message - only used to determine the length of the message
*
* @return time in us length of string buffer.
*
*/
uint32_t calculateTransmissionTimeMs(String message);
uint32_t calculateTransmissionTimeMs(std::string message);
/*
* Setup UART for communication with display
*
* @param uart_num - UART number
* @param baud_rate - baud rate speed
* @param tx_io_num - GPIO TX pin
* @param rx_io_num - GPIO RX pin
*
*/
void setBaudrate(uart_port_t uart_num, uint32_t baud_rate, gpio_num_t tx_io_num, gpio_num_t rx_io_num);
void nexSerialBegin(uint32_t upload_baudrate, int line, int rx, int tx);
/*
* Check is UART is avaialble
*/
uint32_t uartAvailable();
private: /* data */
uint32_t _baudrate; /* nextion serail baudrate */
uint32_t _undownloadByte; /* undownload byte of tft file */
uint32_t _upload_baudrate; /* upload baudrate */
uint16_t _sent_packets = 0; /* upload baudrate */
uint8_t _rx;
uint8_t _tx;
uint8_t _line;
THandlerFunction _updateProgressCallback;
/*
* Read one RX byte
*
* @return one received UART byte
*/
uint8_t uartRead();
#ifdef ESP8266
SoftwareSerial* nexSerial;
#else
Stream* nexSerial;
#endif
/*
* Write one TX byte
*
* @param c - one byte
*
*/
void uartWrite(uint8_t c);
/*
* Write char string
*
* @param data - char string of data to send
* @param len - length of the string
*
*/
void uartWriteBuf(const char * data, size_t len);
/*
* Clear TX UART buffer
*/
void uartFlushTxOnly();
private: /* data */
bool protv2;
uint32_t _baudrate; /* nextion serail baudrate */
uint32_t _undownloadByte; /* undownload byte of tft file */
uart_port_t _upload_uart_num; /* upload uart port number */
uint32_t _upload_baudrate; /* upload baudrate */
gpio_num_t _upload_tx_io_num; /* upload gpio TX */
gpio_num_t _upload_rx_io_num; /* upload gpio RX */
xSemaphoreHandle _upload_uart_lock; /* semaphore to prevent double UART actions */
bool _upload_uart_has_peek; /* UART RX peek flag */
uint8_t _upload_uart_peek_byte; /* UART RX peek byte */
//uint16_t _sent_packets = 0; /* _sent_packets till 4096 bytes */
uint32_t _sent_packets_total = 0; /* total number of uploaded display firmware bytes */
bool _uart_diver_installed; /* flag, if true UART is installed */
std::string str_snprintf(const char *fmt, size_t len, ...);
/// Format the byte array \p data of length \p len in pretty-printed, human-readable hex.
std::string format_hex_pretty(const uint8_t *data, size_t length);
static char format_hex_pretty_char(uint8_t v);
};
/**
* @}
*/
#endif /* #ifndef __ESPNEXUPLOAD_H__ */
#endif /* #ifndef __ESPNEXUPLOAD_H__ */

View File

@@ -14,6 +14,7 @@ private:
bool _UpTelegram;
char _inc;
String _inStr = ""; // буфер приема строк в режимах 0, 1, 2
bool _protv2;
// Выводим русские буквы на экран Nextion (преобразуем в кодировку ISO-8859-5)
String convertRUS(String text)
@@ -65,6 +66,7 @@ public:
jsonRead(parameters, "speed", _speed);
jsonRead(parameters, "line", _line);
jsonRead(parameters, "uploadTelegram", _UpTelegram);
jsonRead(parameters, "protv2", _protv2);
}
IoTValue execute(String command, std::vector<IoTValue> &param)
@@ -211,10 +213,9 @@ public:
if (!updated)
{
SerialPrint("I", F("NextionUpdate"), "connecting to " + (String)_host);
HTTPClient http;
HTTPClient http;
#if defined ESP8266
WiFiClient client;
if (!http.begin(client, _host, 80, _url))
if (!http.begin(_host, 80, _url))
SerialPrint("I", F("NextionUpdate"), "connection failed ");
#elif defined ESP32
if (!http.begin(String("http://") + _host + _url))
@@ -269,29 +270,31 @@ public:
int contentLength = http.getSize();
SerialPrint("I", F("NextionUpdate"), "File received. Update Nextion... ");
bool result;
ESPNexUpload nexUp(_speed, _line, _rx, _tx);
nexUp.setUpdateProgressCallback([]()
{ SerialPrint("I", F("NextionUpdate"), "... "); });
ESPNexUpload nexUp(_line, _speed, (gpio_num_t)_tx, (gpio_num_t)_rx);
// nexUp.setUpdateProgressCallback([]()
// { SerialPrint("I", F("NextionUpdate"), "... "); });
result = nexUp.prepareUpload(contentLength);
result = nexUp.prepareUpload(contentLength, _protv2);
if (!result)
{
SerialPrint("I", F("NextionUpdate"), "Error: " + (String)nexUp.statusMessage);
SerialPrint("I", F("NextionUpdate"), "Error Connect in prepare upload");
}
else
{
updated = true;
SerialPrint("I", F("NextionUpdate"), "Start upload. File size is: " + (String)contentLength);
result = nexUp.upload(*http.getStreamPtr());
if (result)
{
updated = true;
SerialPrint("I", F("NextionUpdate"), "Succesfully updated Nextion! ");
}
else
{
SerialPrint("I", F("NextionUpdate"), "Error updating Nextion: " + (String)nexUp.statusMessage);
SerialPrint("I", F("NextionUpdate"), "Error updating Nextion" );
}
nexUp.end();
updated = false;
}
}
//---------------------NEXTION-UPDATE---END------------------------

View File

@@ -17,6 +17,7 @@
"rx": 16,
"line": 2,
"speed": 9600,
"protv2": 1,
"uploadTelegram": 1
}
],
@@ -28,8 +29,8 @@
"moduleName": "Nextion",
"moduleVersion": "2.0",
"usedRam": {
"esp32_4mb": 15,
"esp8266_4mb": 15
"esp32_4mb": 152,
"esp8266_4mb": 152
},
"title": "Nextion",
"moduleDesc": "загрузка прошивки в дисплей Nextion. Команда для запуска обновления дисплея: Nextion.Update(); ",
@@ -40,6 +41,7 @@
"line": "Актуально только для ESP32: номер линии hardUART. =2 rx=16 tx=17, для SoftwarwSerial в ESP32 line = -1",
"host": "Сервер обновления. Можно использовать LiveServer из VisualCode, указывать ip адрес",
"url": "файл прошивки экрана, указывать с расширением, например nextion.tft или iotm/test.tft",
"protv2": "1-использует быстрый протоколо прошивки v1.2, 0-использует оффициальный протокол прошивки",
"uploadTelegram": "1 - разрешает прошивать экран через модуль Telegram_v2",
"btn-uploadServer": "Кнопка загрузки прошивки с сервера LiveServer или другого по ip"
},
@@ -87,7 +89,12 @@
},
"defActive": false,
"usedLibs": {
"esp32*": [],
"esp82*": []
"esp32_4mb": [],
"esp32_4mb3f": [],
"esp8266_4mb": [],
"esp8266_1mb": [],
"esp8266_1mb_ota": [],
"esp8285_1mb": [],
"esp8285_1mb_ota": []
}
}

View File

@@ -125,6 +125,8 @@ namespace _Broker
}
}
bool _debug;
class BrokerMQTT : public IoTItem
{
private:
@@ -132,7 +134,7 @@ namespace _Broker
int _port = 0;
String _user;
String _pass;
bool _debug;
//bool _debug;
bool _brige;
String _server;
String _srvUser;
@@ -152,19 +154,6 @@ namespace _Broker
jsonRead(parameters, "srvUser", _srvUser);
jsonRead(parameters, "srvPass", _srvPass);
jsonRead(parameters, "srvPort", _srvPort);
if (_brige)
{
clientMqtt = new PicoMQTT::Client(_server.c_str(), _srvPort, nullptr, _srvUser.c_str(), _srvPass.c_str());
if (_debug)
{
SerialPrint("i", F("BrigeMQTT"), "Bridge mode : ON");
SerialPrint("i", F("BrigeMQTT"), "Bridge server: " + _server);
SerialPrint("i", F("BrigeMQTT"), "Bridge port: " + String(_srvPort));
SerialPrint("i", F("BrigeMQTT"), "Bridge user: " + _srvUser);
SerialPrint("i", F("BrigeMQTT"), "Bridge pass: " + _srvPass);
}
}
}
void doByInterval()
@@ -178,11 +167,30 @@ namespace _Broker
picoMqtt->begin();
picoMqtt->setDebug(_debug);
picoMqtt->setAuth(_user, _pass);
if (_brige)
{
clientMqtt = new PicoMQTT::Client(_server.c_str(), _srvPort, chipId.c_str(), _srvUser.c_str(), _srvPass.c_str());
clientMqtt->begin();
if (_debug)
{
SerialPrint("i", F("BrigeMQTT"), "Bridge mode : ON");
SerialPrint("i", F("BrigeMQTT"), "Bridge server: " + _server);
SerialPrint("i", F("BrigeMQTT"), "Bridge port: " + String(_srvPort));
SerialPrint("i", F("BrigeMQTT"), "Bridge user: " + _srvUser);
SerialPrint("i", F("BrigeMQTT"), "Bridge pass: " + _srvPass);
}
}
if (_brige && picoMqtt && clientMqtt)
{
picoMqtt->subscribe("#", [](const char *topic, const char *message)
{ clientMqtt->publish(topic, message);
SerialPrint("i", F("BrigeMQTT"), "client publish, topic: " + String(topic) + " msg: " + String(message) ); });
if (_debug)
SerialPrint("i", F("BrigeMQTT"), "Client publish, topic: " + String(topic) + " msg: " + String(message) ); });
clientMqtt->subscribe("#", [](const char *topic, const char *message)
{ picoMqtt->publish(topic, message);
if (_debug)
SerialPrint("i", F("BrigeMQTT"), "Server publish, topic: " + String(topic) + " msg: " + String(message) ); });
}
// picoMqtt.begin();
xTaskCreatePinnedToCore(

View File

@@ -686,7 +686,7 @@ public:
{
_myBot->sendMessage("ID: " + chipId, _chatID);
_myBot->sendMessage("chatID: " + _chatID, _chatID);
_myBot->sendMessage("Command: /help - this text \n /all - inline menu get all values \n /allMenu - bottom menu get all values \n /menu - bottom USER menu from scenario \n /get_id - get value by ID \n /set_id_value - set value in ID \n /file_name_type - take file from esp \n /file_type - support file type \n /reboot - reboot esp \n\n send file and write download - \"download\" file to esp \n\n send *.tft file - flash Nextion \n\n send firmware.bin or littltfs.bin - firmware ESP ", _chatID);
_myBot->sendMessage("Command: /help - this text \n /all - inline menu get all values \n /allMenu - bottom menu get all values \n /menu - bottom USER menu from scenario \n /get_id - get value by ID \n /set_id_value - set value in ID \n /file_/path/name_type - take file from esp \n /file_type - support file type \n /reboot - reboot esp \n\n send file and write download - \"download\" file to esp \n\n send *.tft file - flash Nextion \n\n send firmware.bin or littltfs.bin - firmware ESP ", _chatID);
}
}
else if (msg.text.indexOf("/reboot") != -1)