@@ -214,7 +214,11 @@ void ModbusTCPTemplate<SERVER, CLIENT>::task() {
214214 CLIENT c;
215215 // WiFiServer.available() == Ethernet.accept() and should wrapped to get code to be compatible with Ethernet library (See ModbusTCP.h code).
216216 // WiFiServer.available() != Ethernet.available() internally
217+ #if defined(MODBUSIP_USE_AVAILABLE)
218+ while (millis () - taskStart < MODBUSIP_MAX_READMS && (c = tcpserver->available ())) {
219+ #else
217220 while (millis () - taskStart < MODBUSIP_MAX_READMS && (c = tcpserver->accept ())) {
221+ #endif
218222#if defined(MODBUSIP_DEBUG)
219223 Serial.println (" IP: Accepted" );
220224#endif
@@ -244,7 +248,11 @@ void ModbusTCPTemplate<SERVER, CLIENT>::task() {
244248 Serial.print (" IP: Conn " );
245249 Serial.println (n);
246250#endif
251+ #if defined(MODBUSIP_USE_AVAILABLE)
252+ break ; // while
253+ #else
247254 continue ; // while
255+ #endif
248256 }
249257 }
250258 // Close connection if callback returns false or MODBUSIP_MAX_CLIENTS reached
@@ -268,14 +276,15 @@ void ModbusTCPTemplate<SERVER, CLIENT>::task() {
268276 continue ;
269277 }
270278 _len = __swap_16 (_MBAP.length );
271- if (_len < MODBUSIP_MINFRAME) { // Length is over MODBUSIP_MAXFRAME
279+ if (_len < MODBUSIP_MINFRAME) { // Length is shorter than MODBUSIP_MINFRAME
280+ Modbus::FunctionCode fc = FC_READ_COILS; // Just placeholder
272281 while (tcpclient[n]->available ()) // Drop rest of the packet
273282 tcpclient[n]->read ();
274283 exceptionResponse (fc, EX_ILLEGAL_VALUE);
275284 }
276285 _len--; // Do not count with last byte from MBAP
277286 if (_len > MODBUSIP_MAXFRAME) { // Length is over MODBUSIP_MAXFRAME
278- Modbus::FunctionCode fc = tcpclient[n]->read ();
287+ Modbus::FunctionCode fc = (Modbus::FunctionCode) tcpclient[n]->read ();
279288 _len--; // Subtract for read byte
280289 for (uint8_t i = 0 ; tcpclient[n]->available () && i < _len; i++) // Drop rest of the packet
281290 tcpclient[n]->read ();
@@ -285,15 +294,15 @@ void ModbusTCPTemplate<SERVER, CLIENT>::task() {
285294 free (_frame);
286295 _frame = (uint8_t *) malloc (_len);
287296 if (!_frame) {
288- Modbus::FunctionCode fc = tcpclient[n]->read ();
297+ Modbus::FunctionCode fc = (Modbus::FunctionCode) tcpclient[n]->read ();
289298 _len--; // Subtract for read byte
290299 for (uint8_t i = 0 ; tcpclient[n]->available () && i < _len; i++) // Drop rest of the packet
291300 tcpclient[n]->read ();
292301 exceptionResponse (fc, EX_SLAVE_FAILURE);
293302 }
294303 else {
295304 if (tcpclient[n]->readBytes (_frame, _len) < _len) { // Try to read MODBUS frame
296- exceptionResponse ((FunctionCode)_frame[0 ], EX_ILLEGAL_VALUE);
305+ exceptionResponse ((Modbus:: FunctionCode)_frame[0 ], EX_ILLEGAL_VALUE);
297306 // while (tcpclient[n]->available()) // Drop all incoming (if any)
298307 // tcpclient[n]->read();
299308 }
0 commit comments