XScript 手册 · Chapter 50

SYS — 系统函数

SYS 是汇集了 QMS 提供的系统函数的对象。函数像 SYS.Start() 这样调用,属性像 SYS.IsRunning 这样不带括号读取。 日志·消息·错误报警等常用函数,作为不带对象名直接调用的内置系统函数提供。

SYS 中不存在的函数·属性名称以及参数个数错误,会在构建时检查(编译诊断)。

示例

xscript
SYS.LogSystemInfo();
 
if( SYS.IsRunning == true )    // IsRunning 是属性 — 不带括号读取
{
   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();
}

方法

内置系统函数(不带前缀调用)

下面的函数不带对象名直接调用。像 SYS.Log(…) 这样加上 SYS. 效果相同。但 ShowError · FormatString 要不带 SYS. 调用。

  • format 参数是 .NET 格式字符串,后面的参数会填入 {0} · {1} 的位置。
  • 消息·错误代码是在 消息·错误编辑器 中登记的编号。使用未登记的代码或 0 时,构建时会给出警告。
  • 按钮组合 EB_* 和结果 ER_* 常量请参阅下面的常量表。
xscript
string lotId = "LOT-01";
Log("Start Lot = {0}", lotId);
LogError("Vacuum timeout : {0} ms", 3000);
 
// 消息窗口 — 把按下的按钮与 ER_* 比较
if( ShowMessage(EB_YesNo, 1001) == ER_Yes )
{
   RunManualThread("Loader", "ManualHome");
}
 
// 错误报警 ( 代码 2001 ) — 弹出窗口后直接进入下一行
ShowError(EB_Retry, 2001, "Station = {0}", ModuleName);
方法说明
Log(string format, …)输出日志
LogError(string format, …)输出错误日志
LogDebug(string format, …)输出日志(作为与 Log 相同的普通日志记录)
string FormatString(string format, …)生成格式字符串并返回
Sleep(int msec)等待指定时间(ms)。系统正在退出(Exit)时会提前唤醒
bool WaitRun()时序为 STOP 时,等待到 START — 时序步骤与线程
int ShowMessage(int buttonSet, int code) · int ShowMessage(int buttonSet, string message)显示消息窗口。返回按下的按钮(ER_*)
int ShowMessageFormat(int buttonSet, string format, …)用格式字符串显示消息窗口
int ShowTimerMessage(int buttonSet, int code) · int ShowTimerMessage(int buttonSet, string format, …)经过一定时间后自动关闭的消息。显示时间为 GUI.TimerMessageShowTime(ms)
int ShowWarning(int code, …) · int ShowWarning(string format, …)警告窗口(OK 按钮,无蜂鸣)
ShowError(int buttonSet, int code, string format="", …)发出错误报警 — 把设备变为错误状态并弹出窗口后,不等待而直接进入下一行。不带 SYS. 调用
int ShowErrorWait(int buttonSet, int code, string format="", …)弹出错误报警并等待到按下按钮。返回按下的按钮(ER_*)
bool ClearAlarm(int code)解除以该代码弹出的报警(解除了任何一个即为 true)
bool RegisterAlarmHandler(string module, string function)注册报警恢复处理函数
bool LogEvent(string name, string message)不在画面显示,只记录到事件列表
bool RunThread(string module, string function [, 参数])把其他模块的函数以单独线程运行(参数最多一个)
bool RunManualThread(string module, string function [, int messageCode])把函数作为手动动作运行(可指定进行中的消息代码,默认 64)
bool SetNextStep(string module, string step)指定模块的下一个执行步骤

按钮组合 · 结果常量 — 常量的整体说明请参阅 语言基础 章。

常量用途
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_NoWaitPass消息·错误窗口的按钮组合(ShowMessage · ShowError 的第一个参数)
ER_Ok ER_Cancel ER_Yes ER_No ER_Retry ER_Skip ER_Reset ER_Ignore ER_Fail ER_TimeEnd ER_NoWaitPass在消息窗口中按下的按钮(与 ShowMessage · ShowErrorWait 的返回值比较)

数据 · 参数

参数前缀(JF. · SS. · MS. · RD.)以及值的读写请参阅 Parameter,全局变量(G_*)请参阅 Global 变量 章。

方法说明
bool LoadGlobalData()载入已保存的全局数据(生产数量·LOT 状态·运行时间 — G_LoadCount · G_LotCount · G_RunTime 等)。打开项目时 QMS 会自动调用
bool SaveGlobalData()把全局数据保存到 SYS.GlobalDataFilePath 文件。关闭项目时 QMS 会自动调用
bool SetParamValue(string dataName, int|double|bool|string value)设置参数值。dataName 像 "SS.CamCalibX" 这样包含前缀(名称在构建时检查)。要保留到文件,请用 SaveParam 或 SaveSingleParam 保存
bool SetParamValue(string dataName)把参数变量(SS.名称 等)的当前值交给待保存的编辑值(画面输入控件使用的形式)
bool GetParamValue(string dataName, ref int|double|bool|string value)读取参数值并放入 value(包含前缀的名称)。名称不存在时为 false
bool SaveSingleParam(string dataName)只把一个参数保存到文件(例 "SS.AutoPrint")。其他正在编辑的参数的未保存值保持不变
bool SaveParam(string managerKey)把参数保存到文件。managerKey : JF 作业文件 · SS 系统设置 · MS 主设置 · RD RUN 数据
bool LoadParam(string managerKey)从文件载入参数(managerKey 同上)
bool SaveJobFileParam() · bool LoadJobFileParam()保存 / 载入作业文件参数。保存时也一并保存作业文件视觉信息,载入后执行 OnJobFileLoaded 事件
bool SaveSetupParam() · bool LoadSetupParam()保存(包含系统视觉信息)/ 载入系统设置参数
bool SaveMasterParam() · bool LoadMasterParam()保存 / 载入主设置参数
bool SaveRunParam() · bool LoadRunParam()保存 / 载入 RUN 数据
bool SaveSysVisionInfo()保存 System Vision 对象的信息
bool SaveJobVisionInfo()保存 JobFile Vision 对象的信息
bool ChangeJobFile(string jobName, bool showMsg=true) 4.0+更换并载入作业文件。jobName 是 XJobFile 下的作业文件夹名称(例 "Default.JOB")。载入后执行 OnJobFileLoaded 事件。showMsg=false 时不显示成功提示直接切换(仍显示失败提示)。失败时为 false

设备 · 模块控制

方法说明
void Start()启动设备的所有时序
void Stop()停止设备的所有时序
void SetError(string module="")把设备变为错误状态(module = 要设为错误的模块名称)
void ResetError()初始化设备的错误状态
void Exit()结束设备的所有时序
void StartStepRun()以单步运行模式启动整台设备
void StartModule(string module) · void StopModule(string module)启动 / 停止指定模块
void SetModuleError(string module) · void ResetModuleError(string module)把指定模块变为错误状态 / 初始化错误状态
void ExitModule(string module)结束指定模块
void StartModuleStepRun(string module)以单步运行模式启动指定模块
void ExitMonitorModule()结束监视模块
void SetModuleBackground(string module, bool value)把时序模块指定为后台模块 — 从 SequenceModuleCountOnRunning 统计中排除
string GetCurrentStep(string module) 4.0+时序模块当前正在执行的步骤名称。模块不存在时为空字符串
int GetCurrentStepIndex(string module) 4.0+当前正在执行的步骤的索引(从 0 开始)。模块不存在时为 -1
string GetCurrentThreadModule() 4.0+当前执行代码的线程是哪个模块的时序线程,返回模块名称。在手动 · RunThread · 画面事件 · 定时器中为空字符串,调用其他模块的函数(模块::函数)时值也不会改变 — 同一函数同时用于时序和手动时,用来区分是谁调用的
bool RunManualThread(string moduleName, string functionName, int messageCode=64)把模块的函数作为手动运行(messageCode = 运行中弹出的消息编号)。是内置系统函数,因此也可以不带 SYS. 调用。设备正在运行或有其他手动动作在执行时不运行,返回 false
void StopManualThread()请求手动停止 — 把 ManualThreadExitSignal 改为 true。实际的停止由手动函数查看此信号后处理
int GetThreadCount(string threadName) · int GetThreadCount(string moduleName, string seqOrFuncName)以该名称运行的线程个数。第二种形式统计 模块::名称 线程 — 用于确认用 RunThread 启动的函数线程是否还在运行
bool RunScriptFunction(string module, string function) · bool RunScriptFunction(string module, string function, string|int|long|double|bool data)运行其他模块的函数,并返回该函数的 bool 返回值(返回值不是 bool 或无法运行时为 false)。传递的参数最多一个,模块·函数名称在运行时查找
xscript
FUNCTION LoadModuleData(string moduleName, string data)
{
   if( SYS.RunScriptFunction(moduleName, "ParseJsonToModuleData", data) == false )
   {
      ShowError(EB_Ok, 107, moduleName);
      return false;
   }
   return true;
}

提示 WaitRun · SetNextStep · RunThread · RunManualThread 的运行规则,以及 GetCurrentStep · GetCurrentThreadModule 的用法,在 时序步骤与线程 章中介绍。对于名称已确定的其他模块函数,用 模块::函数() 调用比 RunScriptFunction 更简单,并且名称·参数会在构建时检查(函数)。

线程同步

多个时序·线程使用同一资源时,按名称区分的同步对象。事件·信号量是 4.0 中新增的。

方法说明
bool EnterCriticalSection(string name)进入临界区(不存在则创建)。在进入的线程释放之前,其他线程等待
bool ExitCriticalSection(string name)释放临界区。当前线程没有持有时为 false
bool TryEnterCriticalSection(string name, int timeout=0)在 timeout(ms)内进入则为 true
bool IsEnteredCriticalSection(string name)当前线程是否持有该临界区
bool ExitAllCriticalSection()释放当前线程持有的所有临界区
bool CreateEvent(string name, bool manualReset=true, bool initialState=false) 4.0+创建事件(已存在则保持不变)
bool SetEvent(string name) · bool ResetEvent(string name) 4.0+置起事件信号(等待的线程被唤醒)/ 放下
bool WaitEvent(string name, int timeout=-1) 4.0+等待信号(-1 = 无限)。收到信号为 true,超时为 false
bool RemoveEvent(string name) 4.0+删除事件
bool CreateSemaphore(string name, int initialCount, int maxCount) 4.0+创建信号量
bool WaitSemaphore(string name, int timeout=-1) · bool ReleaseSemaphore(string name) 4.0+获取 / 归还信号量
int GetSemaphoreCount(string name) · bool RemoveSemaphore(string name) 4.0+剩余可进入个数(未创建的名称为 -1)/ 删除信号量
  • SetEvent · ResetEvent · WaitEvent 在事件不存在时,会创建为手动复位事件使用。
  • 信号量必须先用 CreateSemaphore 创建。对未创建的名称调用 WaitSemaphore · ReleaseSemaphore 为 false。

注意 不要持有临界区的同时用 WaitRun() 等待 — 使用同名临界区的监视与手动动作,会在整个停止期间被卡住(时序步骤与线程)。

电机批量控制

方法说明
void SetSpeedAll(string speed)把所有电机的速度改为设定值。speed : HOME · MAINT(= JOG)· RUN(忽略大小写)
void SetSpeedAll(string speed, int percent)把所有电机的速度改为设定值的 percent %(加减速保持设定值)
void ClearAlarmAll()初始化所有电机的报警(因要开关报警解除信号,约需 1 秒)
void SetServoOnAll(bool on)所有电机的伺服信号 ON / OFF
void ResetMotorHomeDoneAll()初始化所有电机的 Home Done 信号
void StopMotorAll()所有电机减速停止
void StopMotorEmgAll()所有电机急停
int GetAlarmCount()发生报警的电机数
array GetMotorNames()已登记的电机名称列表
array GetIoNames()已登记的 IO 名称列表

路径

方法说明
string Combine(string path1, string path2, string path3="", string path4="")最多连接 4 个路径。去掉后面路径开头的 \ 后连接
bool IsFullPath(string path)是否为绝对路径(以驱动器或 \ 开头)
string MakeFullPath(string pathname)把相对路径转换为以 QMS 可执行文件夹为基准的绝对路径(空字符串则为可执行文件夹)
string GetAbsolutePath(string baseFolder, string path)path 为相对路径时,生成以 baseFolder 为基准的路径
string GetRelativePath(string baseFolder, string path)path 在 baseFolder 之下时,只返回其下面的部分(忽略大小写,否则保持原样)
string GetFileName(string path)路径的最后一部分(文件名 + 扩展名)。以 \ 结尾的路径为空字符串
string GetFileNameWithoutExtension(string path)去掉扩展名的文件名
string GetDirectoryName(string path)去掉最后一部分的文件夹路径(C:\Data\a.txt → C:\Data)
string ChangeFileExt(string filepath, string ext)更改扩展名后的路径(ext 像 ".txt" 这样包含点)
string GetUpdateFileName(string filename)在文件名后加上 _Update 的路径(a.json → a_Update.json)
string GetValidFileName(string fileName)把文件名中不能使用的字符替换为 _(空字符串则为 yyyyMMdd_HHmmss)
string GetCurrentDirectory()当前工作文件夹

文件 · 文件夹

方法说明
bool ExistsFile(string path)文件是否存在
bool CreateFile(string path)在该位置创建空文件(写入内容的文件由 WriteAllText 等直接创建,无需事先创建)
bool DeleteFile(string file)删除单个文件
bool CopyFile(string sourceFileName, string destFileName, bool overwrite)复制文件
bool CopyFiles(string srcDir, string filePattern, string destDir, bool overwrite)把 srcDir 中符合 filePattern(例 *.csv)的文件复制到 destDir。同名文件总是覆盖(overwrite 参数不起作用)
bool MoveFile(string source, string target, bool overwrite=True)移动文件。source 不存在,或 target 已存在而 overwrite 为 false 时失败
bool RenameFile(string source, string target, bool overwrite=True)重命名文件(与 MoveFile 动作相同)
bool SetFileHidden(string filePath, bool setHidden=true)开启 / 关闭文件的隐藏属性
void DeleteFiles(string dir, int remainCount)把文件夹中的文件按名称升序排序,只保留最后 remainCount 个,其余删除(不查看子文件夹 — 名称为日期格式时,从最旧的文件开始删除)
bool IsJsonFile(string filepath)是否为 JSON 文件 — 按第一行是否为 { 或 [ 单个字符来判定
bool Execute(string file, string param)运行文件(运行程序,文档则用关联的程序打开)
void OpenExplorer(string path)打开资源管理器 — 是文件则选中该文件后打开,否则打开 GetDirectoryName(path) 文件夹(要打开文件夹本身,请在末尾加 \)
bool ExistsDirectory(string path)文件夹是否存在
bool CreateDirectory(string path)创建文件夹(包括所有中间文件夹)
bool DeleteDirectory(string path, bool recursive)删除文件夹(recursive = 连同子文件夹·文件一并删除)
bool ForceDeleteDirectory(string path, bool recursive)强制删除 — recursive=true 时,解除内部文件·文件夹的属性(只读等)后删除。文件夹不存在时为 true
bool MoveDirectory(string sourceDirName, string destDirName)移动文件夹
bool CopyDirectory(string source, string destination, bool overwrite=True)连同子文件夹复制整个文件夹
array GetDirectories(string path)该位置所有文件夹的列表(完整路径)
array GetDirectories(string path, string searchPattern)查找符合模式的文件夹。不搜索子文件夹
array GetDirectories(string path, string searchPattern, bool subDirectory)查找符合模式的文件夹(subDirectory = 包括子文件夹)
array GetFiles(string path)该位置所有文件的列表(完整路径)
array GetFiles(string path, string searchPattern)查找符合模式的文件。不搜索子文件夹
array GetFiles(string path, string searchPattern, bool subDirectory)查找符合模式的文件(subDirectory = 包括子文件夹)

文本文件读取 · 写入

方法说明
string ReadAllText(string path)读取文件并以字符串返回(失败时为空字符串)
array ReadAllLines(string path)读取文件并以按行的数组返回。被其他程序打开的文件也能读取
bool WriteAllText(string path, string data)把字符串写入文件(覆盖原有内容)
bool WriteAllLines(string path, array data)把字符串数组逐行写入文件
bool AppendAllText(string path, string data)把字符串追加到文件末尾
bool AppendAllLines(string path, array data)把字符串数组逐行追加到文件末尾
bool AppendLine(string path, string data)在字符串后加上 \r\n 后追加到文件末尾

写入·追加函数在文件不存在时会新建,上级文件夹不存在时也会创建文件夹。编码为 UTF-8(无 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;
}

网络(HTTP)

HTTP 函数返回应答字符串,失败时返回 "[HTTP-ERROR]"(SYS.HTTP_ERROR_STR)。不会因异常而停止,因此要把返回值与 SYS.HTTP_ERROR_STR 比较来判断是否成功。 服务器发回错误应答时,该应答正文会保留在 SYS.LastHttpError 中(超时 · 连接失败为空字符串,原因只记录在日志中)。给出 token 时,会以 Authorization: Bearer 头发送。每次调用的应答等待时间 timeoutMs 是 4.0 中新增的。

方法说明
string SendHttpPost(string url, string data, string token="", string type="", int timeoutMs=10000)用 HTTP POST 发送数据。type = Content 类型(为空则为 application/json),timeoutMs = 应答等待时间(ms)
string SendHttpGet(string url, string token="", int timeoutMs=10000)用 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+在后台发送 POST 并立即返回。不告知结果 — 用于即使失败时序也必须继续的状态上报。待发送队列已满时为 false
属性类型说明
HTTP_ERROR_STRstringHTTP 函数失败时返回的字符串("[HTTP-ERROR]")
LastHttpErrorstring最后一次 HTTP 函数收到的错误应答正文(超时 · 连接失败为空字符串)
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;
}

实战示例 — 测量应答时间并查询订单数。

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);   // 3 秒内没有应答则失败
 
   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;
}

时间 · 定时器

方法说明
int GetTickCount()系统启动后经过的时间(ms)。大约每 24.8 天回到 0
int GetElasped(int start)从 start(先前读取的 GetTickCount() 或 TickCount 值)起经过的时间(ms)。回到 0 的情况也能正确计算
double GetTime()高分辨率定时器值(ms,含小数)。用两次读取值之差测量短时间(不是当前时间)
string GetDateTimeStringFormat(string format)以输入的 .NET 格式返回当前日期·时间(例 "yyyy-MM-dd HH:mm:ss")
string ConvertSecondsToTimeString(int sec)把秒转换为 "HH:mm:ss" 字符串(例 3725 → "01:02:05")
string GetAdjustedDate(string dateString, int offset)把日期字符串(yyyyMMdd 等)加上 offset 天后的日期以 yyyyMMdd 返回。无法读取的日期则以今天为基准
bool SetBoost(bool silent=false)把系统定时器分辨率设为 0.5 ms(Sleep(1) 的动作接近 1 ms)。QMS 启动时和窗口激活时会自行调用。silent=true 时省略设置日志和确认用的等待
bool ResetBoost()解除用 SetBoost 提高的分辨率设置,恢复为 Windows 默认值
void NtSetTimerResolution(uint DesiredResolution, bool SetResolution, ref uint CurrentResolution)直接设置系统定时器分辨率(DesiredResolution = 要设置的值,SetResolution = 是否设置,CurrentResolution = 当前值 — 单位 100 ns)
xscript
int start = SYS.TickCount;
Sleep(500);                            // 要测量时间的动作
int elapsed = SYS.GetElasped(start);   // TickCount 回到 0 也能正确计算
Log($"Elapsed: {elapsed} ms");

系统信息 · 诊断

方法说明
void LogSystemInfo()把当前系统信息(OS · PC 名称 · 处理器数等)输出到日志
void LogVersionInfo()把项目名称·版本·文件、QMS 版本、脚本引擎输出到日志
void AddMemoryLog()把内存 · 句柄 · 线程使用量输出到日志(超过基准时输出警告日志)
void AddThreadIdLog(string prefix, string log="")把当前线程 ID 输出到日志(用于调试,log 参数不使用)
void SetDebugLog(bool use) 4.0+是否输出 QMS 调试日志。默认输出(true),在运行环境中想减少重复的流程日志时使用(例 在 Init 脚本中 SYS.SetDebugLog(G_DebugLog))。脚本的 LogDebug 是普通日志,因此不受影响
long GetAvailableRamSize()可用内存(字节)。QMS 启动后的几秒内为 0
long GetTotalMemorySize()已安装的物理内存(字节)
long GetProcessMemorySize() · long GetManagedMemorySize()QMS 进程的工作内存 / .NET 托管内存(字节)
string GetExeFileVersion()QMS 可执行文件的版本和构建时间(与 SYS.QMSVersion 相同的值)
string GetExeAssemblyVersion()QMS 可执行文件的程序集版本(只反映主版本 — 例 "4.0.0")
bool IsVisualStudioRunning(bool update=false)Visual Studio 是否正在运行。update=false 时原样返回首次确认的结果,true 时重新确认
bool CheckAsyncKeyDown(int vKey)键(虚拟键码)是否被按下(即使自上次确认后按过也为 true)
short GetAsyncKeyState(int vkey)键盘按键状态(Windows GetAsyncKeyState 的值)
string GetScriptEngine() 4.0+当前脚本执行引擎的名称。4.0 中始终为 "NewBytecode"
bool SetScriptEngine(string mode)确认脚本引擎。由于引擎选择功能已取消,只接受 "NewBytecode"(已经准备好时什么都不改变,返回 true),其他值("Legacy" 等)为 false
bool UpdateCustomData(string command, int index)调用项目专用 C# 扩展登记的用户数据更新处理。没有登记的处理时为 false

声音 · 随机数 · 哈希

方法说明
bool PlaySound(string fileName)播放 wav 文件。相对路径以项目文件夹的 Media 文件夹为基准查找,文件不存在时为 false
bool PlaySoundLoop(string fileName)循环播放 wav 文件(路径规则与 PlaySound 相同)
bool StopSound()停止正在播放的声音
int GetRandom()0 以上、小于 int 最大值的随机数
int GetRandom(int min, int max)min 以上、小于 max 的随机数
double GetRandomDouble()0 以上、小于 1 的实数随机数
string GetSha256Hash(string input)字符串(UTF-8)的 SHA-256 哈希(十六进制小写 64 个字符)
ushort CalcCRC16(byte[] data, int length)前 length 个字节的 Modbus CRC-16。传入 byte 缓冲区,结果以整数接收

名称存在确认

方法说明
bool CheckIOName(string name)确认是否存在该名称的 IO
bool CheckMotorName(string name)确认是否存在该名称的电机
bool CheckCylinderName(string name)确认是否存在该名称的气缸
bool CheckIntefaceName(string name)确认是否存在该名称的通信驱动(函数名的拼写 Inteface 保持原样)
bool CheckDeviceContainerName(string name)确认是否存在该名称的设备容器

模块变量读取 · 写入

用 "模块::变量" 字符串写入和读取其他模块的变量。数组元素用 "模块::数组[i]" 指定。直接以字符串书写名称时,会在构建时检查模块·变量是否存在。 名称固定时,像 Loader::WorkCount 这样直接使用 模块::变量 更简单(函数)。

方法说明
bool SetModuleVar(string name, int|double|bool|string value)向模块变量写入值(name 为 "Loader::WorkCount" 形式)。数字只写入 int · long · double 变量,bool 只写入 bool 变量,字符串只写入 string 变量,类型不符或变量不存在时为 false
bool GetModuleVar(string name, ref int|long|double|bool|string value)读取模块变量值并放入 value。变量不存在或类型不符时为 false

UPH

方法说明
void ClearUphData()初始化 UPH 数据
void AddUphData(int uph)添加测得的 UPH 值(最多保留最近的 UphDataMaxCount 个)
int GetAverageUph()保留的 UPH 值的平均值(没有值时为 0)

线性转换器(LINEAR)

在以 index(0 ~ 999)区分的转换表中放入 (x, y) 点,用直线连接各点来转换 x ↔ y。点范围之外,按两端区间的延长线计算。

  • 初始时放有 (0, 0) · (1, 1) · (2, 2) 三个点,按 y = x 转换。放入自己的数据之前,先用 LINEAR_ClearData 清空。
  • 放入的点,其 x · y 要与最初两个点沿同一方向(同时增大或同时减小)延续。方向改变的点不会被添加,返回 false。
  • LINEAR_GetValueY 的结果超出 -1000 ~ 1000 时,会被截为端值并返回 false。
方法说明
bool LINEAR_ClearData(int index)清空一个转换表
bool LINEAR_AddData(int index, double x, double y)添加点 (x, y)
bool LINEAR_GetValueY(int index, double x, ref double y)与 x 对应的 y
bool LINEAR_GetValueX(int index, double y, ref double x)与 y 对应的 x

称重传感器(LOADCELL)

对每个 index(0 ~ 999)连接电机和模拟输入 IO,用(电压,压力)点转换电压 ↔ 压力。转换方式与线性转换器相同。模拟输入请参阅 AIO 章。

方法说明
bool LOADCELL_SetConfig(int index, string motorName="", string readDevName="")称重传感器设置 — 要连接的电机名称和模拟输入 IO 名称。转换数据会被清空
bool LOADCELL_ClearData(int index)初始化转换数据
bool LOADCELL_AddData(int index, double volt, double pressure)添加(电压,压力)点
bool LOADCELL_ConvertVoltToPressure(int index, double volt, ref double pressure)电压 → 压力转换
bool LOADCELL_ConvertPressureToVolt(int index, double pressure, ref double volt)压力 → 电压转换
bool LOADCELL_ReadVoltage(int index, ref double value)已连接的模拟输入的当前电压(10 次平均)
bool LOADCELL_ReadPressure(int index, ref double value)读取当前电压并转换为压力
bool LOADCELL_WaitPressure(int index, double target, int timeout=1000, bool highPressureStop=true)等待到压力达到目标。highPressureStop=true 时达到 target 以上、false 时达到以下则为 true。经过 timeout(ms)后为 false
bool LOADCELL_MoveToPressure(int index, double targetPressure, double moveOffset, bool highPressureStop=true, double motorSpeed=0.0)让已连接的电机相对移动 moveOffset,压力达到目标时急停并返回 true。到达目标之前移动已结束则为 false。motorSpeed 大于 0 时以该速度移动

属性

属性不带括号读取。标有“(可设置)”的属性,是可以在脚本中修改并写入值的属性。HTTP 相关属性在上面的网络一节中。

日期 · 时间

属性类型说明
DateStringstring当前日期 yyyyMMdd
TimeStringstring当前时间 HHmmss
DateTimeStringstring当前日期·时间 yyyyMMdd_HHmmss(精确到秒)
DateTimeFilenamestring当前日期·时间 yyyyMMdd_HHmmss_fff(精确到 ms — 用于文件名)
DateTimeMsecStringstring与 DateTimeFilename 相同的格式
MsecTimeStringstring当前时间 HHmmss_fff(精确到 ms)
CurrentDateTimeInISO8601stringISO 8601 格式(例 2024-12-03T12:34:56.123+09:00)
Year · Month · Dayint当前的年 / 月 / 日
Hour · Minute · Second · Millisecondint当前的时 / 分 / 秒 / 毫秒
TickCountint与 GetTickCount() 相同的值(ms)
SecondCountint以秒为单位的 TickCount
RunTimeString · StopTimeString · IdleTimeString · ErrorTimeStringstring设备 RUN / STOP / IDLE / ERROR 累计时间(HH:mm:ss)

设备状态 · 手动动作

属性类型说明
IsRunningbool设备是否正在运行(RUN)
RunStatestring当前设备状态 — "None" · "Stop" · "Run" · "Error" · "Exit"
SequenceModuleCountOnWaitingint处于等待状态(不执行步骤)的时序模块数
SequenceModuleCountOnRunningint正在执行步骤的时序模块数(不含后台模块)
IsProjectOpenbool项目是否已打开
DesignModebool该 PC 上 Visual Studio(devenv)正在运行时为 true(不是是否为 QMS 编辑画面)
ManualThreadRunbool手动动作是否正在运行
ShowManualStopButtonbool(可设置)设为 true 时,手动进行消息窗口中会出现 STOP 按钮。RunManualThread 开始时会恢复为 false,因此要在手动函数内开启
ManualThreadExitSignalbool(可设置)通过手动进行窗口的 STOP 按钮或 StopManualThread() 变为 true。手动函数确认此值后自行结束(RunManualThread 开始时为 false)

错误 · 版本 · 路径

属性类型说明
LastErrorCodeint最后一次发生的错误报警代码(初始为 -1)
LastErrorMsgstring最后一次发生的错误消息(消息:附加文案 形式)
LastErrorModuleNamestring最后一次错误发生的模块名称
ErrorTraceInfostring脚本的错误信息
ProjectVersionstring当前项目的版本
QMSVersionstringQMS 版本(例 "4.0.9 (261117_0032)" — 版本后附带构建时间)
ProjectBaseDirectorystring项目文件(.xmp)所在的文件夹
JobFileNamestring从作业文件根开始、包含子文件夹的作业文件名称
AppDataFolderPathstringQMS 数据文件夹(%APPDATA%\QMachineStudio)
GlobalDataFilePathstring全局数据文件路径(AppDataFolderPath 下的 XGlobalData.XDF)
DownloadsFolderPathstring当前用户的下载文件夹
UphDataMaxCountint(可设置)使用的 UPH 数据的最大个数(默认 100,最大 10000)

授权

授权的种类和条件请参阅 授权 章。

属性类型说明
HaveLicensebool授权是否有效
TrialLicenseEnabledbool试用版授权是否已激活
HaveProjectCodeLicensebool是否满足项目代码授权条件(未指定项目代码的项目为 true)
LicenseKeyCountint授权中登记的密钥个数
LicenseMotorCountint授权中包含的电机个数
LicensePermitRemainDaysint授权的剩余有效天数

项目统计(SYS.Stat*) 4.0+

读取项目构成个数的只读属性。值是上一次构建时统计的(与 Project 菜单 的项目统计画面相同的值),每次读取时不会重新统计,因此在时序循环中读取也没有负担。 构建之前为 0,因此需要时请先确认 SYS.StatUpdated。

xscript
if( SYS.StatUpdated == true )
{
   Log($"modules={SYS.StatModuleCount}, io={SYS.StatIoCount}, motors={SYS.StatMotorCount} ( {SYS.StatUpdatedTime} )");
}
分类属性(全部为 int,仅标明的类型不同)
统计状态bool StatUpdated(是否已统计)· string StatUpdatedTime(统计时间 "yyyy-MM-dd HH:mm:ss")
模块StatModuleCount · StatSequenceModuleCount · StatViewModuleCount · StatLibraryModuleCount · StatEventModuleCount · StatInitModuleCount · StatMonitorModuleCount · StatDataModuleCount · StatSubModuleCount · StatDisabledModuleCount
代码StatFunctionCount · StatStepCount · StatScriptLineCount · StatVariableLineCount · StatFunctionLineCount · StatStepLineCount · StatScriptFileCount · StatDesignFileCount · StatCompiledFileCount · long StatScriptBytes
变量 · 参数StatVariableCount · StatGlobalVariableCount · StatModuleVariableCount · StatParamVariableCount · StatConstantCount · StatParameterCount · StatSetupParamCount · StatMasterParamCount · StatJobParamCount · StatVisionParamCount · StatRunParamCount
画面StatGuiControlCount · StatGuiControlKindCount · StatGuiControlMaxDepth · StatGuiLangTextCount · StatGuiImageCount · long StatGuiImageBytes
设备StatIoCount · StatIoInputCount · StatIoOutputCount · StatIoAnalogInputCount · StatIoAnalogOutputCount · StatIoBoardCount · StatMotorCount · StatMotorEnabledCount · StatCylinderCount · StatTowerLampCount · StatCommCount · StatDeviceContainerCount
视觉StatCameraCount · StatCameraEnabledCount · StatVisionToolCount · StatVisionImageCount
其他StatDriverCount · StatLibraryCount · StatCustomLibCount · StatDatabaseCount · StatMessageCount · StatErrorCodeCount
订阅申请