Troubleshooting Modbus Connection Issue: "Failed to connect" Error

Hello Python community,

I am currently working on a project that involves communication between a ROS (Robot Operating System) environment and an Allen-Bradley CompactLogix PLC using Modbus TCP. I have encountered an issue with the Modbus connection, and I would appreciate any guidance or insights on resolving it.

Problem Description:

I am attempting to send data from ROS to the 1769-L16ER-BB1B Allen Bradley CompactLogix PLC. However, when running the provided Python code snippet, I am encountering the following error:

Modbus Error: [Connection] Failed to connect [ModbusTcpClient 192.168.1.1:502]

Code Snippet:

python

def move_robot_thread(self):
    plc_ip = '192.168.1.1'
    plc_port = 502

    # Create a synchronous ModbusTcpClient instance
    client = ModbusTcpClient(plc_ip, plc_port)

    try:
        for point in self.palletizing_pattern:
            x, y, z = point
            x_register_value = int(x * 100)  # Convert to an appropriate integer value
            y_register_value = int(y * 100)
            z_register_value = int(z * 100)

            # Write the coordinates to Modbus registers
            client.write_registers(0, [x_register_value, y_register_value, z_register_value])

            print(f"Published pose: x={x}, y={y}, z={z}")
            print("Waiting for response...")

            # Introduce a delay (adjust the duration as needed)
            time.sleep(6)

        print("All poses published.")

    except Exception as e:
        print(f"Error during Modbus communication: {e}")

    finally:
        # Close the Modbus connection
        client.close()

def move_robot(self):
    # Create a new thread for move_robot_thread function
    move_thread = threading.Thread(target=self.move_robot_thread)
    # Start the new thread
    move_thread.start()

Include relevant import statements

!/usr/bin/env python3

from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QComboBox

from PyQt5.QtCore import Qt

from PyQt5.QtWidgets import QComboBox

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

from matplotlib.figure import Figure

import matplotlib.pyplot as plt

from geometry_msgs.msg import PoseStamped

from std_msgs.msg import String

from std_srvs.srv import Trigger

from pymodbus.client import ModbusTcpClient

import rclpy

import sys

import threading

from rclpy.task import Future

import time

Additional Information:

ROS version: humble 
Python version: 3.10.12
Allen Bradley PLC model: 1769-L16ER-BB1B
Network configuration: modbus tcp

Questions:

What could be causing the "Failed to connect" Modbus error?
Are there specific considerations for Modbus communication with the Allen Bradley CompactLogix PLC?
How can I troubleshoot and diagnose the Modbus connection issue?

Any help or advice on resolving this Modbus connection problem would be greatly appreciated.

Thank you,

Check that you have the correct ip address and port.
192.168.1.1 may be wrong, is it your routers address for example?

FYI Also not all the code in your post where formatted as preformatted text, can you edit the post to fix that?

ip address is correct as i check by ping 192.168.1.1
also the port is correct and there is no firewall blocking

Hi !

I see you nowhere call client.connect(). I remember including it in my code when using pymodbus a while ago, could that be the problem ?

now i include client.connect( ) but still i am getting
Connection to (192.168.1.102, 502) failed: timed out
Failed to connect to the Modbus server.

i also try to change the ip of the plc from 192.168.1.1 to 192.168.1.102

Sounds like you are not sure what the IP address of the device is.

Is there anyway to query the device setup to see its IP address by another means?

For example can you see what addresses your router is handing out over DHCP?

Perviously i set ip 192.168.1.1
But now change ip which is 192.168.1.102
My ip is correct and i checked by ping it

I have a modbus device in my home.
It was painful to get access working to it.

I think it was not using the “normal” modbus port number.

Once I had that working I faced the issue that it only responded to correctly formatted requests.
Some one else had figure out what “correct” meant for my device.
I might have seen timeout errors with I got the message wrong, but I forget the details now.

Also note that devices that claim to do modbus may only not have a full protocol implementation, as was the case with my device at home.

I ended up having to write my own code to create the modbus frames with the none-standard headers.
But I could use pymodbus to encode and decode the payload.

Thankfully, as I said, someone else had done the hard work of figureing out the details.