import binascii
from scapy.all import *
import socket

def send_receive(s,pack):
	BUFFER_SIZE = 1024
	try:
		s.send(pack)
		data = s.recv(BUFFER_SIZE)
	except:
		return False
	return data

def first_parse_response(response,output):
	value=hex(response[7])
	if (value == "0x32"):
		output["Module"]=response[43:43+19].decode()
		output["Basic_Hardware"]=response[71:71+19].decode()
		output["Version"]="%s.%s.%s"%(response[122],response[122+1],response[122+2])
		return output
	else:
		return False


def second_parse_response(response,output):
	value=hex(response[7])
	offset = 0
	szl_id = hex(response[30])
	if (value == "0x32"):
		if( szl_id != "0x1c" ):
			offset = 4
	output["System Name"]=((response[39+offset:].split(b"\x00",1))[0]).decode()
	output["Module Type"] =((response[73+offset:].split(b"\x00",1))[0]).decode()
	output["Serial Number"]=((response[175+offset:].split(b"\x00",1))[0]).decode()
	output["Copyright"]=((response[141+offset:].split(b"\x00",1))[0]).decode()
	return output


def action(host,port):
	output={}
	cotp=binascii.unhexlify('0300001611e00000001400c1020100c2020102c0010a')
	alt_COTP = binascii.unhexlify("0300001611e00000000500c1020100c2020200c0010a")
	ROSCTR_Setup = binascii.unhexlify("0300001902f08032010000000000080000f0000001000101e0")
	Read_SZL = binascii.unhexlify("0300002102f080320700000000000800080001120411440100ff09000400110001")
	first_SZL_Request = binascii.unhexlify("0300002102f080320700000000000800080001120411440100ff09000400110001")
	second_SZL_Request = binascii.unhexlify("0300002102f080320700000000000800080001120411440100ff090004001c0001")
	response=None
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	try:
		s.settimeout(3)
		s.connect((host,port))
	except:
		return False
	response=send_receive(s,cotp)
	if(response):
		if(hex(response[5])!="0xd0"):
			s.close()
			s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			s.connect((host,port))
			response=send_receive(s,alt_COTP)
			if(response):
				if(hex(response[5])!="0xd0"):
					return False
	response  = send_receive(s,ROSCTR_Setup)
	if(response):
		if(hex(response[7])!="0x32"):
			return False
	response  = send_receive(s,Read_SZL)
	if(response):
		if(hex(response[7])!="0x32"):
			return False
	response  = send_receive(s, first_SZL_Request)
	try:
		output = first_parse_response(response,output)
	except:
		return False
	response = send_receive(s, second_SZL_Request)
	output=second_parse_response(response,output)
	output["DeviceIP"]=host
	output["Port"]=port
	return output



def get_info(ip,port):
	return(action(ip,port))