import sys
from pymodbus.client.sync import ModbusTcpClient
#from https://ctftime.org/writeup/31455

client = ModbusTcpClient(sys.argv[1])

for unit in range(32):
    for address, register in enumerate(client.read_holding_registers(0, 99, unit=unit).registers):
        if register != 0:
            print(f"hr {unit} {address} {register}")

for unit in range(32):
    for address, register in enumerate(client.read_input_registers(0, 99, unit=unit).registers):
        if register != 1:
            print(f"ir {unit} {address} {register}")

for unit in range(32):
    for address_base in range(0, 2999, 256):
        for address_index, coil in enumerate(client.read_coils(address_base, min(256, 2999 - address_base), unit=unit).bits[:min(256, 2999 - address_base)]):
            if coil != False:
                print(f"c {unit} {address_base + address_index} {coil}")

for unit in range(32):
    for address_base in range(0, 2999, 256):
        for address_index, coil in enumerate(client.read_discrete_inputs(address_base, min(256, 2999 - address_base), unit=unit).bits[:min(256, 2999 - address_base)]):
            if coil != True:
                print(f"di {unit} {address_base + address_index} {coil}")
