Communicating with external applications over TCP/IP socket /websockets using gateway scripts

Sure, we use it all the time where Ignition is the client. Use it to connect to devices, MES, printers.... Acting as a client is easy.... server is a bit harder. Our MES is all XML over TCP and we have load tested with millions of transactions per day with no issues.

Super simple send only in Jython using Java TCP

from java.net import Socket, InetSocketAddress
from java.io import DataOutputStream
def printZPL(zpl, ip):
	
	zpl = zpl.encode('utf-8')
	port = 9100

	try:
		printer = Socket()
		printer.connect(InetSocketAddress(ip, port), 2000)
		outPrinter = DataOutputStream(printer.getOutputStream())
		outPrinter.write(zpl)
		outPrinter.close()
		printer.close()
		
		return True
	except IOError:
		return False

Send/Recieve XML over TCP Socket in Jython

import socket, xml.etree.cElementTree as ET, xmltodict


def connect(server):
	"""
	connect : Create a socket and connect
	"""
	
	# Create a python socket
	sock = socket.socket()
	
	# Set the timeout to something reasonable so our program does not lockup
	sock.settimeout(5)
	
	# Connect
	server_address = (server, 1000)
	sock.connect(server_address)
	
	# Return the socket for further use
	return sock
	

def recv(sock):
	"""
	recv : Recieve the response
	"""
	
	# Setup a var to hold the return data
	total_data=[]
	
	# Recieve the data until no more data is returned
	sock.settimeout(45)
	while True:
		data = sock.recv(4096)
		if not data: break
		total_data.append(data)
		
	# Join all the data recieved into a single string
	resp = ''.join(total_data)
		
	# Return the response
	return resp
	
def submit(xml, ip='127.0.0.1', raw_resp=0):
	"""
	submit : Submit an XML request
	"""
	
	# Connect 
	try:
		ets = connect(ip)
		logger.trace("Connecting to %s" % ip)
	except:
		return formatResp( xmlResp(0, "Failed to create a socket to %s.", ip))
	
	# Convert the XML to a string
	requestXML = ET.tostring(xml, 'UTF-8')
	
	# Send the XML string to the open socket
	ets.sendall(requestXML)
	
	# Recieve the response
	try:
		responseXML = recv(ets)
		logger.trace("Got response from %s, %s" % (ip, responseXML))
	except Exception, e:
		return formatResp( xmlResp(0, "Failed to recieve response from socket. %s" % e, ip))
	
	# Close the connection
	ets.close()

	# Format the response
	response = formatResp(responseXML)
	
	# Return the response data
	return response

4 Likes