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).
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();}
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 lineShowError(EB_Retry, 2001, "Station = {0}", ModuleName);
Method
Description
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)
For the parameter prefixes (JF. · SS. · MS. · RD.) and reading / writing values see Parameter; for the global variables (G_*) see Global variables.
Method
Description
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
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)
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
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
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
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).
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).
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)
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)
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
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.
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
Property
Type
Description
HTTP_ERROR_STR
string
String returned when an HTTP function fails ("[HTTP-ERROR]")
LastHttpError
string
Body 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 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
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 timeint elapsed = SYS.GetElasped(start); // correct even when TickCount wraps to 0Log($"Elapsed: {elapsed} ms");
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
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).
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
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.
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.
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)
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 are read without parentheses. Properties marked "(settable)" are meant to be changed by scripts. The HTTP properties are in the network section above.
Current machine state — "None" · "Stop" · "Run" · "Error" · "Exit"
SequenceModuleCountOnWaiting
int
Number of sequence modules waiting (not running a step)
SequenceModuleCountOnRunning
int
Number of sequence modules running a step (background modules excluded)
IsProjectOpen
bool
Whether a project is open
DesignMode
bool
True when Visual Studio (devenv) is running on this PC (not whether a QMS editor screen is open)
ManualThreadRun
bool
Whether a manual operation is running
ShowManualStopButton
bool (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
ManualThreadExitSignal
bool (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)
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.