fg71
I try to understand why I get sometimes error from my python script to talk to Modbus Tcp. When this only happen when I use OpenPLC. I do the same example in Arduino IDE and I do not get any error. I use Arduino Nano Esp32.
 
Why does below python script only work sometimes without any modification?
 
Does any know if OpenPLC implementation is different from saying using <ModbusIP_ESP8266.h> in Arduino IDE.
 
  1. I have setup OpenPLC with Arduino Nano ESP32 with 1 contact and 1 coil.
  2. The contact use %QX0.0 and coil %QX0.3
  3. I have setup Modbus TCP communication
  4. All compile and download to the Arduino Nano ESP3
I use pymodbus module in python 3 here is my code.
from pymodbus.client import ModbusTcpClient
from pymodbus import pymodbus_apply_logging_config

client = ModbusTcpClient('192.168.0.189')
if client.connect():
    print("Connect to Modbus server...")

pymodbus_apply_logging_config("DEBUG")

"""
Write to coil
"""
client.write_coil(0, True, slave=1)

r = client.read_coils(0, 1, slave=1)
print(r.bits)
print(r.bits[0])

client.close()
 
Here is the log that is correct
 
>>> %Run read_modbus.py
Connect to Modbus server...
2024-09-29 13:05:09,940 DEBUG logging:103 Current transaction state - IDLE
2024-09-29 13:05:09,940 DEBUG logging:103 Running transaction 1
2024-09-29 13:05:09,940 DEBUG logging:103 SEND: 0x0 0x1 0x0 0x0 0x0 0x6 0x1 0x5 0x0 0x0 0xff 0x0
2024-09-29 13:05:09,940 DEBUG logging:103 New Transaction state "SENDING"
2024-09-29 13:05:09,940 DEBUG logging:103 Changing transaction state from "SENDING" to "WAITING FOR REPLY"
2024-09-29 13:05:09,940 DEBUG logging:103 Transaction failed. (Modbus Error: [Connection] ModbusTcpClient 192.168.0.189:502: Connection unexpectedly closed 0.000 seconds into read of 8 bytes without response from slave before it closed connection)
2024-09-29 13:05:09,940 DEBUG logging:103 Processing:
2024-09-29 13:05:09,940 DEBUG logging:103 Getting transaction 1
2024-09-29 13:05:09,940 DEBUG logging:103 Changing transaction state from "PROCESSING REPLY" to "TRANSACTION_COMPLETE"
2024-09-29 13:05:09,950 DEBUG logging:103 Connection to Modbus server established. Socket ('192.168.0.177', 55808)
2024-09-29 13:05:09,950 DEBUG logging:103 Current transaction state - TRANSACTION_COMPLETE
2024-09-29 13:05:09,950 DEBUG logging:103 Running transaction 2
2024-09-29 13:05:09,950 DEBUG logging:103 SEND: 0x0 0x2 0x0 0x0 0x0 0x6 0x1 0x1 0x0 0x0 0x0 0x1
2024-09-29 13:05:09,950 DEBUG logging:103 New Transaction state "SENDING"
2024-09-29 13:05:09,950 DEBUG logging:103 Changing transaction state from "SENDING" to "WAITING FOR REPLY"
2024-09-29 13:05:09,962 WARNING logging:109  after returning 10 bytes: b'\x00\x02\x00\x00\x00\x04\x01\x01\x01\x01'
2024-09-29 13:05:09,962 DEBUG logging:103 Changing transaction state from "WAITING FOR REPLY" to "PROCESSING REPLY"
2024-09-29 13:05:09,962 DEBUG logging:103 RECV: 0x0 0x2 0x0 0x0 0x0 0x4 0x1 0x1 0x1 0x1
2024-09-29 13:05:09,962 DEBUG logging:103 Got response!!!
2024-09-29 13:05:09,962 DEBUG logging:103 Processing: 0x0 0x2 0x0 0x0 0x0 0x4 0x1 0x1 0x1 0x1
2024-09-29 13:05:09,962 DEBUG logging:103 Factory Response[ReadCoilsResponse': 1]
2024-09-29 13:05:09,962 DEBUG logging:103 Adding transaction 2
2024-09-29 13:05:09,962 DEBUG logging:103 Getting transaction 2
2024-09-29 13:05:09,962 DEBUG logging:103 Changing transaction state from "PROCESSING REPLY" to "TRANSACTION_COMPLETE"
[True, False, False, False, False, False, False, False]
True
>>>

>>> %Run read_modbus.py
Connect to Modbus server...
2024-09-29 13:22:12,364 DEBUG logging:103 Current transaction state - IDLE
2024-09-29 13:22:12,364 DEBUG logging:103 Running transaction 1
2024-09-29 13:22:12,364 DEBUG logging:103 SEND: 0x0 0x1 0x0 0x0 0x0 0x6 0x1 0x5 0x0 0x0 0xff 0x0
2024-09-29 13:22:12,364 DEBUG logging:103 New Transaction state "SENDING"
2024-09-29 13:22:12,365 DEBUG logging:103 Changing transaction state from "SENDING" to "WAITING FOR REPLY"
2024-09-29 13:22:12,373 DEBUG logging:103 Changing transaction state from "WAITING FOR REPLY" to "PROCESSING REPLY"
2024-09-29 13:22:12,374 DEBUG logging:103 RECV: 0x0 0x1 0x0 0x0 0x0 0x6 0x1 0x5 0x0 0x0 0xff 0x0
2024-09-29 13:22:12,374 DEBUG logging:103 Processing: 0x0 0x1 0x0 0x0 0x0 0x6 0x1 0x5 0x0 0x0 0xff 0x0
2024-09-29 13:22:12,374 DEBUG logging:103 Factory Response[WriteSingleCoilResponse': 5]
2024-09-29 13:22:12,374 DEBUG logging:103 Adding transaction 1
2024-09-29 13:22:12,374 DEBUG logging:103 Getting transaction 1
2024-09-29 13:22:12,374 DEBUG logging:103 Changing transaction state from "PROCESSING REPLY" to "TRANSACTION_COMPLETE"
2024-09-29 13:22:12,374 DEBUG logging:103 Current transaction state - TRANSACTION_COMPLETE
2024-09-29 13:22:12,374 DEBUG logging:103 Running transaction 2
2024-09-29 13:22:12,374 DEBUG logging:103 SEND: 0x0 0x2 0x0 0x0 0x0 0x6 0x1 0x1 0x0 0x0 0x0 0x1
2024-09-29 13:22:12,374 DEBUG logging:103 New Transaction state "SENDING"
2024-09-29 13:22:12,375 DEBUG logging:103 Changing transaction state from "SENDING" to "WAITING FOR REPLY"
2024-09-29 13:22:12,375 DEBUG logging:103 Transaction failed. (Modbus Error: [Connection] ModbusTcpClient 192.168.0.189:502: Connection unexpectedly closed 0.000 seconds into read of 8 bytes without response from slave before it closed connection)
2024-09-29 13:22:12,375 DEBUG logging:103 Processing:
2024-09-29 13:22:12,375 DEBUG logging:103 Getting transaction 2
2024-09-29 13:22:12,375 DEBUG logging:103 Changing transaction state from "PROCESSING REPLY" to "TRANSACTION_COMPLETE"
Traceback (most recent call last):
  File "C:\Users\fgustafsson_user\Documents\OpenPLC\ModbusTcp\ModbusTcp_v1\python\read_modbus.py", line 16, in <module>
    print(r.bits)
AttributeError: 'ModbusIOException' object has no attribute 'bits'
>>>
 
The log above is the error log, it looks to me compare the 2 logs the error log are missing: Connection to Modbus server established
Reply 0 0
fg71
I used standard Wifi.h with the Nano ESP32, its Esp32-S3 and I could use both Arduino or Espressif implementations in Arduino IDE.
 
You could test this in Arduino IDE with your ESP32 board.
#include <WiFi.h>
#include <ModbusIP_ESP8266.h>

const int LED_COIL = 1;
//Used Pins
const int ledPin = LED_BUILTIN;

/*
  CHANGE TO YOUR SSID AND PASSWORD FOR YOUR NETWORK
*/
#define SSID ""
#define PASSWORD ""


ModbusIP mb;

void setup() {
  Serial.begin(115200);

  WiFi.begin(SSID, PASSWORD);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }

  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  mb.server();

  pinMode(ledPin, OUTPUT);
  mb.addCoil(LED_COIL);
}

void loop() {
   //Call once inside loop() - all magic here
   mb.task();

   //Attach ledPin to LED_COIL register
   digitalWrite(ledPin, mb.Coil(LED_COIL));
   delay(10);
}
 
And this python script
from pymodbus.client import ModbusTcpClient
# from pymodbus import pymodbus_apply_logging_config
import time

client = ModbusTcpClient('192.168.0.189', port=502)
if client.connect():
    print("Connect to Modbus server...")

# pymodbus_apply_logging_config("DEBUG")

def write_memory(state):
    client.write_coil(1, state, slave=1)
    res = client.read_coils(1, 2, slave=1)
    print("Q1:", res.bits[0])
    client.close()

write_memory(True)
time.sleep(3)
write_memory(False)
 
It works the same as my example in Siemens LOGO
Reply 0 0
thiagoralves
I can't use that specific implementation on OpenPLC Runtime as that will break Modbus TCP on all boards that are not compatible with this library. That's why OpenPLC has its own implementation that is supposed to work everywhere. The problem is that a few boards implements network a little bit different, and those differences must be taken into consideration to make it work properly.
Reply 0 0
fg71
@thiagoralves
Thanks for your inputs.
Reply 0 0
thiagoralves
I’ll try to purchase those boards to see what is going on. Unfortunately Arduino keeps changing their API over time to the point that currently there are slightly different ways to do stuff depending on which board generation you’re using. That’s why OpenPLC code has so many #ifdefs in its Modbus code. Perhaps I’ll have to create yet another #ifdef for Nano ESP32 and Giga
Reply 0 0
thiagoralves
Just to give a short example of what I’m talking about:
#ifdef MBTCP_WIFI
        #if defined(BOARD_ESP8266) || defined(BOARD_ESP32)
            if (ip != NULL && gateway != NULL && subnet != NULL && dns != NULL)
            {
                uint8_t secondaryDNS[] = {8, 8, 8, 8};
                WiFi.config(IPAddress(ip), IPAddress(gateway), IPAddress(subnet), IPAddress(dns), IPAddress(secondaryDNS));
            }
            mb_server.setNoDelay(true);
        #elif defined(BOARD_PORTENTA)
            if (ip != NULL && subnet != NULL && gateway != NULL)
            {
                WiFi.config(IPAddress(ip), IPAddress(subnet), IPAddress(gateway));
            }
        #else
            if (ip != NULL)
            {
                if (dns == NULL)
                    WiFi.config(IPAddress(ip));
                else if (gateway == NULL)
                    WiFi.config(IPAddress(ip), IPAddress(dns));
                else if (subnet == NULL)
                    WiFi.config(IPAddress(ip), IPAddress(dns), IPAddress(gateway));
                else
                    WiFi.config(IPAddress(ip), IPAddress(dns), IPAddress(gateway), IPAddress(subnet));
            }
        #endif
        WiFi.begin(MBTCP_SSID, MBTCP_PWD);
        int num_tries = 0;
 
Reply 0 0
fg71
I did see that when I looked in the ModbusSlave.cpp.
 
Funny thing is that Arduino update yesterday nano esp32 board version to 2.0.18 but that version break my code that was based on 2.0.13.
Same goes with lvgl version 8.x vs 9.x that is not compatible. So doing automatic update is not something I could do anymore. I'm not sure if OpenPLC is checking for the latest board version from the json and download it. As I use Espressif library in OpenPLC compare to Arduino's version.
Reply 0 0
fg71
Perhaps I’ll have to create yet another #ifdef for Nano ESP32 and Giga
I do believe you could use
 
#ifdef ARDUINO_ARCH_ESP32
// do something
#endif
Reply 0 0
fg71
I could share that modbus rtu was working very well with OpenPLC and Arduino Nano ESP32. I guess you are right that wifi (in my case) modbus tcp do not.
Here is the python script that do what I want with modbus rtu over USB port.
 
import time

from pymodbus.client import ModbusSerialClient as ModbusClient
from pymodbus import pymodbus_apply_logging_config

#pymodbus_apply_logging_config("DEBUG")

client = ModbusClient(framer='rtu', port='COM5', baudrate=9600, timeout=1, parity='N', stopbits=1, bytesize=8)
client.connect()

def write_memory(state):
    client.write_coils(0, state)
    res = client.read_coils(0, 1)
    if not res.isError():
        print("Coil value:", res.bits[0])
    else:
        print("Error reading registers")
    client.close()

for i in range(10):
    write_memory(True)
    time.sleep(.1)
    write_memory(False)
 
Reply 0 0
thiagoralves
That's the thing... if you look at the Modbus .cpp code, both RTU and TCP share basically the same code. The only difference is in the network initialization. One thing you could try is to change the board define in the hals.json file for the board you're using to something else. For example, the Arduino ESP32 being an Arduino board, I would guess it would use a network API more similar to the Portenta platform than the generic ESP32 platform. Then you could try replacing the BOARD_ESP32 board define with BOARD_PORTENTA and see if that works. This will basically initialize the network the same way that Arduino Portenta boards are initialized.
Reply 0 0
fg71
The problem with the latest board release of Arduino Nano ESP32 on Windows platform (I believe its only windows). Report limited in filename and extension path.
 
 
Arduino Nano ESP32 version 2.0.18
the filename or extension is too long
 
It make sense to believe you only need Arduino Nano ESP32 board installed to be able to download sketch to the board in Arduino IDE. That is true for version 2.0.13 that do not report the error above. That is not enough for OpenPLC it also need the ESP32 board library to be installed.
I do believe Espressif version of ESP32-S3 3.x version is more updated and Arduino's that is based on 2.x.
 
To download from OpenPLC to Arduino Nano ESP32 is working for Espressif board library or hal esp32:esp32:nano_nora
 
I also find out that if I had older board library from Espressif OpenPLC didn't download to the board at all no matter if I use modbus or not.
 
So far it looks to me Espessif ESP32 version 3.1 RC is the most stable but without Modbus TCP.
 
The question is why do not ONLY Arduino board library for Nano ESP32 work with OpenPLC if the hal use arduino:esp32:nano_nora
It means from my perspective Arduino IDE do not need ESP32 board library to download sketch to the board but OpenPLC does.
Reply 0 0
thiagoralves
OpenPLC does not have a specific Arduino Nano ESP32 entry. So you're probably using one of the ESP32 options. There was a significant change from Espressif Arduino core 2.x to 3.x. OpenPLC had to make changes as well to compile correctly with this new SDK. Therefore, the old 2.x core does not compile on OpenPLC anymore, only the new 3.x ones.
 
The right way to approach this would be to create a new entry on OpenPLC hals.json file for the Arduino Nano ESP32 and then use the correct core and platform for it. This, most likely, does not depend on ESP32 core and libraries and should compile just like the Arduino IDE does. Once you have that working, then you can determine which network model works correctly with this SDK. I would bet that this will follow the BOARD_PORTENTA one, just like all other official Arduino boards.
Reply 0 0
fg71
I will try your approach when Arduino have updated the latest board library to something that works on Windows platform. In other words there is limitations in Windows how long a filename and extension could be. As you know its NTFS thing... and is not effected in macOS or Linux.
 
Maybe that will happen when Arduino's fork is v3, that could maybe be in the next release.... I believe the last version from Espressif was 2.0.17 from v2.x
 
I believe the modbus-tcp code I used in Arduino IDE that was working use this code.
 
I have not give-up yet 😉
Reply 0 0
fg71
I decide to make a example in OpenPLC and compile the project. Next open the source code in Arduino IDE.
Copy all the files it needs into 1 directory. Doing comparing Arduino vs Espressif.
 
The basic to setup WiFi with Arduino Nano ESP32 or ESP32 that is working in Arduino IDE.
#include <WiFi.h>

// Set your Static IP address
IPAddress local_IP(192, 168, 0, 150);
// Set your Gateway IP address
IPAddress gateway(192, 168, 0, 1);

IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);   // optional
IPAddress secondaryDNS(8, 8, 4, 4); // optional

char ssid[] = "ssid";
char psw[] = "password";

void setup() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, psw);
// Configures static IP address
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
  Serial.println("STA Failed to configure");
}
}

void loop() {
  delay(10000);
  WiFi.disconnect();
  Serial.println("Disconnect the WiFi after 10 seconds...");
}
 
Do ping for both (Espressif and Arduino), result the IP 192.168.0.150 is replay data.
 
Next remove starting to isolate the problem by comment out all code that is not used.
When the Arduino board library is used I get this error in Arduino IDE.
 
Compilation error: no matching function for call to "WiFiClass::config(IPAddress)"
  1. Change the .cpp file to remove the error...
  2. No error but still no working modbus tcp.
Do the ping and replay return data.
 
To have everything in Arduino IDE is easier to debug.... but now I think I need to understand your implementation of modbus.
And do examples in Arduino IDE.
Reply 0 0
fg71
I could inform I have got Modbus Tcp to work for Arduino Nano ESP32. Its doesn't matter if we use Arduino fork or Espressif board library.
As @thiagoralves explained it was the hals.json file that need to be updated with this line: "define": "BOARD_PORTENTA",
 
I will later test on Arduino Giga r1 if that approach also work with that board.
 
The test I have done is sending request Siemens (Client) to Arduino Nano ESP32 (Server)
 
"Arduino Nano ESP32": {
    "core": "esp32:esp32",
    "default_ain": "A0, A1, A2, A3, A4, A5",
    "default_aout": "9, 10, 11",
    "default_din": "2, 3, 4, 5, 6",
    "default_dout": "7, 8, 12, 13",
    "define": "BOARD_PORTENTA",
    "last_update": 0,
    "platform": "esp32:esp32:nano_nora",
    "source": "nano_esp32.cpp",
    "version": "3.1.0-RC1"
  },
Reply 0 0
fg71
I could also inform that Arduino Giga r1 also have a working Modbus Tcp when we include: "define": "BOARD_PORTENTA", in the hals.json file.
We also need to update the default Analog Outputs GPIO to remove 86, 87 and 88. The GPIO 86 (red_led), 87 (green_led) and 88 (blue_led).
I use the Red Led in the example below for Digital Output GPIO 86. That is %QX3.0
[203128%2F9012104%2Fmceclip0]
Reply 0 0
Reply