XScript Manual · Chapter 16

COMMUNICATION — communication devices

COM["name"] accesses a communication device registered in the Com Driver Editor (serial · TCP server/client · UDP · Modbus · cloud, …). Send data with WriteStr · WriteStrRaw; received packets arrive in a script function linked in advance. What a device can do depends on its driver. A function the driver does not implement does nothing, and most of them log a message and return false · 0 · an empty string. To test a communication directly on screen, use the Communication screen.

Example

xscript
// Link the MES receive event — runs OnReceiveFromServer(data) of the "MES" module for every packet received
COM["MES"].LinkModuleName = "MES";
COM["MES"].OnParseFunctionName = "OnReceiveFromServer";
 
// When used as a TCP/IP client, the function run when it connects to the server ( same LinkModuleName module, the argument is an empty string )
COM["MES"].OnTcpIpClientConnectFunctionName = "OnClientConnected";
 
FUNCTION OnReceiveFromServer(string data)
{
   Log("SCRIPT READ :'{0}'", data);
 
   // process the comma-separated items one by one
   array arrItems = STR.ParseCommaString(data);
   int itemCount = arrItems.Count - 1;
   string lineData = "";
   string paramName = "";
   string paramValue = "";
 
   int i = 0;
   for( i, 0, itemCount )
   {
      lineData = arrItems[i];
      if( lineData == "" )
      {
         continue;
      }
 
      // split the name and value separated by ':'
      array param = STR.ParseSplitString(lineData, ":");
      paramName = param[0];
      paramValue = param[1];
 
      // TodoSomething is assumed to be a user FUNCTION defined in this module
      bool ret = TodoSomething(paramName, paramValue);
      if( ret == false )
      {
         continue;
      }
   }
   return true;
}
 
FUNCTION OnClientConnected(string data)
{
   Log("MES client connected");
   return true;
}
 
FUNCTION SendToServer(string data)
{
   if( COM["MES"].WriteStr(data) == false )
   {
      // Send Fail
      return false;
   }
   // Send Success
   return true;
}

Real-world — send a command and wait for the reply

A TCP client sends a command, then waits, with a time limit, until the receive function gets the reply and marks it in module variables. Send is called from a sequence step or similar and the receive function runs on the communication receive thread, but both see the same module variables. That is why COM["Cube"].LinkModuleName is set to this module.

xscript
// Module variables — filled by the receive function when a reply arrives
bool   ReplyReceived = false;   // whether a reply arrived
bool   ReplyOk       = false;   // whether the reply is OK
string LastCommand   = "";      // the last command sent
int    TCP_TIMEOUT   = 3000;    // reply wait time ( ms )
 
// Receive function — link it by setting COM["Cube"].LinkModuleName to this module
// and OnParseFunctionName to "OnCubeReceive"
FUNCTION OnCubeReceive(string data)
{
   array items = STR.ParseCommaString(data);
   ReplyOk = ( items[0] == "OK" );
   ReplyReceived = true;
   return true;
}
 
FUNCTION bool Send(int unit, string cmd, string data, bool wait)
{
   if( COM["Cube"].IsOpen() == false )
   {
      return false;
   }
 
   ReplyReceived = false;
   string sendData = $"{unit},{cmd}";
   if( STR.IsNullOrWhiteSpace(data) == false )
   {
      sendData = sendData + "," + data;
   }
   LastCommand = cmd;
 
   // WriteStr adds the start · end delimiters ( STX · ETX by default )
   if( COM["Cube"].WriteStr(sendData) == false )
   {
      return false;
   }
 
   if( wait == false )
   {
      return true;
   }
 
   // Wait up to TCP_TIMEOUT until the receive function sets ReplyReceived to true
   int waited = 0;
   while( ReplyReceived == false )
   {
      if( waited >= TCP_TIMEOUT )
      {
         return false;
      }
      Sleep(20);
      waited = waited + 20;
   }
 
   return ReplyOk;
}

Linking receive and connect functions

Received data and connection events arrive in the script functions named in the properties below. Each function takes one argument (string data).

Link propertyCalled whenValue passed to the function
LinkModuleNameName of the module that holds the functions below — required—
OnParseFunctionNameOnce for each packet split from the received data by the start · end delimiters (when the driver handled that packet successfully)The packet string without the delimiters
OnTcpIpClientConnectFunctionNameA TCP/IP client connects to the serverAn empty string
OnReadFunctionNameOnly when the driver uses this name (e.g. message reception in the ZeroMQ driver)The received data
  • The function name is looked up in the LinkModuleName module on every call, so it can be set at any time. If the module or function does not exist, only an error is logged and nothing is called.
  • The receive function runs on the communication receive thread. The next packet is processed only after the function returns, so keep long waits (long Sleep · wait functions) out of it.

Methods

Connection

MethodDescription
bool Open(void)Starts the communication (opens the serial port · starts the TCP server · connects the TCP client, …). A TCP client keeps trying to connect in the background and returns the connection state after about 0.5 s
void Close(void)Stops the communication (Close · Disconnect)
bool IsOpen(void)Returns whether the communication is open — for serial, whether the port is open; for a TCP server, whether the server has started; for a TCP client, whether it is connected to the server
bool IsLiveConnection(void)True if it is open and the driver's link test is healthy (IsLinkTestOk) — checks that data is actually flowing
bool OpenTcpIpServer(void)Starts the server of a TCP/IP device (waits for connections on the port number in PortName)
void CloseServer(void)Stops the server of a TCP/IP device
bool IsOpenServer(void)Returns whether the server of a TCP/IP device has started
void SetPort(string portName)Changes the port. An open serial port is closed first, so call Open() again
bool SetUse(bool use) / bool GetUse() 4.0+Changes or reads whether the device is used. Turned off with SetUse(false), an unused device is not connected automatically and raises no connection-failure notice. The value is not saved in the project, so set it in OnProjectOpened or similar, which runs before the automatic connection when the project opens

Send · receive

MethodDescription
bool WriteStr(string data)Sends data with the start and end delimiters added (e.g. STX + DATA + ETX). If the start delimiter is empty, only the end delimiter is added. Returns false when not open or when data is empty
bool WriteStrRaw(string data)Sends data as is, without any processing
bool SendCustomData(string data)Sends in the way the driver defines. If the driver does not implement it, it is the same as WriteStrRaw
bool SendCustomData(string group, string data)Sends with a group name (must be implemented in the communication DLL)
bool SendCommand(string command, string data="")Sends a command defined by the driver
string ReceiveCustomData(string option="")Receives in the way the driver defines (e.g. the AWS SQS driver). option is an option string for processing the data
bool Parse(string data)Interprets a received packet in the driver's way. Called automatically for each packet when received data is split
void SeparateData(void)Splits received data by the start and end delimiters and runs Parse and the OnParseFunctionName function for each packet (normally called automatically on reception)
void StartCustomReadThread(void) / void StopCustomReadThread(void)Starts / stops the thread that calls ReadCustom periodically
bool ReadCustom(void)Calls the read function defined in the driver

Values · channels (instruments · light controllers)

MethodDescription
bool SetValue(double value)Sets a value on the device. The meaning and unit of the value are defined by the driver
double GetValue(bool wait=false)Reads a value from the device. wait sets whether to wait for the response
bool SetChannelValue(int channel, double value)Sets the value of the given channel
bool SetChannelAll(double value)Sets the same value on every channel
double GetChannelValue(int channel)Reads the value of the given channel
void SetChannelMinMaxValue(int channel, double min, double max)Sets the min / max values of the given channel

Data store

Reads and writes the data groups (name-value pairs per group) created by the driver.

MethodDescription
bool GetData(string groupName, string name, ref bool|int|double|string data)Gets the value name of group groupName into the data variable. Returns false when the group or name does not exist, or when the variable type differs from the stored value type
bool SetData(string groupName, string name, bool|int|double|string data)Puts the value name into group groupName. Returns false when the group does not exist

Other

MethodDescription
string GetDesc(void)Returns the description defined in the driver
string ToString(void)Returns the driver information as ClassName,Name,Address,Port
int GetCount(void)Returns a count defined by the driver (e.g. the AWS SQS driver returns the number of queued messages). 0 for drivers that do not implement it
bool SetCustomConnectionParameters(void)Used when the driver sets its own connection parameters
void IdleCheckFunc(void)Idle check function — called once by the internal timer when nothing has been sent with WriteStr for IdleCheckTimeSec (what it does is defined by the driver)
void SendLinkTest(void)Sends the driver's link test. With UseLinkTest on, the internal timer calls it each time LinkTestTimeMsec passes after the last send

Modbus data read / write

Register and coil read / write functions implemented by the Modbus TCP · Modbus RTU drivers. Called on a driver that does not implement them, they log Function not defined and return false. Array functions take a script array variable, and the values a read function fills in are written back to that array after the call 4.0+. Create a read array in advance with at least as many elements as you read (if it is smaller, false is returned).

xscript
array coils[8] = {OFF};   // create it with the size to read
 
FUNCTION bool ReadCoils()
{
   if( COM["ModBus"].ReadDataBitArray(/*slave*/1, /*startAddress*/0, /*count*/8, /*ref output*/coils) == false )
   {
      LogError("ReadDataBitArray failed");
      return false;
   }
   Log($"coil0 = {coils[0]}, coil7 = {coils[7]}");
 
   // Write several coils with one request ( Modbus function code 15 )
   array outs = {ON, OFF, ON, ON};
   return COM["ModBus"].WriteDataBitArray(/*slave*/1, /*startAddress*/16, outs);
}
MethodDescription
bool ReadDataBit(int slave, int startAddress, ref bool output)Read one coil
bool ReadDataBitArray(int slave, int startAddress, int count, array output)Read several coils
bool ReadInputDataBit(int slave, int startAddress, ref bool output)Read one input bit ( discrete input )
bool ReadInputDataBitArray(int slave, int startAddress, int count, array output)Read several input bits ( discrete inputs )
bool ReadDataWord(int slave, int startAddress, ref int output)Read one holding register ( 16 bit )
bool ReadDataInt(int slave, int startAddress, ref int output)Read two registers as a 32-bit integer
bool ReadDataWordArray(int slave, int startAddress, int count, array output)Read several holding registers
bool ReadInputDataWord · ReadInputDataInt · ReadInputDataWordArrayRead input registers ( same arguments as above )
bool WriteDataBit(int slave, int registerAddress, bool value)Write one coil
bool WriteDataBitArray(int slave, int startAddress, array values) 4.0+Write several coils with one request ( function code 15 — no half-written state when one write fails midway )
bool WriteDataWord(int slave, int registerAddress, int value)Write one register
bool WriteDataWordArray(int slave, int startAddress, array values)Write several registers

When the device rejects a write ( exception response ), the function returns false and logs the reason.

AWS S3 key storage (XDriver_CommAwsS3 1.0.1~)

Do not write AWS keys in project files (.XDF · .xmp) or scripts — committing, deploying or backing up the project spreads the key (4.1.34~). Take the key from a password box on screen (PasswordBox) and keep it encrypted on this PC only with SaveCredential. It is encrypted with Windows DPAPI, so only the Windows user who saved it can decrypt it, and only on that PC (%LOCALAPPDATA%\QMachineStudio\AwsS3Credentials.dat). A loaded key is not put into the public AccessKey · SecretKey properties — a key in those two properties is written in plain text to XData\LocalSysConfig.XDF when the project is saved. A complete example is ViewRun.xms in SampleProject\Communication\CloudAWS_S3_Sample.

xscript
string AwsCredProfile = "MyLine_S3"          // storage name on this PC ( one per project )
 
FUNCTION OnSaveKeyClick(string sender, int tag , array params)
{
   string accessKey = CONTROL["ViewRun::pwAccessKey"].Password;
   string secretKey = CONTROL["ViewRun::pwSecretKey"].Password;
   CONTROL["ViewRun::pwAccessKey"].Password = "";   // clear the boxes right away
   CONTROL["ViewRun::pwSecretKey"].Password = "";
 
   bool saved = COM["AwsS3"].SaveCredential(AwsCredProfile, accessKey, secretKey);
   accessKey = "";
   secretKey = "";
   return saved;
}
 
FUNCTION Connect()
{
   COM["AwsS3"].AccessKey = "";                     // keep the properties saved with the project empty
   COM["AwsS3"].SecretKey = "";
   COM["AwsS3"].Region = SS.CloudRegion;
 
   if( COM["AwsS3"].LoadCredential(AwsCredProfile) == false )
   {
      ShowMessage(EB_Ok, 1100);                      // "Enter the AWS key in the settings" ( project message )
      return false;                                  // no key - do not call S3
   }
   return COM["AwsS3"].Open();
}
SignatureDescription
bool SaveCredential(string profile, string accessKey, string secretKey)Encrypt the key on this PC and load it for use. false if the format is wrong (key values are never logged)
bool LoadCredential(string profile)Decrypt the saved key for the next Open(). false if missing or saved by another user or PC (a connection made with that name's key is closed too)
bool ClearCredential(string profile)Delete the saved key, and close a connection made with it
bool HasCredential(string profile)Whether a key is saved (does not decrypt it)
string GetCredentialHint(string profile)"****ABCD" for display (last 4 of the access key), "" if none
bool UseAwsCredentialChain (property)If true and there is no key, look in the AWS environment variables (AWS_ACCESS_KEY_ID · AWS_SECRET_ACCESS_KEY), then the %USERPROFILE%\.aws\credentials profile. Default false
string AwsProfileName (property)That profile name. Empty uses the AWS_PROFILE environment variable, then default. Restart QMS if the profile file was created while QMS was running
string CredentialSource (read)Where the key of the last connection came from : Project · Stored:name · Environment · Profile:name

Key order used by Open() : ① the AccessKey + SecretKey properties (unchanged old behavior) → ② the key from LoadCredential → ③ the AWS standard locations when UseAwsCredentialChain is on. Before a connection, or after a failed one, UploadFile · DownloadFile · DoesRemoteFileExist return false without calling S3.

Properties

Connection settings

PropertyTypeDescription
NamestringName of the communication object
ClassNamestringClass name of the communication driver
AddressstringCommunication address (the IP address for TCP/IP) (read / write)
PortNamestringPort — the COM port name for serial, the port number for TCP/IP (read / write)
BaudRateintSerial baud rate (read / write)
IsBaudRateFixboolWhether the baud rate is fixed
OpenOnStartboolWhether to connect immediately when the project opens (read / write)
Url · AccessKey · SecretKey · RegionstringAddress · AccessKey · SecretKey · Region of a CLOUD driver (read / write). Values put in AccessKey · SecretKey are written in plain text to XData\LocalSysConfig.XDF when the project is saved — for AWS S3 use the key storage above
CurrentChannel · MaxChannelintCurrent channel · maximum channel (read / write)
IsChannelboolWhether this communication object supports channels (read only)
MaxValue · MinValueintMaximum · minimum settable value for a light controller — 255 · 0 by default (read / write)

Packet · data handling

PropertyTypeDescription
PacketStartDelimiterstringStart value of a valid packet — STX (0x02) by default. When empty, packets are split by the end delimiter only (read / write)
PacketEndDelimiterstringEnd value of a valid packet — ETX (0x03) by default (read / write)
MinDataSizeintMinimum data size — received data shorter than this is not split yet and more data is awaited (read / write)
DataDelimiterstringDelimiter that separates data — , by default (read / write)
ValueDelimiterstringDelimiter that separates a name from a value — = by default (read / write)
FilterstringCommunication data filter — e.g. the subscription topic of the ZeroMQ driver (read / write)
UseDebugLogboolWhether detailed debug logs are written (read / write)

State · checks

PropertyTypeDescription
StartedboolTrue after Open() is called until Close() — separate from whether the connection succeeded (read only)
ResponseOkboolWhether valid communication data was received — changes only with drivers that use it (e.g. Mewtocol)
OnIdleboolWhether it is idle because nothing was sent with WriteStr for IdleCheckTimeSec — returns to false at the next WriteStr
IsLinkTestOkboolWhether the link test is healthy — true while valid packets keep arriving within LinkTestTimeMsec plus a margin. Updated only while UseLinkTest is on
UseLinkTestboolWhether the internal link test is used (read / write)
LinkTestTimeMsecintInterval at which the link test runs — 1000 ms by default (read / write)
UseIdleTimeOutboolWhether idle detection and the idle check are used (read / write)
IdleCheckTimeSecintTime after which it counts as idle — 10 s by default (read / write)
UseInternalTimerboolWhether the timer for internal checks (idle timeout · link test, …) is used (read / write)
PropertyTypeDescription
LinkModuleNamestringName of the module in which the linked functions are defined (read / write)
OnParseFunctionNamestringName of the function that handles received packets (read / write)
OnTcpIpClientConnectFunctionNamestringName of the function run when a TCP/IP client connects to the server (read / write)
OnReadFunctionNamestringName of the function run when data is received — works only with drivers that use this name (read / write)

Notes

  • Always put a time limit on a loop that waits for a reply (see the real-world example above). If the receive function is never called, the loop never ends.
  • For server API (HTTP) calls use SYS.SendHttpGet · SYS.SendHttpPost · SYS.SendHttpDelete, not COM. On failure they return SYS.HTTP_ERROR_STR ("[HTTP-ERROR]") — see SYS — system functions.
  • For parameters marked ref and for array arguments, pass a variable, not a value, to get the result back — see FUNCTION · ref parameters.
Subscribe