Pythonによるmodbus TCP通信の方法をご紹介します。
Modbusとは?
ModbusはModicon社が1979年、同社のプログラマブルロジックコントローラ (PLC) 向けに策定したシリアル通信プロトコルである。産業界におけるデ・ファクト標準の通信プロトコルとなり、現在では産業用電子機器を接続する最も一般的手段となっている。
Wikipediaより
条件
- Ubuntu 16.04 LTS
 - Python 3.5.2
 
使用するライブラリ
pyModbusTCPというライブラリを使用します。
詳細は以下のサイトを参照してください。
https://pypi.org/project/pyModbusTCP/
インストール
以下のコマンドを実行してインストールします。
$ sudo pip install pyModbusTCP
接続サンプル
ホストを指定して接続し、読み込んだレジスタを表示するサンプルを実行します。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# read_register
# read 10 registers and print result on stdout
# you can use the tiny modbus server "mbserverd" to test this code
# mbserverd is here: https://github.com/sourceperl/mbserverd
# the command line modbus client mbtget can also be useful
# mbtget is here: https://github.com/sourceperl/mbtget
from pyModbusTCP.client import ModbusClient
import time
SERVER_HOST = "target_host" # 接続先ホスト
SERVER_PORT = 502
c = ModbusClient()
# uncomment this line to see debug message
#c.debug(True)
# define modbus server host, port
c.host(SERVER_HOST)
c.port(SERVER_PORT)
while True:
    # open or reconnect TCP to server
    if not c.is_open():
        if not c.open():
            print("unable to connect to "+SERVER_HOST+":"+str(SERVER_PORT))
    # if open() is ok, read register (modbus function 0x03)
    if c.is_open():
        # read 10 registers at address 0, store result in regs list
        regs = c.read_holding_registers(0, 10)
        # if success display registers
        if regs:
            print("reg ad #0 to 9: "+str(regs))
    # sleep 2s before next polling
    time.sleep(2)
出典:https://github.com/sourceperl/pyModbusTCP/blob/master/examples/read_register.py
実行結果
接続に成功すると以下のように表示されます。
$ python3 read_register.py reg ad #0 to 9: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] reg ad #0 to 9: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] reg ad #0 to 9: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] reg ad #0 to 9: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] reg ad #0 to 9: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] reg ad #0 to 9: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] reg ad #0 to 9: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] reg ad #0 to 9: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
詳細な使用方法
pyModbusTCPの詳細な使用方法は以下のサイトをご参照ください。

