XScript Manual · Chapter 50

SYS — system global object

SYS bundles system-level utilities — time, files, HTTP, module execution. It is the single most-used global and unifies OS access for scripts.

Time / ticks

Property / MethodTypeDescription
SYS.TickCountintElapsed ms since startup
SYS.GetTickCount()intSame, as function
SYS.GetElasped(int startTick)intTickCount - startTick
SYS.SecondCountintSeconds counter
SYS.Year / Month / Day / HourintCurrent date/time parts
SYS.DateStringstringYYYYMMDD
SYS.TimeStringstringHHMMSS
SYS.DateTimeStringstringYYYYMMDD_HHMMSS
SYS.DateTimeFilenamestringFile-safe timestamp
SYS.DateTimeMsecStringstringWith milliseconds
SYS.CurrentDateTimeInISO8601stringISO 8601
SYS.GetDateTimeStringFormat(string format)stringC# format string
int start = SYS.TickCount;
DoSomething();
int elapsed = SYS.GetElasped(start);
Log($"Elapsed: {elapsed} ms");

Files / paths

MethodDescription
bool ExistsFile(string path)File exists
string ReadAllText(string path)Read whole file
bool WriteAllText(string path, string data)Write whole file
array ReadAllLines(string path)Read as lines
bool WriteAllLines(string path, array lines)Write as lines
bool AppendLine(string path, string data)Append line
bool CreateDirectory(string path)mkdir -p
bool DeleteFile(string path)Delete
bool CopyFile(string src, string dest, bool overwrite)Copy
string Combine(string path1, string path2)Join path
string GetFileName(string path)Base name
string GetFileNameWithoutExtension(string path)No extension
string GetValidFileName(string name)Sanitize invalid chars
string ProjectBaseDirectoryProject root
string DownloadsFolderPathDownloads folder
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);

HTTP

MethodDescription
string SendHttpGet(string url) / with tokenGET
string SendHttpPost(string url, string data) / with tokenPOST
string SendHttpDelete(string url, string token)DELETE
string SendHttpPatch(string url, string data, string token)PATCH
SYS.HTTP_ERROR_STRSentinel for error
SYS.LastHttpErrorLast error message
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;
}

Parameters / module execution

MethodDescription
bool SaveSetupParam(void)Persist setup params
bool LoadJobFileParam(void)Reload job-file params
bool GetParamValue(string name, ref string value)Read parameter
bool SetModuleVar(string name, value) / bool GetModuleVar(string name, ref value)Cross-module vars
bool RunScriptFunction(string module, string func, args...)Call cross-module
bool StartModule(string module)Restart module
void StopMotorAll(void)Stop all axes
bool CheckMotorName(string name)Axis exists
if (SYS.RunScriptFunction(moduleName, "ParseJsonToModuleData", data) == false)
{
    ShowError(EB_Ok, 107, moduleName);
    return false;
}

System state / errors

PropertyTypeDescription
SYS.IsRunningboolAuto-run active
SYS.ManualThreadExitSignalboolManual thread exit requested
SYS.LastErrorCodeintLast error code
SYS.LastErrorMsgstringLast error message
SYS.LastErrorModuleNamestringOrigin module
SYS.ProjectVersion / SYS.QMSVersionstringVersions
if (SYS.IsRunning == false)
{
    return true;
}
 
SYS.LastErrorCode = 0;
SYS.LastErrorMsg = "";
SYS.ResetError();

Real-world — HTTP with timing & logging

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

Tips

  • Long waits: measure with SYS.GetElasped(startTick) and check ManualThreadExitSignal between sleeps.
  • File IO: always precede writes with CreateDirectory and ExistsFile for reads.
  • HTTP calls don't throw — compare result with SYS.HTTP_ERROR_STR.
  • Cross-module calls: always go through SetModuleVar / GetModuleVar / RunScriptFunction.

SYS full reference (XUtilSystem)

Sourced from C# — XUtilSystem plus the _LinearConverter / _LoadCell / _ThreadSync partial classes.

Time (properties / functions)

ItemMeaning
SYS.TickCount / SYS.SecondCountelapsed since boot (ms / s)
SYS.GetTickCount() / SYS.GetTime()current tick / time
SYS.GetElasped(startTick)elapsed ms
SYS.DateString / SYS.TimeString / SYS.DateTimeString / SYS.DateTimeMsecString / SYS.DateTimeFilenamecommon formats
SYS.CurrentDateTimeInISOISO-8601
SYS.GetDateTimeStringFormat(format)custom format
SYS.GetAdjustedDate(dateString, offset)offset days
SYS.ConvertSecondsToTimeString(sec)sec → HH:mm:ss
SYS.Year / SYS.Month / SYS.Day / SYS.Hourparts
SYS.RunTimeString / SYS.StopTimeString / SYS.IdleTimeString / SYS.ErrorTimeStringaccumulated stats

System / module control

FunctionMeaning
SYS.IsRunning (prop)running?
SYS.Start() / SYS.StartStepRun() / SYS.Stop() / SYS.Exit() / SYS.ExitMonitorModule()global control
SYS.SetError(module="") / SYS.ResetError()toggle error state
SYS.LastErrorCode / SYS.LastErrorMsg / SYS.LastErrorModuleName (props)last error
SYS.StartModule(module) / StopModule(module) / StartModuleStepRun(module) / ExitModule(module)per-module
SYS.SetModuleError(module) / ResetModuleError(module)module error
SYS.SetModuleBackground(module, value)toggle background
SYS.SequenceModuleCountOnWaiting / SequenceModuleCountOnRunning (props)sequence counts
SYS.StopManualThread() / SYS.ManualThreadExitSignal (prop)manual thread
SYS.GetThreadCount(threadName) / (moduleName, seqOrFuncName)thread count

System info · license · diagnostics

ItemMeaning
SYS.QMSVersion / SYS.ProjectVersionversions
SYS.GetExeFileVersion() / GetExeAssemblyVersion()exe versions
SYS.IsProjectOpen / ProjectBaseDirectoryproject state
SYS.LicenseKeyCount / LicenseMotorCount / LicensePermitRemainDays / TrialLicenseEnabled / HaveProjectCodeLicense / HaveLicenselicense
SYS.GetAvailableRamSize() / GetProcessMemorySize() / GetManagedMemorySize() / GetTotalMemorySize()memory
SYS.AddThreadIdLog(prefix, log) / AddMemoryLog() / LogSystemInfo() / LogVersionInfo()diagnostic logs
SYS.IsVisualStudioRunning(update=false)debugger attached?

Throughput (UPH)

FunctionMeaning
SYS.ClearUphData() / AddUphData(uph) / GetAverageUph()UPH stats
SYS.SetBoost() / ResetBoost()boost mode

File / directory

FunctionMeaning
SYS.MakeFullPath(pathname) / IsFullPath(path)path conversion
SYS.GetCurrentDirectory()cwd
SYS.GetFileName(path) / GetFileNameWithoutExtension(path) / GetDirectoryName(path)split
SYS.ChangeFileExt(filepath, ext)replace extension
SYS.GetUpdateFileName(filename)generate update file name
SYS.GetValidFileName(fileName)safe filename
SYS.GetRelativePath(baseFolder, path) / GetAbsolutePath(baseFolder, path)abs/rel
SYS.Combine(p1, p2, p3="", p4="")path combine
SYS.ExistsFile(path) / ExistsDirectory(path)exists
SYS.CreateFile(path) / DeleteFile(file) / CopyFile(src, dst, overwrite) / CopyFiles(srcDir, pattern, dstDir, overwrite)files
SYS.MoveFile(src, dst, overwrite=true) / RenameFile(src, dst, overwrite=true)move/rename
SYS.SetFileHidden(path, setHidden=true)hidden attribute
SYS.CreateDirectory(path) / DeleteDirectory(path, recursive) / ForceDeleteDirectory(path, recursive) / MoveDirectory(src, dst)directories
SYS.CopyDirectory(src, dst, overwrite=true)recursive copy
SYS.GetFiles(path) / (path, pattern) / (path, pattern, subDirectory)file list
SYS.GetDirectories(path) / (path, pattern) / (path, pattern, subDirectory)dir list
SYS.DeleteFiles(dir, remainCount)clean old files
SYS.OpenExplorer(path)open Explorer
SYS.Execute(file, param)run external

Text file I/O

FunctionMeaning
SYS.ReadAllLines(path) / ReadAllText(path)read
SYS.WriteAllLines(path, data) / WriteAllText(path, data)write
SYS.AppendAllLines(path, data) / AppendAllText(path, data) / AppendLine(path, data)append
SYS.IsJsonFile(filepath)JSON file?

Parameters (XParam)

FunctionMeaning
SYS.SaveParam(managerKey) / LoadParam(managerKey)by key
SYS.SaveJobFileParam() / LoadJobFileParam()JobFile
SYS.SaveSetupParam() / LoadSetupParam()Setup
SYS.SaveMasterParam() / LoadMasterParam()Master
SYS.SaveRunParam() / LoadRunParam()Run
SYS.GetParamValueObjectRef(dataName, remainLog=true)XParamValue
SYS.SetParamValue(dataName) / (dataName, string/int/double/bool)set
SYS.GetParamValue(dataName, ref string/int/double/bool)get
SYS.SaveSysVisionInfo() / SaveJobVisionInfo()vision info
SYS.SaveGlobalData() / LoadGlobalData()global data

Cross-module

FunctionMeaning
SYS.SetModuleVar(name, string/int/double/bool)write module var
SYS.GetModuleVar(name, ref string/int/long/double/bool)read module var
SYS.GetModuleVarXData(dataName)as XData
SYS.RunScriptFunction(module, function) / (module, function, string/int/long/double/bool)call function in another module

HTTP

FunctionMeaning
SYS.SendHttpGet(url, token="")GET
SYS.SendHttpPost(url, data, token="", type="")POST
SYS.SendHttpPatch(url, data, token="", type="application/json")PATCH
SYS.SendHttpDelete(url, token="")DELETE
SYS.HTTP_ERROR_STR (prop)error prefix ("[HTTP-ERROR]")
SYS.LastHttpError (prop)last error message

Sound

FunctionMeaning
SYS.PlaySound(fileName) / PlaySoundLoop(fileName) / StopSound()wav playback

Bulk motor / IO control

FunctionMeaning
SYS.SetSpeedAll(speed) / (speed, percent)set speed for all motors
SYS.ServoOnAll(on) (SetServoOnAll)servo all on/off
SYS.ResetMotorHomeDoneAll()reset Home Done
SYS.StopMotorAll() / StopMotorEmgAll()stop all
SYS.ClearAlarmAll() / GetAlarmCount()alarms
SYS.GetMotorNames() / GetIoNames()name lists
SYS.CheckIOName(name) / CheckMotorName(name) / CheckCylinderName(name) / CheckIntefaceName(name) / CheckDeviceContainerName(name)name validation

Messages / errors

FunctionMeaning
SYS.ShowError(buttonType, code, module, format, args...)error dialog (parallels global ShowError)

Misc (random · hash · CRC)

FunctionMeaning
SYS.GetRandom() / (min, max) / GetRandomDouble()random
SYS.GetSha256Hash(input)SHA-256
SYS.CalcCRC16(data, length)Modbus CRC-16
SYS.UpdateCustomData(command, index)update custom data