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.
// Link the MES receive event — runs OnReceiveFromServer(data) of the "MES" module for every packet receivedCOM["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;}
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 arrivesbool ReplyReceived = false; // whether a reply arrivedbool ReplyOk = false; // whether the reply is OKstring LastCommand = ""; // the last command sentint 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;}
Received data and connection events arrive in the script functions named in the properties below. Each function takes one argument (string data).
Link property
Called when
Value passed to the function
LinkModuleName
Name of the module that holds the functions below — required
—
OnParseFunctionName
Once 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
OnTcpIpClientConnectFunctionName
A TCP/IP client connects to the server
An empty string
OnReadFunctionName
Only 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.
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
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)
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
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
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 readFUNCTION 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);}
Method
Description
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)
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();}
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.
Communication address (the IP address for TCP/IP) (read / write)
PortName
string
Port — the COM port name for serial, the port number for TCP/IP (read / write)
BaudRate
int
Serial baud rate (read / write)
IsBaudRateFix
bool
Whether the baud rate is fixed
OpenOnStart
bool
Whether to connect immediately when the project opens (read / write)
Url · AccessKey · SecretKey · Region
string
Address · 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 · MaxChannel
int
Current channel · maximum channel (read / write)
IsChannel
bool
Whether this communication object supports channels (read only)
MaxValue · MinValue
int
Maximum · minimum settable value for a light controller — 255 · 0 by default (read / write)
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.