#this is a script to inject data as a read response into the master PLC using MODBUS ASCII

import time
import serial

#function to perform the LRC(logitudinal redunancy check) of a string of data
#an LRC is composed by taking the 2's compliment of the sum of every byte in the string
def LRC(data):	
	length = len(data)/2	#because each 2 chars of a python string make a byte, we need a loop of len/2 to add all the bytes
	lrc = 0
	for l in range(length):
		temp1 = data[l*2]			
		temp2 = data[l*2+1]
		temp3 = temp1 + temp2	#adds two bytes
		tempInt = int(temp3,16)	
		lrc += tempInt
		lrc &= 0xFF
		if(lrc > 0xFF):		#makes sure it stays a byte
			lrc -= 0x100	
	lrc ^= 0xFF	#two's compliment
	lrc += 1	#two's compliment
	lrc &= 0xFF 
	if(lrc > 0xFF):
		lrc -= 0x100	#makes sure it stays a byte
	temp = str(hex(lrc))
	lrc = temp[2] + temp[3]	#take out the "0x" from the hex string
	return lrc
	
if __name__ == "__main__":
	ser = serial.Serial('/dev/ttyUSB1',timeout = 0.1)
	count = 0
	stationAddress = "04"
	functionCode = "10"
	writeAddress = "0BE9"
	numRegisters = "0012"
	numBytes = "24"
	data = "00010000000000010000000041A00000720000003EE8CE70000000003EDC28F63F4CCCCD"
	lrcPacket = stationAddress + functionCode + writeAddress + numRegisters + numBytes + data
	lrc = LRC(lrcPacket)
	CRLF = "\r\n"
	packet = ":" + stationAddress + functionCode + writeAddress + numRegisters + numBytes + data + lrc + CRLF
	while(1):   
		print "writing request #" + str(count) +"\n" + packet		
		ser.write(packet)
		count +=1
		received = ser.readline()
		if(received != 0):
			print "received response #" + str(count) +"\n" + received
		time.sleep(0.5)
		#if((received[0]+received[1]+received[2]+received[3]+received[4]) == ":0403"):	
			#packet = injectedPacket			
			#print "read reqest received\n" + received + "response packet #"  + str(count) + "\n" + packet + "\n"			
		#elif((received[0]+received[1]+received[2]+received[3]+received[4]) == ":0410"):	
			#packet = ":04100BE90012E6"
			#print "write request received\n" + received + "response packet #" + str(count) + "\n" +":04100BE90012E6\n"
		
		
		

