XScript Manual · Chapter 50

SYS — System Functions

SYS is the object that groups the system functions QMS provides. Call a function as SYS.Start() and read a property without parentheses, as in SYS.IsRunning. Frequently used functions such as logs, messages and error alarms are provided as built-in system functions that are called directly, without an object name.

Unknown SYS function or property names and wrong argument counts are reported at build time (Compile diagnostics).

Example

xscript
SYS.LogSystemInfo();
 
if( SYS.IsRunning == true )    // IsRunning is a property — read it without parentheses
{
   Log("Machine Is Running State");
}
else
{
   Log("Machine Is Stop State");
}
 
string crntState = SYS.RunState;
Log("Current State = {0}", crntState);
if( crntState == "Stop" )
{
   SYS.Start();
}

Methods

Built-in system functions (called without a prefix)

These functions are called directly, without an object name. Adding SYS., as in SYS.Log(…), works the same — except ShowError · FormatString, which are called without SYS..

  • A format argument is a .NET format string whose {0} · {1} placeholders take the following arguments.
  • Message and error codes are numbers registered in the Message Error Editor. An unregistered code or code 0 is reported as a warning at build time.
  • For the button-set constants EB_* and the result constants ER_*, see the constants table below.
xscript
string lotId = "LOT-01";
Log("Start Lot = {0}", lotId);
LogError("Vacuum timeout : {0} ms", 3000);
 
// Message window — compare the pressed button with ER_*
if( ShowMessage(EB_YesNo, 1001) == ER_Yes )
{
   RunManualThread("Loader", "ManualHome");
}
 
// Error alarm ( code 2001 ) — shows the window and continues on the next line
ShowError(EB_Retry, 2001, "Station = {0}", ModuleName);
MethodDescription
Log(string format, …)Write to the log
LogError(string format, …)Write an error log
LogDebug(string format, …)Write to the log (kept as a normal log, the same as Log)
string FormatString(string format, …)Build and return a formatted string
Sleep(int msec)Wait for the given time (ms). Wakes early when the system is shutting down (Exit)
bool WaitRun()Wait until START while the sequence is stopped — Sequence steps and threads
int ShowMessage(int buttonSet, int code) · int ShowMessage(int buttonSet, string message)Show a message window. Returns the pressed button (ER_*)
int ShowMessageFormat(int buttonSet, string format, …)Show a message window from a format string
int ShowTimerMessage(int buttonSet, int code) · int ShowTimerMessage(int buttonSet, string format, …)Message that closes by itself after a while. The time is GUI.TimerMessageShowTime (ms)
int ShowWarning(int code, …) · int ShowWarning(string format, …)Warning window (OK button, no buzzer)
ShowError(int buttonSet, int code, string format="", …)Raise an error alarm — puts the machine into the error state, shows the window and continues on the next line without waiting. Called without SYS.
int ShowErrorWait(int buttonSet, int code, string format="", …)Raise an error alarm and wait for a button. Returns the pressed button (ER_*)
bool ClearAlarm(int code)Clear the active alarms with that code (true if any were cleared)
bool RegisterAlarmHandler(string module, string function)Register an alarm recovery function
bool LogEvent(string name, string message)Record to the event list only, without any window
bool RunThread(string module, string function [, arg])Run another module's function on its own thread (at most one argument)
bool RunManualThread(string module, string function [, int messageCode])Run a function as a manual operation (a progress message code can be given, default 64)
bool SetNextStep(string module, string step)Set the next step a module runs

Button-set and result constants — for constants in general, see Language Basics.

ConstantUse
EB_Ok EB_OkCancel EB_YesNo EB_YesNoCancel EB_Retry EB_Skip EB_RetrySkip EB_Reset EB_Ignore EB_Yes EB_No EB_Cancel EB_None EB_NoWaitPassButton set of a message / error window (first argument of ShowMessage · ShowError)
ER_Ok ER_Cancel ER_Yes ER_No ER_Retry ER_Skip ER_Reset ER_Ignore ER_Fail ER_TimeEnd ER_NoWaitPassButton pressed in a message window (compare with the return value of ShowMessage · ShowErrorWait)

Data & parameters

For the parameter prefixes (JF. · SS. · MS. · RD.) and reading / writing values see Parameter; for the global variables (G_*) see Global variables.

MethodDescription
bool LoadGlobalData()Load the stored global data (production counts, LOT state and run times — G_LoadCount · G_LotCount · G_RunTime …). QMS calls it automatically when a project is opened
bool SaveGlobalData()Save the global data to the SYS.GlobalDataFilePath file. QMS calls it automatically when a project is closed
bool SetParamValue(string dataName, int|double|bool|string value)Set a parameter value. dataName includes its prefix, such as "SS.CamCalibX" (checked at build time). To keep it in the file, save with SaveParam or SaveSingleParam
bool SetParamValue(string dataName)Pass the current value of the parameter variable (SS.Name …) on as the edit value to save (the form used by screen input controls)
bool GetParamValue(string dataName, ref int|double|bool|string value)Read a parameter value into value (name with its prefix). False for an unknown name
bool SaveSingleParam(string dataName)Save only one parameter to the file (e.g. "SS.AutoPrint"). Unsaved values of other parameters being edited are left as they are
bool SaveParam(string managerKey)Save parameters to the file. managerKey : JF job file · SS system setup · MS master setup · RD RUN data
bool LoadParam(string managerKey)Load parameters from the file (managerKey as above)
bool SaveJobFileParam() · bool LoadJobFileParam()Save / load the job file parameters. Saving also saves the job file vision information; loading runs the OnJobFileLoaded event afterwards
bool SaveSetupParam() · bool LoadSetupParam()Save (including the system vision information) / load the system setup parameters
bool SaveMasterParam() · bool LoadMasterParam()Save / load the master setup parameters
bool SaveRunParam() · bool LoadRunParam()Save / load the RUN data
bool SaveSysVisionInfo()Save the information of the System Vision objects
bool SaveJobVisionInfo()Save the information of the JobFile Vision objects
bool ChangeJobFile(string jobName, bool showMsg=true) 4.0+Switch to and load another job file. jobName is a job file folder name under XJobFile (e.g. "Default.JOB"). Runs the OnJobFileLoaded event after loading. With showMsg=false it switches without the success notice (a failure is still shown). False on failure

Machine & module control

MethodDescription
void Start()Start every sequence of the machine
void Stop()Stop every sequence of the machine
void SetError(string module="")Put the machine into the error state (module = the module name to put into error)
void ResetError()Clear the error state of the machine
void Exit()Terminate every sequence of the machine
void StartStepRun()Start the whole machine in step-run mode
void StartModule(string module) · void StopModule(string module)Start / stop a specific module
void SetModuleError(string module) · void ResetModuleError(string module)Put a specific module into error / clear its error
void ExitModule(string module)Terminate a specific module
void StartModuleStepRun(string module)Start a specific module in step-run mode
void ExitMonitorModule()Terminate the monitor modules
void SetModuleBackground(string module, bool value)Mark a sequence module as a background module — it is left out of SequenceModuleCountOnRunning
string GetCurrentStep(string module) 4.0+Name of the step a sequence module is running now. Empty string when the module does not exist
int GetCurrentStepIndex(string module) 4.0+Index (from 0) of the step running now. -1 when the module does not exist
string GetCurrentThreadModule() 4.0+Name of the module whose sequence thread is running the current code. Empty string on manual, RunThread, screen-event and timer threads; calling another module's function (Module::Function) does not change it — use it to tell who called a function shared by a sequence and a manual operation
bool RunManualThread(string moduleName, string functionName, int messageCode=64)Run the given module's function manually (messageCode = message number shown while running). A built-in system function, so it can be called without SYS.. Returns false without running while the machine is running or another manual operation is running
void StopManualThread()Request a manual stop — sets ManualThreadExitSignal to true. The manual function itself must check the signal and stop
int GetThreadCount(string threadName) · int GetThreadCount(string moduleName, string seqOrFuncName)Number of running threads with that name. The second form counts Module::Name threads — use it to check whether a function thread started with RunThread is still running
bool RunScriptFunction(string module, string function) · bool RunScriptFunction(string module, string function, string|int|long|double|bool data)Run another module's function and return its bool return value (false when it does not return a bool or cannot run). At most one argument; module and function names are looked up at run time
xscript
FUNCTION LoadModuleData(string moduleName, string data)
{
   if( SYS.RunScriptFunction(moduleName, "ParseJsonToModuleData", data) == false )
   {
      ShowError(EB_Ok, 107, moduleName);
      return false;
   }
   return true;
}

Note The run rules of WaitRun · SetNextStep · RunThread · RunManualThread, and how to use GetCurrentStep · GetCurrentThreadModule, are covered in Sequence steps and threads. When another module's function name is fixed, calling Module::Function() is simpler than RunScriptFunction and its name and arguments are checked at build time (Functions).

Thread synchronisation

Synchronisation objects, identified by name, for sequences and threads that share a resource. Events and semaphores were added in 4.0.

MethodDescription
bool EnterCriticalSection(string name)Enter a critical section (created if missing). Other threads wait until the owner leaves
bool ExitCriticalSection(string name)Leave a critical section. False when the current thread does not own it
bool TryEnterCriticalSection(string name, int timeout=0)True when entered within timeout (ms)
bool IsEnteredCriticalSection(string name)Whether the current thread owns that critical section
bool ExitAllCriticalSection()Leave every critical section owned by the current thread
bool CreateEvent(string name, bool manualReset=true, bool initialState=false) 4.0+Create an event (left as it is when it already exists)
bool SetEvent(string name) · bool ResetEvent(string name) 4.0+Signal the event (waiting threads wake up) / reset it
bool WaitEvent(string name, int timeout=-1) 4.0+Wait for the signal (-1 = forever). True when signalled, false on timeout
bool RemoveEvent(string name) 4.0+Remove the event
bool CreateSemaphore(string name, int initialCount, int maxCount) 4.0+Create a semaphore
bool WaitSemaphore(string name, int timeout=-1) · bool ReleaseSemaphore(string name) 4.0+Acquire / release the semaphore
int GetSemaphoreCount(string name) · bool RemoveSemaphore(string name) 4.0+Remaining entry count (-1 for a name never created) / remove the semaphore
  • SetEvent · ResetEvent · WaitEvent create a manual-reset event when the event does not exist.
  • A semaphore must be created with CreateSemaphore first. WaitSemaphore · ReleaseSemaphore on a name never created return false.

Caution Do not wait with WaitRun() while holding a critical section — monitors and manual operations that use the same name stop for the whole stop (Sequence steps and threads).

Motor bulk control

MethodDescription
void SetSpeedAll(string speed)Change the speed of every motor to the configured value. speed : HOME · MAINT (= JOG) · RUN (case-insensitive)
void SetSpeedAll(string speed, int percent)Change the speed of every motor to percent % of the configured value (acceleration / deceleration stay as configured)
void ClearAlarmAll()Clear the alarms of every motor (takes about one second while the alarm-clear signal is pulsed)
void SetServoOnAll(bool on)Servo signal of every motor ON / OFF
void ResetMotorHomeDoneAll()Clear the Home Done signal of every motor
void StopMotorAll()Decelerate and stop every motor
void StopMotorEmgAll()Emergency-stop every motor
int GetAlarmCount()Number of motors in alarm
array GetMotorNames()Names of the registered motors
array GetIoNames()Names of the registered IOs

Paths

MethodDescription
string Combine(string path1, string path2, string path3="", string path4="")Join up to four paths. A leading \ of the later paths is dropped before joining
bool IsFullPath(string path)Whether the path is absolute (starts with a drive or \)
string MakeFullPath(string pathname)Convert a relative path to an absolute path based on the QMS executable folder (an empty string gives the executable folder)
string GetAbsolutePath(string baseFolder, string path)When path is relative, make it a path under baseFolder
string GetRelativePath(string baseFolder, string path)When path is under baseFolder, return only the part below it (case-insensitive; otherwise unchanged)
string GetFileName(string path)Last part of the path (file name + extension). Empty for a path ending in \
string GetFileNameWithoutExtension(string path)File name without the extension
string GetDirectoryName(string path)Folder path without the last part (C:\Data\a.txt → C:\Data)
string ChangeFileExt(string filepath, string ext)Path with the extension replaced (ext includes the dot, as in ".txt")
string GetUpdateFileName(string filename)Path with _Update added to the file name (a.json → a_Update.json)
string GetValidFileName(string fileName)Replace characters not allowed in a file name with _ (an empty string gives yyyyMMdd_HHmmss)
string GetCurrentDirectory()Current working folder

Files & folders

MethodDescription
bool ExistsFile(string path)Whether a file exists
bool CreateFile(string path)Create an empty file at the given location (a file you write content to is created by WriteAllText etc., so there is no need to create it first)
bool DeleteFile(string file)Delete a single file
bool CopyFile(string sourceFileName, string destFileName, bool overwrite)Copy a file
bool CopyFiles(string srcDir, string filePattern, string destDir, bool overwrite)Copy the files in srcDir matching filePattern (e.g. *.csv) to destDir. Files with the same name are always overwritten (the overwrite argument is not applied)
bool MoveFile(string source, string target, bool overwrite=True)Move a file. Fails when source does not exist, or when target exists and overwrite is false
bool RenameFile(string source, string target, bool overwrite=True)Rename a file (same behaviour as MoveFile)
bool SetFileHidden(string filePath, bool setHidden=true)Set / clear the hidden attribute of a file
void DeleteFiles(string dir, int remainCount)Sort the file names in the folder ascending and delete all but the last remainCount (sub-folders are not looked at — with date-style names the oldest files go first)
bool IsJsonFile(string filepath)Whether the file is JSON — judged by whether the first line is a single { or [
bool Execute(string file, string param)Run a file (start a program, or open a document with its associated program)
void OpenExplorer(string path)Open Explorer — for a file, opens with the file selected; otherwise opens the GetDirectoryName(path) folder (end the path with \ to open the folder itself)
bool ExistsDirectory(string path)Whether a folder exists
bool CreateDirectory(string path)Create a folder (including all intermediate folders)
bool DeleteDirectory(string path, bool recursive)Delete a folder (recursive = sub-folders and their files too)
bool ForceDeleteDirectory(string path, bool recursive)Force delete — with recursive=true, clears the attributes (read-only …) of the files and folders inside before deleting. True when the folder does not exist
bool MoveDirectory(string sourceDirName, string destDirName)Move a folder
bool CopyDirectory(string source, string destination, bool overwrite=True)Copy a whole folder including sub-folders
array GetDirectories(string path)Every folder at the given location (full paths)
array GetDirectories(string path, string searchPattern)Folders matching the pattern. Sub-folders are not searched
array GetDirectories(string path, string searchPattern, bool subDirectory)Folders matching the pattern (subDirectory = search sub-folders too)
array GetFiles(string path)Every file at the given location (full paths)
array GetFiles(string path, string searchPattern)Files matching the pattern. Sub-folders are not searched
array GetFiles(string path, string searchPattern, bool subDirectory)Files matching the pattern (subDirectory = search sub-folders too)

Text file read & write

MethodDescription
string ReadAllText(string path)Read a file and return it as a string (empty on failure)
array ReadAllLines(string path)Read a file and return it line by line. Also reads a file another program has open
bool WriteAllText(string path, string data)Write a string to the file (existing content is overwritten)
bool WriteAllLines(string path, array data)Write a list of strings to the file, one per line
bool AppendAllText(string path, string data)Append a string to the end of the file
bool AppendAllLines(string path, array data)Append a list of strings to the end of the file, one per line
bool AppendLine(string path, string data)Append a string followed by \r\n to the end of the file

The write and append functions create the file when it does not exist, and the parent folder when it is missing. The encoding is UTF-8 (without BOM).

xscript
FUNCTION LoadMachineJson()
{
   string file = SYS.Combine(SYS.ProjectBaseDirectory, "JSON\\cube_machine.json");
   if( SYS.ExistsFile(file) == false )
   {
      LogError($"Not found: {file}");
      return false;
   }
   string text = SYS.ReadAllText(file);
   return true;
}

Network (HTTP)

The HTTP functions return the response string, or "[HTTP-ERROR]" (SYS.HTTP_ERROR_STR) on failure. They do not stop with an exception, so compare the return value with SYS.HTTP_ERROR_STR to tell success from failure. When the server returns an error response, its body is kept in SYS.LastHttpError (empty for a timeout or connection failure — the reason is only logged). A token is sent as an Authorization: Bearer header. The per-call response timeout timeoutMs was added in 4.0.

MethodDescription
string SendHttpPost(string url, string data, string token="", string type="", int timeoutMs=10000)Send data with an HTTP POST. type = content type (empty = application/json), timeoutMs = response timeout (ms)
string SendHttpGet(string url, string token="", int timeoutMs=10000)Fetch data with an HTTP GET
string SendHttpPatch(string url, string data, string token="", string type="application/json", int timeoutMs=10000)HTTP PATCH
string SendHttpDelete(string url, string token="", int timeoutMs=10000)HTTP DELETE
bool SendHttpPostFireAndForget(string url, string data, string token="", string type="", int timeoutMs=1000) 4.0+Send a POST in the background and return at once. No result is reported — for status reports the sequence must not wait for. False when the send queue is full
PropertyTypeDescription
HTTP_ERROR_STRstringString returned when an HTTP function fails ("[HTTP-ERROR]")
LastHttpErrorstringBody of the error response received by the last HTTP function (empty for a timeout or connection failure)
xscript
FUNCTION ReportMachineStatus(string data)
{
   string url = SS.MachineApiServer + "/machine-status";
   string result = SYS.SendHttpPost(url, data, SS.HttpToken);
   if( result == SYS.HTTP_ERROR_STR )
   {
      LogError($"ERROR: {SYS.LastHttpError}");
      return false;
   }
   return true;
}

Real-world example — query the order count while timing the response.

xscript
FUNCTION GetServerOrderCount()
{
   string url = $"{SS.HttpOrderAddr}/order-queue/machines/{SS.MachineId}/status";
   int s = SYS.TickCount;
   string data = SYS.SendHttpGet(url, SS.HttpToken, 3000);   // fails when there is no response within 3 s
 
   if( data == SYS.HTTP_ERROR_STR )
   {
      if( SS.OrderMode == 1 )
      {
         LogError($"GetServerOrderCount Error :[{SYS.GetElasped(s)}ms] {SYS.LastHttpError}");
      }
      return -1;
   }
 
   int count = Order::GetOrderCount(data);
   return count;
}

Time & timers

MethodDescription
int GetTickCount()Time elapsed since the system started (ms). Wraps back to 0 about every 24.8 days
int GetElasped(int start)Time (ms) elapsed since start (a GetTickCount() or TickCount value read earlier). Correct across the wrap to 0
double GetTime()High-resolution timer value (ms, with fractions). Use the difference of two readings to time short intervals (it is not the time of day)
string GetDateTimeStringFormat(string format)Current date and time in the given .NET format (e.g. "yyyy-MM-dd HH:mm:ss")
string ConvertSecondsToTimeString(int sec)Seconds as an "HH:mm:ss" string (e.g. 3725 → "01:02:05")
string GetAdjustedDate(string dateString, int offset)Add offset days to a date string (yyyyMMdd …) and return it as yyyyMMdd. An unreadable date counts from today
bool SetBoost(bool silent=false)Set the system timer resolution to 0.5 ms (so Sleep(1) sleeps close to 1 ms). QMS calls it itself at start-up and when its window is activated. silent=true skips the log and the check wait
bool ResetBoost()Release the resolution set by SetBoost, back to the Windows default
void NtSetTimerResolution(uint DesiredResolution, bool SetResolution, ref uint CurrentResolution)Set the system timer resolution directly (DesiredResolution = value to set, SetResolution = whether to apply it, CurrentResolution = current value — in units of 100 ns)
xscript
int start = SYS.TickCount;
Sleep(500);                            // the operation to time
int elapsed = SYS.GetElasped(start);   // correct even when TickCount wraps to 0
Log($"Elapsed: {elapsed} ms");

System information & diagnostics

MethodDescription
void LogSystemInfo()Log the current system information (OS · PC name · processor count …)
void LogVersionInfo()Log the project name, version and file, the QMS version and the script engine
void AddMemoryLog()Log memory, handle and thread usage (a warning log when a limit is exceeded)
void AddThreadIdLog(string prefix, string log="")Log the current thread ID (for debugging; the log argument is not used)
void SetDebugLog(bool use) 4.0+Whether QMS debug logs are written. The default is on (true); use it to reduce repeated flow logs in production (e.g. SYS.SetDebugLog(G_DebugLog) in the Init script). The script's LogDebug writes a normal log and is not affected
long GetAvailableRamSize()Available memory (bytes). 0 for a few seconds right after QMS starts
long GetTotalMemorySize()Installed physical memory (bytes)
long GetProcessMemorySize() · long GetManagedMemorySize()Working memory of the QMS process / .NET managed memory (bytes)
string GetExeFileVersion()QMS executable version and build time (the same value as SYS.QMSVersion)
string GetExeAssemblyVersion()Assembly version of the QMS executable (major version only — e.g. "4.0.0")
bool IsVisualStudioRunning(bool update=false)Whether Visual Studio is running. With update=false the result of the first check is returned; true checks again
bool CheckAsyncKeyDown(int vKey)Whether a key (virtual key code) is held down (also true when it was pressed since the last check)
short GetAsyncKeyState(int vkey)Keyboard key state (the Windows GetAsyncKeyState value)
string GetScriptEngine() 4.0+Name of the script engine in use. On 4.0 it is always "NewBytecode"
bool SetScriptEngine(string mode)Confirm the script engine. Engine selection was removed, so it accepts only "NewBytecode" (true without changing anything when it is already ready); any other value ("Legacy" …) returns false
bool UpdateCustomData(string command, int index)Call the user-data update handler registered by a project-specific C# extension. False when no handler is registered

Sound, random numbers & hashes

MethodDescription
bool PlaySound(string fileName)Play a wav file. A relative path is looked up from the Media folder of the project folder; false when the file does not exist
bool PlaySoundLoop(string fileName)Play a wav file in a loop (same path rule as PlaySound)
bool StopSound()Stop the sound being played
int GetRandom()Random number from 0 up to (not including) the int maximum
int GetRandom(int min, int max)Random number from min up to (not including) max
double GetRandomDouble()Random real number from 0 up to (not including) 1
string GetSha256Hash(string input)SHA-256 hash of the string (UTF-8), as 64 lowercase hex characters
ushort CalcCRC16(byte[] data, int length)Modbus CRC-16 of the first length bytes. Pass a byte buffer; the result is an integer

Name existence checks

MethodDescription
bool CheckIOName(string name)Checks whether an IO with that name exists
bool CheckMotorName(string name)Checks whether a motor with that name exists
bool CheckCylinderName(string name)Checks whether a cylinder with that name exists
bool CheckIntefaceName(string name)Checks whether a communication driver with that name exists (use the function name exactly as spelled: Inteface)
bool CheckDeviceContainerName(string name)Checks whether a device container with that name exists

Module variable read & write

Write and read another module's variable given as a "Module::Variable" string. An array element is given as "Module::Array[i]". A name written directly as a string is checked at build time for its module and variable. When the name is fixed, writing Module::Variable directly, as in Loader::WorkCount, is simpler (Functions).

MethodDescription
bool SetModuleVar(string name, int|double|bool|string value)Write a module variable (name in the "Loader::WorkCount" format). Numbers go only to int · long · double variables, bool only to bool variables and strings only to string variables; false on a type mismatch or an unknown variable
bool GetModuleVar(string name, ref int|long|double|bool|string value)Read a module variable into value. False for an unknown variable or a type mismatch

UPH

MethodDescription
void ClearUphData()Clear the UPH data
void AddUphData(int uph)Add a measured UPH value (the latest UphDataMaxCount values are kept)
int GetAverageUph()Average of the kept UPH values (0 when there are none)

Linear converter (LINEAR)

Put (x, y) points into a conversion table identified by index (0 ~ 999); the points are joined by straight lines to convert x ↔ y. Outside the points, the end segments are extended.

  • A new table holds the three points (0, 0) · (1, 1) · (2, 2), so it converts y = x. Clear it with LINEAR_ClearData before adding your own data.
  • Add points so that x and y keep moving in the same direction as the first two points (both increasing or both decreasing). A point that changes direction is not added and returns false.
  • When the result of LINEAR_GetValueY falls outside -1000 ~ 1000, it is clamped to the limit and false is returned.
MethodDescription
bool LINEAR_ClearData(int index)Clear one conversion table
bool LINEAR_AddData(int index, double x, double y)Add the point (x, y)
bool LINEAR_GetValueY(int index, double x, ref double y)The y for x
bool LINEAR_GetValueX(int index, double y, ref double x)The x for y

Load cell (LOADCELL)

For each index (0 ~ 999), link a motor and an analog input IO, and convert voltage ↔ pressure with (voltage, pressure) points. The conversion works the same way as the linear converter. For analog inputs see AIO.

MethodDescription
bool LOADCELL_SetConfig(int index, string motorName="", string readDevName="")Configure a load cell — the motor name and the analog input IO name to link. The conversion data is cleared
bool LOADCELL_ClearData(int index)Clear the conversion data
bool LOADCELL_AddData(int index, double volt, double pressure)Add a (voltage, pressure) point
bool LOADCELL_ConvertVoltToPressure(int index, double volt, ref double pressure)Convert a voltage into a pressure
bool LOADCELL_ConvertPressureToVolt(int index, double pressure, ref double volt)Convert a pressure into a voltage
bool LOADCELL_ReadVoltage(int index, ref double value)Current voltage of the linked analog input (average of 10 readings)
bool LOADCELL_ReadPressure(int index, ref double value)Read the current voltage and convert it into a pressure
bool LOADCELL_WaitPressure(int index, double target, int timeout=1000, bool highPressureStop=true)Wait until the pressure reaches the target. With highPressureStop=true it returns true at or above target, with false at or below. False after timeout (ms)
bool LOADCELL_MoveToPressure(int index, double targetPressure, double moveOffset, bool highPressureStop=true, double motorSpeed=0.0)Move the linked motor relatively by moveOffset; when the pressure reaches the target, emergency-stop it and return true. False when the move ends before the target is reached. With motorSpeed above 0 the motor moves at that speed

Properties

Properties are read without parentheses. Properties marked "(settable)" are meant to be changed by scripts. The HTTP properties are in the network section above.

Date & time

PropertyTypeDescription
DateStringstringCurrent date yyyyMMdd
TimeStringstringCurrent time HHmmss
DateTimeStringstringCurrent date and time yyyyMMdd_HHmmss (down to sec)
DateTimeFilenamestringCurrent date and time yyyyMMdd_HHmmss_fff (down to msec — for file names)
DateTimeMsecStringstringSame format as DateTimeFilename
MsecTimeStringstringCurrent time HHmmss_fff (down to msec)
CurrentDateTimeInISO8601stringISO 8601 format (e.g. 2024-12-03T12:34:56.123+09:00)
Year · Month · DayintCurrent year / month / day
Hour · Minute · Second · MillisecondintCurrent hour / minute / second / millisecond
TickCountintSame value as GetTickCount() (ms)
SecondCountintTickCount in seconds
RunTimeString · StopTimeString · IdleTimeString · ErrorTimeStringstringAccumulated machine RUN / STOP / IDLE / ERROR time (HH:mm:ss)

Machine state & manual operation

PropertyTypeDescription
IsRunningboolWhether the machine is running (RUN)
RunStatestringCurrent machine state — "None" · "Stop" · "Run" · "Error" · "Exit"
SequenceModuleCountOnWaitingintNumber of sequence modules waiting (not running a step)
SequenceModuleCountOnRunningintNumber of sequence modules running a step (background modules excluded)
IsProjectOpenboolWhether a project is open
DesignModeboolTrue when Visual Studio (devenv) is running on this PC (not whether a QMS editor screen is open)
ManualThreadRunboolWhether a manual operation is running
ShowManualStopButtonbool (settable)When true, a STOP button appears on the manual progress message window. RunManualThread sets it back to false when it starts, so turn it on inside the manual function
ManualThreadExitSignalbool (settable)Becomes true with the STOP button of the manual progress window or StopManualThread(). The manual function checks it and ends itself (RunManualThread sets it to false when it starts)

Errors, versions & paths

PropertyTypeDescription
LastErrorCodeintCode of the last error alarm raised (-1 at first)
LastErrorMsgstringLast error message raised (message:sub-message format)
LastErrorModuleNamestringName of the module where the last error was raised
ErrorTraceInfostringScript error information
ProjectVersionstringVersion of the current project
QMSVersionstringQMS version (e.g. "4.0.9 (261117_0032)" — the build time follows the version)
ProjectBaseDirectorystringFolder that holds the project file (.xmp)
JobFileNamestringJob file name including sub-folders from the job file root
AppDataFolderPathstringQMS data folder (%APPDATA%\QMachineStudio)
GlobalDataFilePathstringPath of the global data file (XGlobalData.XDF under AppDataFolderPath)
DownloadsFolderPathstringDownloads folder of the current user
UphDataMaxCountint (settable)Maximum number of UPH samples used (default 100, at most 10000)

License

For license types and conditions see License.

PropertyTypeDescription
HaveLicenseboolWhether the license is valid
TrialLicenseEnabledboolWhether a trial license is active
HaveProjectCodeLicenseboolWhether the project code license condition is met (true for a project without a project code)
LicenseKeyCountintNumber of keys registered in the license
LicenseMotorCountintNumber of motors included in the license
LicensePermitRemainDaysintDays remaining on the license

Project statistics (SYS.Stat*) 4.0+

Read-only properties with the counts of the project's parts. The values were counted at the last build (the same values as the project statistics screen in the Project menu) and are not recounted on each read, so reading them in a sequence loop costs nothing. They are 0 before the first build, so check SYS.StatUpdated first when needed.

xscript
if( SYS.StatUpdated == true )
{
   Log($"modules={SYS.StatModuleCount}, io={SYS.StatIoCount}, motors={SYS.StatMotorCount} ( {SYS.StatUpdatedTime} )");
}
GroupProperties (all int unless a type is shown)
Statusbool StatUpdated (counted yet) · string StatUpdatedTime (time counted, "yyyy-MM-dd HH:mm:ss")
ModulesStatModuleCount · StatSequenceModuleCount · StatViewModuleCount · StatLibraryModuleCount · StatEventModuleCount · StatInitModuleCount · StatMonitorModuleCount · StatDataModuleCount · StatSubModuleCount · StatDisabledModuleCount
CodeStatFunctionCount · StatStepCount · StatScriptLineCount · StatVariableLineCount · StatFunctionLineCount · StatStepLineCount · StatScriptFileCount · StatDesignFileCount · StatCompiledFileCount · long StatScriptBytes
Variables · parametersStatVariableCount · StatGlobalVariableCount · StatModuleVariableCount · StatParamVariableCount · StatConstantCount · StatParameterCount · StatSetupParamCount · StatMasterParamCount · StatJobParamCount · StatVisionParamCount · StatRunParamCount
ScreensStatGuiControlCount · StatGuiControlKindCount · StatGuiControlMaxDepth · StatGuiLangTextCount · StatGuiImageCount · long StatGuiImageBytes
DevicesStatIoCount · StatIoInputCount · StatIoOutputCount · StatIoAnalogInputCount · StatIoAnalogOutputCount · StatIoBoardCount · StatMotorCount · StatMotorEnabledCount · StatCylinderCount · StatTowerLampCount · StatCommCount · StatDeviceContainerCount
VisionStatCameraCount · StatCameraEnabledCount · StatVisionToolCount · StatVisionImageCount
OtherStatDriverCount · StatLibraryCount · StatCustomLibCount · StatDatabaseCount · StatMessageCount · StatErrorCodeCount
Subscribe