Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Description

This example shows how to write to and or read from an XCON (TCP, UDP, etc.) connection. The connection can be handled with LUA function. The write value can be written from any selected item, and the read value also be written to an output item.
The read function handles the incoming values and converts them into a hex dump string. 

This tutorial has two functions: 

  • Send_TcpHex(): used to send HEX values of an Item in this example : ('NETx\\VAR\\String\\Item001') to the Server which has IP address : 127.0.0.1 and Port : 23. More info about xcon.SendHex

  • MyTCP_OnReceiveEvent(data, size, sourceip, sourceport):

     This

     This callback function is invoked when an XCON connection has been established.

    Create

    Implement a callback function for each connection to monitor and name it accordingly, e.g. for connection

    "MyTCP"create the functionMyTCP

    named MyTCP implement the callback function MyTCP_OnReceiveEvent().

LUA
Code Block
title
languageapplescriptluaLUA
function OnStartEvent() -- this is a predefined callback function, add only the following line to the function.
	xcon.CreateTCP("MyTCP","0",0,"127.0.0.1",23) --Remote Server:127.0.0.1, Remote Port:23
end


function Send_TcpHex()
	local var = nxa.GetValue('NETx\\VAR\\String\\Item001') --Send value NETx\VAR\String\Item001
	xcon.SendHex("MyTCP", var)
end


function MyTCP_OnReceiveEvent(data, size, sourceip, sourceport)
	local val= string.tohex(data)
	nxa.SetValue('NETx\\VAR\\String\\Item002',val) --Received value NETx\VAR\String\Item002
end

function string.tohex(str)
    return (str:gsub('.', function (c)
        return string.format('%02X', string.byte(c))
    end))
end


Next, define a server task that is triggerd upon changes of the source item, NETx\VAR\String\Item001 –  – That is, to send data the LUA function is invoked: the source item value is treated as a hex dump string, converted into binary data and sent to the connection.Image Removed

...

Info

...

Note:

The MyTCP_OnReceiveEvent() callback function is invoked when data is received on the established XCON connection named MyTCP. The actual setup of the connection is done in the OnStartEvent() callback function.

Image RemovedImage Added