Расширяем модуль UART для обмена сообщениями с другими МК

This commit is contained in:
2022-11-04 17:01:12 +03:00
parent 67e9c160ea
commit 15da6dd973
2 changed files with 118 additions and 32 deletions

View File

@@ -6,58 +6,143 @@
#include "modules/sensors/UART/Uart.h" #include "modules/sensors/UART/Uart.h"
#ifdef ESP8266 #ifdef ESP8266
SoftwareSerial* myUART = nullptr; SoftwareSerial* myUART = nullptr;
#else #else
HardwareSerial* myUART = nullptr; HardwareSerial* myUART = nullptr;
#endif #endif
class UART : public IoTItem { class UART : public IoTItem {
private: private:
int tx; int _tx;
int rx; int _rx;
int speed; int _speed;
int _eventFormat = 0; // 0 - нет приема, 1 - json IoTM, 2 - Nextion
#ifdef ESP8266
SoftwareSerial* _myUART = nullptr;
#else
HardwareSerial* _myUART = nullptr;
#endif
public: public:
UART(String parameters) : IoTItem(parameters) { UART(String parameters) : IoTItem(parameters) {
tx = jsonReadInt(parameters, "tx"); jsonRead(parameters, "tx", _tx);
rx = jsonReadInt(parameters, "rx"); jsonRead(parameters, "rx", _rx);
speed = jsonReadInt(parameters, "speed"); jsonRead(parameters, "speed", _speed);
jsonRead(parameters, "eventFormat", _eventFormat);
if (!myUART) {
#ifdef ESP8266 #ifdef ESP8266
myUART = new SoftwareSerial(tx, rx); myUART = _myUART = new SoftwareSerial(_tx, _rx);
myUART->begin(speed); _myUART->begin(_speed);
#endif #endif
#ifdef ESP32 #ifdef ESP32
myUART = new HardwareSerial(2); _myUART = new HardwareSerial(2);
myUART->begin(speed, SERIAL_8N1, rx, tx); _myUART->begin(speed, SERIAL_8N1, rx, tx);
#endif #endif
} }
SerialPrint("i", F("UART"), F("UART Init"));
// проверяем формат и если событие, то регистрируем его
void analyzeString(const String& msg) {
switch (_eventFormat) {
case 0: // не указан формат, значит все полученные данные воспринимаем как общее значение из UART
setValue(msg);
break;
case 1: // формат событий IoTM с использованием json, значит создаем временную копию
analyzeMsgFromNet(msg);
break;
case 2: // формат команд от Nextion ID=Value
String id = selectToMarker(msg, "=");
IoTItem *item = findIoTItem(id);
if (!item) return;
String valStr = selectToMarkerLast(msg, "=");
valStr.replace("\"", "");
item->setValue(valStr);
break;
}
} }
void uartHandle() { void uartHandle() {
if (myUART) { if (!_myUART) return;
static String incStr;
if (myUART->available()) { if (_myUART->available()) {
static String inStr = "";
char inc; char inc;
inc = myUART->read(); inc = _myUART->read();
incStr += inc; inStr += inc;
if (inc == '\n') { if (inc == '\n') {
parse(incStr); analyzeString(inStr);
incStr = ""; inStr = "";
}
} }
} }
} }
void parse(String& incStr) { void onRegEvent(IoTItem* eventItem) {
SerialPrint("I", "=>UART", incStr); if (!_myUART) return;
String printStr = "";
switch (_eventFormat) {
case 0: return; // не указан формат, значит не следим за событиями
case 1: // формат событий IoTM с использованием json
eventItem->getNetEvent(printStr);
_myUART->println(printStr);
break;
case 2: // формат событий для Nextion ID=Value0xFF0xFF0xFF
printStr += eventItem->getID();
printStr += "=";
if (eventItem->value.isDecimal)
printStr += eventItem->value.valD;
else {
printStr += "\"";
printStr += eventItem->value.valS;
printStr += "\"";
}
_myUART->print(printStr);
_myUART->write(0xff);
_myUART->write(0xff);
_myUART->write(0xff);
break;
}
} }
void uartPrint(String msg) { virtual void loop() {
myUART->print(msg); uartHandle();
} }
void uartPrint(const String& msg) {
if (_myUART) {
_myUART->println(msg);
}
}
void uartPrintHex(const String& msg) {
if (!_myUART) return;
unsigned char Hi, Lo;
uint8_t byteTx;
const char* strPtr = msg.c_str();
while ((Hi = *strPtr++) && (Lo = *strPtr++)) {
byteTx = (ChartoHex(Hi) << 4) | ChartoHex(Lo);
_myUART->write(byteTx);
}
}
IoTValue execute(String command, std::vector<IoTValue> &param) {
if (command == "print") {
if (param.size() == 1) {
uartPrint(param[0].valS);
}
} else if (command == "printHex") {
if (param.size() == 1) {
uartPrintHex(param[0].valS);
}
}
return {};
}
}; };
void* getAPI_UART(String subtype, String param) { void* getAPI_UART(String subtype, String param) {

View File

@@ -2,7 +2,6 @@
"menuSection": "Сенсоры", "menuSection": "Сенсоры",
"configItem": [ "configItem": [
{ {
"global": 0,
"name": "UART", "name": "UART",
"type": "Reading", "type": "Reading",
"subtype": "UART", "subtype": "UART",
@@ -12,7 +11,8 @@
"id": "u", "id": "u",
"tx": 12, "tx": 12,
"rx": 13, "rx": 13,
"speed": 9600 "speed": 9600,
"eventFormat": 0
} }
], ],
"about": { "about": {
@@ -30,11 +30,12 @@
"SoftUART" "SoftUART"
], ],
"title": "Software uart для esp8266 или hardware uart для esp32", "title": "Software uart для esp8266 или hardware uart для esp32",
"moduleDesc": "Используется вместе с Pzem004t или с другими работающими по uart сенсорами, в последствии будет доработан для связи с arduino платами", "moduleDesc": "Используется вместе с Pzem004t или с другими работающими по uart сенсорами. Пригоден для обмена данными с другими контроллерами в ручном режиме или с автоматической трансляцией событий как по сети.",
"propInfo": { "propInfo": {
"tx": "TX пин", "tx": "TX пин",
"rx": "RX пин", "rx": "RX пин",
"speed": "Скорость UART" "speed": "Скорость UART",
"eventFormat": "Выбор формата обмена сообщениями с другими контроллерами. =0 - не указан формат, значит не следим за событиями, =1 - формат событий IoTM с использованием json, =2 - формат событий для Nextion отправка событий: ID=Value0xFF0xFF0xFF прием ордеров: ID=Value"
} }
}, },
"defActive": true, "defActive": true,