diff --git a/tasmota/my_user_config.h b/tasmota/my_user_config.h index 9bf93bf55b09..094199aef9bb 100644 --- a/tasmota/my_user_config.h +++ b/tasmota/my_user_config.h @@ -754,6 +754,7 @@ //#define USE_DYP // Add support for DYP ME-007 ultrasonic distance sensor, serial port version (+0k5 code) #define USE_SERIAL_BRIDGE // Add support for software Serial Bridge (+0k8 code) //#define USE_MODBUS_BRIDGE // Add support for software Modbus Bridge (+3k code) +//#define USE_MODBUS_TCP_BRIDGE // Add support for software Modbus TCP Bridge (? code) //#define USE_TCP_BRIDGE // Add support for Serial to TCP bridge (+1.3k code) //#define USE_MP3_PLAYER // Use of the DFPlayer Mini MP3 Player RB-DFR-562 commands: play, pause, stop, track, volume and reset #define MP3_VOLUME 30 // Set the startup volume on init, the range can be 0..100(max) diff --git a/tasmota/tasmota_xdrv_driver/xdrv_63_modbus_bridge.ino b/tasmota/tasmota_xdrv_driver/xdrv_63_modbus_bridge.ino index faf102934565..d0596d3926bb 100644 --- a/tasmota/tasmota_xdrv_driver/xdrv_63_modbus_bridge.ino +++ b/tasmota/tasmota_xdrv_driver/xdrv_63_modbus_bridge.ino @@ -17,19 +17,21 @@ along with this program. If not, see . */ -#ifdef USE_MODBUS_BRIDGE +#if defined(USE_MODBUS_BRIDGE) || defined(USE_MODBUS_TCP_BRIDGE) /*********************************************************************************************\ * Modbus Bridge using Modbus library (TasmotaModbus) * + * Can be used trough web/mqtt commands and also via direct TCP connection (when defined) + * * Example Command: - * ModbusSend {"deviceaddress": 1, "functioncode": 3, "startaddress": 1, "type":"uint8", "count":4} + * ModbusSend {"deviceaddress": 1, "functioncode": 3, "startaddress": 1, "type":"uint16", "count":2} \*********************************************************************************************/ -#define XDRV_63 63 +#define XDRV_63 63 -#define MBR_MAX_VALUE_LENGTH 30 -#define MBR_SPEED TM_MODBUS_BAUDRATE -#define MBR_MAX_REGISTERS 64 +#define MBR_MAX_VALUE_LENGTH 30 +#define MBR_SPEED TM_MODBUS_BAUDRATE +#define MBR_MAX_REGISTERS 64 #define D_CMND_MODBUS_SEND "Send" #define D_CMND_MODBUS_SETBAUDRATE "Baudrate" @@ -45,11 +47,41 @@ #define D_JSON_MODBUS_VALUES "Values" #define D_JSON_MODBUS_LENGTH "Length" +#ifndef USE_MODBUS_TCP_BRIDGE const char kModbusBridgeCommands[] PROGMEM = "Modbus|" // Prefix D_CMND_MODBUS_SEND "|" D_CMND_MODBUS_SETBAUDRATE "|" D_CMND_MODBUS_SETSERIALCONFIG; void (*const ModbusBridgeCommand[])(void) PROGMEM = { &CmndModbusBridgeSend, &CmndModbusBridgeSetBaudrate, &CmndModbusBridgeSetConfig}; +#endif + +#ifdef USE_MODBUS_TCP_BRIDGE +#ifndef MODBUS_TCP_BRIDGE_CONNECTIONS +#define MODBUS_TCP_BRIDGE_CONNECTIONS 1 // number of maximum parallel connections, only 1 supported with modbus +#endif + +#ifndef MODBUS_TCP_BRIDGE_BUF_SIZE +#define MODBUS_TCP_BRIDGE_BUF_SIZE 255 // size of the buffer, above 132 required for efficient XMODEM +#endif + +#define D_CMND_MODBUS_TCP_START "TCPStart" +#define D_CMND_MODBUS_TCP_CONNECT "TCPConnect" + +const char kModbusBridgeCommands[] PROGMEM = "Modbus|" // Prefix + D_CMND_MODBUS_TCP_START "|" D_CMND_MODBUS_TCP_CONNECT "|" D_CMND_MODBUS_SEND "|" D_CMND_MODBUS_SETBAUDRATE "|" D_CMND_MODBUS_SETSERIALCONFIG; + +void (*const ModbusBridgeCommand[])(void) PROGMEM = { + &CmndModbusTCPStart, &CmndModbusTCPConnect, + &CmndModbusBridgeSend, &CmndModbusBridgeSetBaudrate, &CmndModbusBridgeSetConfig}; + +WiFiServer *server_tcp = nullptr; +WiFiClient client_tcp[MODBUS_TCP_BRIDGE_CONNECTIONS]; +uint8_t client_next = 0; +uint8_t *tcp_buf = nullptr; // data transfer buffer +IPAddress ip_filter; + +uint16_t tcp_transaction_id = 0; +#endif #include TasmotaModbus *tasmotaModbus = nullptr; @@ -80,15 +112,13 @@ enum class ModbusBridgeFunctionCode enum class ModbusBridgeType { mb_undefined, - mb_uint8, mb_uint16, mb_uint32, - mb_int8, mb_int16, mb_int32, mb_float, mb_raw, - mb_bit8 + mb_bit }; enum class ModbusBridgeEndian @@ -143,21 +173,51 @@ void ModbusBridgeHandle(void) if (data_ready) { uint8_t *buffer; - buffer = (uint8_t *)malloc(5 + modbusBridge.registerCount); // Addres(1), Function(1), Length(1), Data(1..n), CRC(2) + buffer = (uint8_t *)malloc(5 + (modbusBridge.registerCount * 2)); // Addres(1), Function(1), Length(1), Data(1..n), CRC(2) uint32_t error = tasmotaModbus->ReceiveBuffer(buffer, modbusBridge.registerCount); - ModbusBridgeError errorcode = ModbusBridgeError::noerror; if (error) { AddLog(LOG_LEVEL_DEBUG, PSTR("MBS: MBR Driver error %d"), error); + return; + } + +#ifdef USE_MODBUS_TCP_BRIDGE + for (uint32_t i = 0; i < nitems(client_tcp); i++) + { + WiFiClient &client = client_tcp[i]; + if (client) + { + uint8_t MBAP_Header[7]; + MBAP_Header[0] = tcp_transaction_id >> 8; + MBAP_Header[1] = tcp_transaction_id; + MBAP_Header[2] = 0; + MBAP_Header[3] = 0; + MBAP_Header[4] = ((modbusBridge.registerCount * 2) + 2) >> 8; + MBAP_Header[5] = (modbusBridge.registerCount * 2) + 2; + MBAP_Header[6] = buffer[0]; + client.write(MBAP_Header, 7); + client.write(buffer+1, 1); // Don't send CRC + client.write(buffer+3, (modbusBridge.registerCount*2)); // Don't send CRC + client.flush(); + AddLog(LOG_LEVEL_DEBUG, PSTR("MBS: MBRTCP Writing %d bytes to client"), (modbusBridge.registerCount*2) + 6 + 3); + } } - else if (modbusBridge.deviceAddress == 0) +#endif + + ModbusBridgeError errorcode = ModbusBridgeError::noerror; + if (modbusBridge.deviceAddress == 0) + { +#ifdef USE_MODBUS_TCP_BRIDGE + return; +#endif errorcode = ModbusBridgeError::nodataexpected; + } else if (modbusBridge.deviceAddress != (uint8_t)buffer[0]) errorcode = ModbusBridgeError::wrongdeviceaddress; else if ((uint8_t)modbusBridge.functionCode != (uint8_t)buffer[1]) errorcode = ModbusBridgeError::wrongfunctioncode; - else if ((uint8_t)modbusBridge.registerCount != (uint8_t)buffer[2]) + else if ((uint8_t)modbusBridge.registerCount*2 != (uint8_t)buffer[2]) errorcode = ModbusBridgeError::wrongregistercount; else { @@ -222,15 +282,7 @@ void ModbusBridgeHandle(void) else snprintf(svalue, MBR_MAX_VALUE_LENGTH, "%u", value); } - else if ((modbusBridge.type == ModbusBridgeType::mb_int8) || - (modbusBridge.type == ModbusBridgeType::mb_uint8)) - { - if (modbusBridge.type == ModbusBridgeType::mb_int8) - snprintf(svalue, MBR_MAX_VALUE_LENGTH, "%d", (int8_t)(buffer[3 + count])); - else - snprintf(svalue, MBR_MAX_VALUE_LENGTH, "%u", (uint8_t)(buffer[3 + count])); - } - else if (modbusBridge.type == ModbusBridgeType::mb_bit8) + else if (modbusBridge.type == ModbusBridgeType::mb_bit) { uint8_t value = (uint8_t)(buffer[3 + count]); snprintf(svalue, MBR_MAX_VALUE_LENGTH, "%d%d%d%d%d%d%d%d", ((value >> 7) & 1), ((value >> 6) & 1), ((value >> 5) & 1), ((value >> 4) & 1), ((value >> 3) & 1), ((value >> 2) & 1), ((value >> 1) & 1), (value & 1)); @@ -275,8 +327,109 @@ void ModbusBridgeInit(void) AddLog(LOG_LEVEL_DEBUG, PSTR("MBS: MBR %s ser init at %d baud"), (2 == result ? "HW" : "SW"), MBR_SPEED); } } + +#ifdef USE_MODBUS_TCP_BRIDGE + tcp_buf = (uint8_t *)malloc(MODBUS_TCP_BRIDGE_BUF_SIZE); + if (!tcp_buf) + { + AddLog(LOG_LEVEL_ERROR, PSTR("MBS: MBR could not allocate TCP buffer")); + return; + } +#endif } +#ifdef USE_MODBUS_TCP_BRIDGE +/********************************************************************************************/ +// +// Called at event loop, checks for incoming data from the modbus devices +// +void ModbusTCPLoop(void) +{ + uint8_t c; + bool busy; // did we transfer some data? + int32_t buf_len; + + if (!tasmotaModbus) + return; + + // check for a new client connection + if ((server_tcp) && (server_tcp->hasClient())) + { + WiFiClient new_client = server_tcp->available(); + + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "MBS: MBRTCP Got connection from %s"), new_client.remoteIP().toString().c_str()); + // Check for IP filtering if it's enabled. + if (ip_filter) + { + if (ip_filter != new_client.remoteIP()) + { + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "MBS: MBRTCP Rejected due to filtering")); + new_client.stop(); + } + else + { + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "MBS: MBRTCP Allowed through filter")); + } + } + + // find an empty slot + uint32_t i; + for (i = 0; i < nitems(client_tcp); i++) + { + WiFiClient &client = client_tcp[i]; + if (!client) + { + client = new_client; + break; + } + } + if (i >= nitems(client_tcp)) + { + i = client_next++ % nitems(client_tcp); + WiFiClient &client = client_tcp[i]; + client.stop(); + client = new_client; + } + } + + do + { + busy = false; // exit loop if no data was transferred + + // handle data received from TCP + for (uint32_t i = 0; i < nitems(client_tcp); i++) + { + WiFiClient &client = client_tcp[i]; + buf_len = 0; + while (client && (buf_len < MODBUS_TCP_BRIDGE_BUF_SIZE) && (client.available())) + { + c = client.read(); + if (c >= 0) + { + tcp_buf[buf_len++] = c; + busy = true; + } + } + if (buf_len > 11) + { + AddLog(LOG_LEVEL_DEBUG_MORE, PSTR("MBS: MBRTCP to Modbus deviceAddress:%d, functionCode:%d, startAddress:%d, Length:%d"), + (uint8_t)tcp_buf[6], + (uint8_t)tcp_buf[7], + (uint16_t)((((uint16_t)tcp_buf[8]) << 8) | ((uint16_t)tcp_buf[9])), + (uint16_t)((((uint16_t)tcp_buf[10]) << 8) | ((uint16_t)tcp_buf[11]))); + tcp_transaction_id = (uint16_t)((((uint16_t)tcp_buf[0]) << 8) | ((uint16_t)tcp_buf[1])); + modbusBridge.registerCount = (uint16_t)((((uint16_t)tcp_buf[10]) << 8) | ((uint16_t)tcp_buf[11])); + tasmotaModbus->Send((uint8_t)tcp_buf[6], + (uint8_t)tcp_buf[7], + (uint16_t)((((uint16_t)tcp_buf[8]) << 8) | ((uint16_t)tcp_buf[9])), + (uint16_t)((((uint16_t)tcp_buf[10]) << 8) | ((uint16_t)tcp_buf[11]))); + } + } + yield(); // avoid WDT if heavy traffic + } while (busy); +} +#endif + /*********************************************************************************************\ * Commands \*********************************************************************************************/ @@ -309,55 +462,46 @@ void CmndModbusBridgeSend(void) } modbusBridge.type = ModbusBridgeType::mb_undefined; - if (strcmp(stype, "int8") == 0) - { - modbusBridge.type = ModbusBridgeType::mb_int8; - modbusBridge.registerCount = 1 * modbusBridge.count; - } - else if (strcmp(stype, "int16") == 0) + if (strcmp(stype, "int16") == 0) { modbusBridge.type = ModbusBridgeType::mb_int16; - modbusBridge.registerCount = 2 * modbusBridge.count; + modbusBridge.registerCount = modbusBridge.count; } else if (strcmp(stype, "int32") == 0) { modbusBridge.type = ModbusBridgeType::mb_int32; - modbusBridge.registerCount = 4 * modbusBridge.count; - } - else if (strcmp(stype, "uint8") == 0) - { - modbusBridge.type = ModbusBridgeType::mb_uint8; - modbusBridge.registerCount = 1 * modbusBridge.count; + modbusBridge.registerCount = 2 * modbusBridge.count; } else if (strcmp(stype, "uint16") == 0) { modbusBridge.type = ModbusBridgeType::mb_uint16; - modbusBridge.registerCount = 2 * modbusBridge.count; + modbusBridge.registerCount = modbusBridge.count; } else if (strcmp(stype, "uint32") == 0) { modbusBridge.type = ModbusBridgeType::mb_uint32; - modbusBridge.registerCount = 4 * modbusBridge.count; + modbusBridge.registerCount = 2 * modbusBridge.count; } else if (strcmp(stype, "float") == 0) { modbusBridge.type = ModbusBridgeType::mb_float; - modbusBridge.registerCount = 4 * modbusBridge.count; + modbusBridge.registerCount = 2 * modbusBridge.count; } else if (strcmp(stype, "raw") == 0) { modbusBridge.type = ModbusBridgeType::mb_raw; modbusBridge.registerCount = modbusBridge.count; } - else if (strcmp(stype, "bit8") == 0) + else if (strcmp(stype, "bit") == 0) { - modbusBridge.type = ModbusBridgeType::mb_bit8; + modbusBridge.type = ModbusBridgeType::mb_bit; modbusBridge.registerCount = modbusBridge.count; } else errorcode = ModbusBridgeError::wrongtype; - if (modbusBridge.registerCount > MBR_MAX_REGISTERS) errorcode = ModbusBridgeError::wrongcount; + if (modbusBridge.registerCount > MBR_MAX_REGISTERS) + errorcode = ModbusBridgeError::wrongcount; if (errorcode != ModbusBridgeError::noerror) { @@ -407,6 +551,114 @@ void CmndModbusBridgeSetConfig(void) ResponseCmndChar(GetSerialConfig(Settings->sserial_config).c_str()); } +#ifdef USE_MODBUS_TCP_BRIDGE +// +// Command `TCPStart` +// Params: port, +// +void CmndModbusTCPStart(void) +{ + + if (!tasmotaModbus) + { + return; + } + + int32_t tcp_port = XdrvMailbox.payload; + if (ArgC() == 2) + { + char sub_string[XdrvMailbox.data_len]; + ip_filter.fromString(ArgV(sub_string, 2)); + } + else + { + // Disable whitelist if previously set + ip_filter = (uint32_t)0; + } + + if (server_tcp) + { + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "Stopping TCP server")); + server_tcp->stop(); + delete server_tcp; + server_tcp = nullptr; + + for (uint32_t i = 0; i < nitems(client_tcp); i++) + { + WiFiClient &client = client_tcp[i]; + client.stop(); + } + } + if (tcp_port > 0) + { + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "MBS: MBR Starting TCP server on port %d"), tcp_port); + if (ip_filter) + { + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "MBS: MBR Filtering TCP %s"), ip_filter.toString().c_str()); + } + server_tcp = new WiFiServer(tcp_port); + server_tcp->begin(); // start TCP server + server_tcp->setNoDelay(true); + } + + ResponseCmndDone(); +} + +// +// Command `Connect` +// Params: port, +// +void CmndModbusTCPConnect(void) +{ + int32_t tcp_port = XdrvMailbox.payload; + + if (!tasmotaModbus) + { + return; + } + + if (ArgC() == 2) + { + char sub_string[XdrvMailbox.data_len]; + WiFiClient new_client; + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "MBS: MBR Connecting to %s on port %d"), ArgV(sub_string, 2), tcp_port); + if (new_client.connect(ArgV(sub_string, 2), tcp_port)) + { + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "MBS: MBR connected!")); + } + else + { + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "MBS: MBR error connecting!")); + } + + // find an empty slot + uint32_t i; + for (i = 0; i < nitems(client_tcp); i++) + { + WiFiClient &client = client_tcp[i]; + if (!client) + { + client = new_client; + break; + } + } + if (i >= nitems(client_tcp)) + { + i = client_next++ % nitems(client_tcp); + WiFiClient &client = client_tcp[i]; + client.stop(); + client = new_client; + } + } + else + { + AddLog(LOG_LEVEL_INFO, PSTR(D_LOG_TCP "MBS: MBR Usage: port,ip_address")); + } + + ResponseCmndDone(); +} +#endif + /*********************************************************************************************\ * Interface \*********************************************************************************************/ @@ -423,12 +675,15 @@ bool Xdrv63(uint8_t function) { switch (function) { - case FUNC_EVERY_250_MSECOND: - ModbusBridgeHandle(); - break; case FUNC_COMMAND: result = DecodeCommand(kModbusBridgeCommands, ModbusBridgeCommand); break; + case FUNC_LOOP: + ModbusBridgeHandle(); +#ifdef USE_MODBUS_TCP_BRIDGE + ModbusTCPLoop(); +#endif + break; } } return result;