SYS 는 QMS 가 제공하는 시스템 함수를 모은 객체입니다. 함수는 SYS.Start() 처럼 부르고, 속성은 SYS.IsRunning 처럼 괄호 없이 읽습니다.
로그·메시지·에러 알람처럼 자주 쓰는 함수는 객체 이름 없이 바로 부르는 내장 시스템 함수 로 제공됩니다.
SYS 에 없는 함수·속성 이름과 인자 개수 오류는 빌드할 때 검사합니다 (컴파일 진단 ).
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 인자는 {0} · {1} 자리에 뒤 인자를 넣는 .NET 포맷 문자열입니다.
메시지·에러 코드는 메시지·에러 에디터 에 등록한 번호입니다. 등록하지 않은 코드나 0 을 쓰면 빌드 때 경고합니다.
버튼 조합 EB_* 과 결과 ER_* 상수는 아래 상수 표를 봅니다.
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). 넘길 인자는 하나까지이고 모듈·함수 이름은 실행할 때 찾음
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) 안에 진입하면 truebool 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 없음)입니다.
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-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_STR string HTTP 함수가 실패할 때 반환하는 문자열 ("[HTTP-ERROR]" ) LastHttpError string 마지막 HTTP 함수가 받은 오류 응답 본문 (시간 초과 · 연결 실패는 빈 문자열)
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 ;
}
실전 예 — 응답 시간을 재며 주문 수를 조회합니다.
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 로 올린 분해능 설정을 해제해 윈도우 기본값으로 되돌림void NtSetTimerResolution(uint DesiredResolution, bool SetResolution, ref uint CurrentResolution) 시스템 타이머 분해능 직접 설정 (DesiredResolution = 설정할 값, SetResolution = 설정 여부, CurrentResolution = 지금 값 — 단위 100 ns)
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) 키보드 키 상태(윈도우 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 해시 (16진수 소문자 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
메서드 설명 void ClearUphData() UPH 데이터 초기화 void AddUphData(int uph) 측정한 UPH 값 추가 (최근 UphDataMaxCount 개까지 보관) int GetAverageUph() 보관된 UPH 값의 평균 (값이 없으면 0)
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
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 관련 속성은 위 네트워크 절에 있습니다.
속성 타입 설명 DateString string 현재 날짜 yyyyMMdd TimeString string 현재 시간 HHmmss DateTimeString string 현재 날짜·시간 yyyyMMdd_HHmmss (초 단위까지) DateTimeFilename string 현재 날짜·시간 yyyyMMdd_HHmmss_fff (ms 단위까지 — 파일 이름용) DateTimeMsecString string DateTimeFilename 과 같은 형식MsecTimeString string 현재 시간 HHmmss_fff (ms 단위까지) CurrentDateTimeInISO8601 string ISO 8601 형식 (예 2024-12-03T12:34:56.123+09:00 ) Year · Month · Day int 현재 년 / 월 / 일 Hour · Minute · Second · Millisecond int 현재 시 / 분 / 초 / 밀리초 TickCount int GetTickCount() 와 같은 값 (ms)SecondCount int TickCount 를 초 단위로RunTimeString · StopTimeString · IdleTimeString · ErrorTimeString string 장비 RUN / STOP / IDLE / ERROR 누적 시간 (HH:mm:ss )
속성 타입 설명 IsRunning bool 장비가 가동(RUN) 중인지 RunState string 현재 장비 상태 — "None" · "Stop" · "Run" · "Error" · "Exit" SequenceModuleCountOnWaiting int 대기 상태(스텝을 실행하지 않는) 시퀀스 모듈 수 SequenceModuleCountOnRunning int 스텝을 실행 중인 시퀀스 모듈 수 (백그라운드 모듈 제외) IsProjectOpen bool 프로젝트가 열려 있는지 DesignMode bool 이 PC 에서 Visual Studio(devenv )가 실행 중이면 true (QMS 편집 화면 여부가 아님) ManualThreadRun bool 매뉴얼 동작이 실행 중인지 ShowManualStopButton bool (설정 가능)true 로 두면 매뉴얼 진행 메시지 창에 STOP 버튼이 나타남. RunManualThread 가 시작할 때 false 로 돌아가므로 매뉴얼 함수 안에서 켬 ManualThreadExitSignal bool (설정 가능)매뉴얼 진행 창의 STOP 버튼이나 StopManualThread() 로 true 가 됨. 매뉴얼 함수가 이 값을 확인해 스스로 끝냄 (RunManualThread 가 시작할 때 false)
속성 타입 설명 LastErrorCode int 마지막으로 발생한 에러 알람 코드 (처음은 -1) LastErrorMsg string 마지막으로 발생한 에러 메시지 (메시지:추가 문구 형식) LastErrorModuleName string 마지막 에러가 발생한 모듈 이름 ErrorTraceInfo string 스크립트의 에러 정보 ProjectVersion string 현재 프로젝트의 버전 QMSVersion string QMS 버전 (예 "4.0.9 (261117_0032)" — 버전 뒤에 빌드 시각이 붙음) ProjectBaseDirectory string 프로젝트 파일(.xmp)이 있는 폴더 JobFileName string 작업파일 루트부터 하위 폴더를 포함한 작업파일 이름 AppDataFolderPath string QMS 데이터 폴더 (%APPDATA%\QMachineStudio ) GlobalDataFilePath string 전역 데이터 파일 경로 (AppDataFolderPath 아래 XGlobalData.XDF ) DownloadsFolderPath string 현재 사용자의 다운로드 폴더 UphDataMaxCount int (설정 가능)사용할 UPH 데이터의 최대 개수 (기본 100, 최대 10000)
라이선스 종류와 조건은 라이선스 장을 봅니다.
속성 타입 설명 HaveLicense bool 라이선스가 유효한지 TrialLicenseEnabled bool 체험판 라이선스가 활성화돼 있는지 HaveProjectCodeLicense bool 프로젝트 코드 라이선스 조건을 충족하는지 (프로젝트 코드를 지정하지 않은 프로젝트는 true) LicenseKeyCount int 라이선스에 등록된 키 개수 LicenseMotorCount int 라이선스에 포함된 모터 개수 LicensePermitRemainDays int 라이선스의 남은 유효 일수
프로젝트 구성 개수를 읽는 읽기 전용 속성입니다. 값은 마지막 빌드 때 집계한 것으로(프로젝트 메뉴 의 프로젝트 통계 화면과 같은 값), 읽을 때마다 다시 세지 않아 시퀀스 루프 안에서 읽어도 부담이 없습니다.
빌드 전에는 0 이므로 필요하면 SYS.StatUpdated 를 먼저 확인합니다.
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