-
Notifications
You must be signed in to change notification settings - Fork 0
/
adrchanger.py
74 lines (63 loc) · 1.86 KB
/
adrchanger.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Ugly code following!
import array
import pymodbus
import serial
import argparse
from pymodbus.pdu import ModbusRequest
from pymodbus.client import ModbusSerialClient as ModbusClient #initialize a serial RTU client instance
from pymodbus.transaction import ModbusRtuFramer
#import logging
#logging.basicConfig()
#log = logging.getLogger()
#log.setLevel(logging.DEBUG)
baudrate = 38400
parity = 'N'
port = "/dev/ttyUSB0"
global newAdr
def probe():
try:
client = ModbusClient(method = "rtu", port = port, stopbits = 1, bytesize = 8, parity = parity, baudrate = baudrate, timeout=0.5)
connection = client.connect()
result0 = client.read_coils(2000,1,slave=unit)
client.close()
except:
print ("Serial error. Is "+port+" available?")
client.close()
else:
try:
result0.string
except:
client.close()
return True
else:
client.close()
print("Client unreachable!")
return False
def chAdr():
client = ModbusClient(method = "rtu", port = port, stopbits = 1, bytesize = 8, parity = parity, baudrate = baudrate)
try:
connection = client.connect()
adrReg = client.read_holding_registers(1000,1,slave=unit)
result = client.write_register(1000,newAdr,slave=unit)
adrReg = client.read_holding_registers(1000,1,slave=unit)
if adrReg.registers[0] == newAdr:
print("Write: ok")
result = client.write_register(1001,16727,slave=unit)
print("Store: ok")
except:
print("Failed!")
try:
adrReg = client.read_holding_registers(1000,1,slave=newAdr)
print("Verification: pass")
print("New address: "+str(newAdr))
except:
print("Verification failed!")
client.close()
parser = argparse.ArgumentParser()
parser.add_argument("address", type=int, help="device's current address")
parser.add_argument("newAddress", type=int, help="new device address")
args = parser.parse_args()
unit = args.address
newAdr = args.newAddress
if probe():
chAdr()