是一種新興且廣泛使用的高階程式語言,易學易用的特性使其成為程式開發者的理想入門程式,也是樹莓派 Raspberry PI  中 'PI' 的由來。

在許多工業控制中,針對現場 MODBUS TCP Server 控制點的運算或資料交換必須透過 監控系統軟體 (SCADA) 來進行,其實利用 Python 的 pyModbusTCP 庫,即可輕易達成。

本文以樹莓派內建的 python 程式參考 https://pypi.org/project/pyModbusTCP/ 做說明:

  1. 安裝 pyModbusTCP :執行  sudo pip install pyModbusTCP 指令以進行安裝,必須注意樹莓派內同時具備 python 2 與 python 3 兩個版本,因此為了確認安裝的版本 以 "sudo pip2 install pyModbusTCP" 指令 安裝 python 2 版本, "sudo pip3 install pyModbusTCP" 指令 安裝 python 3 版本" 
  2. 編輯 py 程式,例如 mbservertest.py 範例程式如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# install pyModbusTCP ref: https://pypi.org/project/pyModbusTCP/

from pyModbusTCP.client import ModbusClient
import time
HOST1 = "192.168.0.109"
PORT1 = 502

HOST2 = "192.168.0.110"
PORT2 = 502

c1 = ModbusClient()
c2 = ModbusClient()

# uncomment this line to see debug message
#c1.debug(True)
#c2.debug(True)

# define modbus server host, port
c1.host(HOST1)
c1.port(PORT1)
#set UID to 1
c1.unit_id(1)

c2.host(HOST2)
c2.port(PORT2)
c2.unit_id(1)

while True:
    # open or reconnect TCP to server
    if not c1.is_open():
        if not c1.open():
            print("unable to connect to "+HOST1+":"+str(PORT1))

    if not c2.is_open():
        if not c2.open():
            print("unable to connect to "+HOST2+":"+str(PORT2))

    # if open() is ok, read register (modbus function 0x03)
    if c1.is_open() and c2.is_open():
        # read 32 registers at address 0, store result in regs list
        regs = c1.read_holding_registers(0, 32)
        if regs:
            #write regs) to c2 address 0 (32 registers)
            c2.write_multiple_registers(0,regs)
            #print(regs)
    # sleep 2s before next polling
    time.sleep(2)

3. 執行 python3 mbservertest.py 指令 即可將程式中 TCP Server 192.168.0.109:502 UID 1 REG0~REG31 複製到 192.168.0.110:502 UID 1 REG0~REG31

必須注意 以程式直接發送 TCP 封包,如果沒有適當的時間延遲,可能造成 Server 設備或網路超出負荷,因此除了讀取本身(127.0.0.1)以外 time.sleep() 函數內的數值建議不要小於 0.1 (0.1秒)

範例程式可以在 https://goo.gl/M3BkXf 下載

關於 pyModbusTCP 的進一步應用說明,可以參考 http://pymodbustcp.readthedocs.io

補充說明: python 也可以直接在 Windows 作業環境下執行,可以自 https://www.python.org/downloads/%20windows/ 下載安裝檔即可