-
Notifications
You must be signed in to change notification settings - Fork 0
/
modbus_client.py
60 lines (47 loc) · 1.74 KB
/
modbus_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python
# coding: utf-8
# In[2]:
#!/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
#SERVER_HOST = "127.0.0.1"
#SERVER_PORT = 502
# uncomment this line to see debug message
#c.debug(True)
# define modbus server host, port
from pyModbusTCP.client import ModbusClient
import time
def modbus_com(SERVER_HOST,SERVER_PORT,function_code,start_register,amount_of_registers):
c = ModbusClient()
c.host(SERVER_HOST)
c.port(SERVER_PORT)
cnt=0
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():
if function_code == "3":
# Read the amount_of_registers from start_register
regs = c.read_holding_registers(int(start_register), int(amount_of_registers))
# if success display registers
if regs:
print("reg address" +str(start_register)+ "to" +str(int(start_register)+int(amount_of_registers)-1)+":"+str(regs))
elif function_code == "16":
#Future support
pass
cnt+=1
if cnt>=2:
print("クライアント通信終了")
c.close()
break
# sleep 1s before next polling
time.sleep(1)
# In[ ]: