ModbusTCP從站(服務端)掃描工具 python實現

生命在等待中延续發表於2024-05-16

掃描指定IP網路下,有哪些modbusTCP服務端[1-247]

from pymodbus.client import ModbusTcpClient
from pymodbus.exceptions import ModbusIOException, ConnectionException, NoSuchSlaveException
import time


def read_holding_registers(client, slave_address):
    """嘗試讀取指定從站的保持暫存器40001的資料"""
    try:
        # 使用client.read_holding_registers函式讀取保持暫存器
        result = client.read_holding_registers(0, 1, slave_address)
        # 檢查result是否為ModbusIOException,如果是,則直接處理異常,不嘗試訪問registers屬性
        if isinstance(result, ModbusIOException):
            raise result  # 重新丟擲異常以便在外部統一處理

        print(f"Slave {slave_address}: {result.registers[0]}")
    except ConnectionException as e:
        # 如果連線問題或無此從站,則捕獲異常並列印資訊
        print(f"Error connecting to or reading from Slave {slave_address}: {e}")
    except ModbusIOException as e:
        # 其他Modbus通訊錯誤
        print(f"Error communicating with Slave {slave_address}: {e}")
    except NoSuchSlaveException as e:
        # NoSuchSlaveException
        print(f"NoSuchSlaveException with Slave {slave_address}: {e}")


if __name__ == "__main__":
    # 初始化TCP客戶端,這裡以預設埠502為例
    client = ModbusTcpClient('localhost', port=502)  # 請將'localhost'替換為實際的Modbus TCP伺服器IP地址

    # 連線到Modbus TCP裝置
    if client.connect():
        print("Connected to Modbus TCP device.")

        # 迴圈遍歷從站地址1至247
        for slave_address in range(1, 248):
            read_holding_registers(client, slave_address)
            time.sleep(0.200)  # 延遲200毫秒

        # 關閉連線
        client.close()
    else:
        print("Failed to connect to the Modbus TCP device.")

相關文章