#!/usr/bin/env python

"""
File: set_reg.py
Desc: set a specific register to a specific value
"""
__author__ = '0xRoM'
from argparse import ArgumentParser, ArgumentTypeError
from pyModbusTCP.client import ModbusClient
import time
import sys

parser = ArgumentParser()
parser.add_argument('-i','--ipaddress', action='store', type=str, required=True, help='Input IP Address')
parser.add_argument('-p','--port', action='store', type=int, required=False, help='Port Number', default=502)
parser.add_argument('-r','--reg', action='store', type=int, required=True, help='Register Number', default=0)
parser.add_argument('-v','--val', action='store', type=int, required=True, help='Register Value', default=0)
parser.add_argument('-l','--loop', action='store_true', required=False, help='loop on')
parser.add_argument('-t','--timeout', action='store', type=float, required=False, help='request every X seconds', default=2)
args = parser.parse_args()

client=ModbusClient(host=args.ipaddress,port=args.port,auto_open=True,auto_close=True,timeout=10)
client.write_single_register(args.reg,args.val)
client.close()

if args.loop:
    i=1 
    while True:
        client=ModbusClient(host=args.ipaddress,port=args.port,auto_open=True,auto_close=True,timeout=10)
        client.write_single_register(args.reg,args.val)
        client.close()
        print '\r>>packet: %d' % i,
        sys.stdout.flush()
        i+=1
        time.sleep(args.timeout)

