XScript Manual · Chapter 16

title: "COMMUNICATION — TCP / Serial / HTTP" chapter: 16

COMMUNICATION — channel control

COM["name"] accesses a channel registered in the Communication Editor (TCP server/client, serial, Modbus, MES, AWS S3, …). Attach event functions for asynchronous receive/connect, send with WriteStr or SendCustomData.

Basic example

// Hook receive event
COM["MES"].LinkModuleName = "MES";
COM["MES"].LinkFunctionName = "OnReceiveFromServer";
 
// Hook connected event
COM["MES"].ConnectedLinkModuleName = "MES";
COM["MES"].ConnectedLinkFunctionName = "OnConnected";
 
FUNCTION OnReceiveFromServer(string data)
{
    Log("READ: '{0}'", data);
 
    array items = STR.ParseCommaString(data);
    for (i, 0, items.Count - 1)
    {
        string line = items[i];
        if (line == "")
        {
            continue;
        }
 
        array pair = STR.ParseSplitString(line, ":");
        string name = pair[0];
        string value = pair[1];
 
        if (TodoSomething(name, value) == false)
        {
            continue;
        }
    }
    return true;
}
 
FUNCTION SendToServer(string data)
{
    if (COM["MES"].WriteStr(data) == false)
    {
        return false;
    }
    return true;
}

Real-world — TCP client framing

Adapted from TcpClient.xms. Builds a length+unit+payload frame, sends, and waits for response with timeout.

FUNCTION Send(int unit, string cmd, string data, bool wait)
{
    if (COM["Cube"].IsOpen() == false)
    {
        return false;
    }
 
    int unit_no = Common::GetUnitNo(unit);
    ResponseOk = false;
    string sendData;
 
    if (STR.IsNullOrWhiteSpace(data))
    {
        sendData = MakeSendData(unit_no, cmd);
    }
    else
    {
        sendData = MakeSendData(unit_no, cmd + "," + data);
    }
 
    LastCommand = cmd;
 
    if (COM["Cube"].WriteStr(sendData) == false)
    {
        return false;
    }
 
    if (wait == false)
    {
        return true;
    }
 
    int start = SYS.GetTickCount();
    while (true)
    {
        if (ResponseOk)
        {
            break;
        }
        Sleep(20);
        if (SYS.GetTickCount() - start > TCP_TIMEOUT)
        {
            return false;
        }
    }
 
    return ReplyOk;
}

Key methods

Connection

SignatureDescription
bool Open(void)Open channel
void Close(void)Close
bool IsOpen(void)Connected flag
bool IsLiveConnection(void)Live check
bool OpenTcpIpServer(void) / void CloseServer(void) / bool IsOpenServer(void)Server mode
int GetCount(void)Connected clients

Send

SignatureDescription
bool WriteStr(string data)Send framed
bool WriteStrRaw(string data)Send raw
bool SendCustomData(string data)Custom format
bool SendCustomData(string group, string data)Grouped
bool SendCommand(string command, string data = "")Command

Receive / parse

SignatureDescription
string ReceiveCustomData(string option = "")Custom receive
bool Parse(string data)Run registered parser
void SeparateData(void)Frame split
string GetData(string name) / bool SetData(string name, string value)Receive map
void StartCustomReadThread(void) / void StopCustomReadThread(void)Read thread
bool ReadCustom(void)One-shot read

Channel values (instrumentation)

SignatureDescription
bool SetValue(double value) / double GetValue(bool wait = false)Single value
bool SetChannelValue(int channel, double value)Per-channel write
double GetChannelValue(int channel)Per-channel read
bool SetChannelAll(double value)All channels
void SetChannelMinMaxValue(int channel, double min, double max)Channel range

Misc

SignatureDescription
bool SetCustomConnectionParameters(void)Re-apply params
void SetPort(string portName)Serial port
void IdleCheckFunc(void)Idle callback
void SendLinkTest(void)Link-test frame
string GetDesc(void) / string ToString(void)Info strings

Key properties

PropertyTypeDescription
Name / ClassNamestringIdentity
Address / PortName / BaudRate / IsBaudRateFixConnection
Url / AccessKey / SecretKey / RegionstringHTTP/S3
OpenOnStartboolAuto open
FilterstringReceive filter
MinDataSizeintMin frame
CurrentChannel / MaxChannel / IsChannelMulti-channel
PacketStartDelimiter / PacketEndDelimiter / DataDelimiterstringFrame delimiters
MaxValue / MinValueintValue range
IdleCheckTimeSec / LinkTestTimeMsecintPeriods
UseDebugLog / UseLinkTest / UseIdleTimeOut / UseInternalTimerboolOptions
OnIdle / IsLinkTestOk / ResponseOkboolState

Event-function contract

FieldFired on
LinkModuleName + LinkFunctionNameReceive
ConnectedLinkModuleName + ConnectedLinkFunctionNameConnect state change
OnParseFunctionNameCustom parser

Tips

  • Receive callbacks run on the communication thread — marshal to UI via dispatcher.
  • Never while(true) wait — track elapsed with SYS.GetTickCount().
  • Binary protocols: use WriteStrRaw + PacketStartDelimiter/EndDelimiter.
  • Prefer SYS.SendHttpGet/Post/Delete helpers for REST, and always check SYS.HTTP_ERROR_STR.