39
예제를 통한 시뮬레이터 연동 이해 Ping Pong Systems Modeling Simulation Lab. KAIST 2011. 12. 08

예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

Embed Size (px)

Citation preview

Page 1: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

예제를 통한 시뮬레이터 연동 이해

– Ping Pong

Systems Modeling Simulation Lab. KAIST

2011. 12. 08

Page 2: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

Ping-Pong 시스템의 요구사항 경기방법

게임은 중앙에 네트를 친 테이블의 양 끝에 상대하는 플레이어가 볼을 서로 라켓으로 번갈아 가면서 쳐 넘긴다.

경기 종류 개인전

2명의 플레이어가 경기를 진행한다.

득점 방법 및 승패 서브를 하면서 경기 시작한다.

서비스는 서브권을 가진 측에서 2번을 서비스를 한 후 상대 플레이어에게 서브권을 넘긴다. 듀스 상황일 경우에는 1번씩 서브권을 주고 받는다.

플레이어가 공을 받아 치는 것은 확률적으로 계산한다.

득점은 1점씩이며 11점을 먼저 얻는 측이 승리한다.

듀스가 되면 계속해서 2점을 먼저 얻어야 승리한다.

Page 3: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

Ping-Pong 모델링 과정 실제로 시스템을 이루고 있는 구성요소 파악.

심판, 플레이어 2명, 탁구대, 탁구채, 탁구공 등.

모델링 목적에 맞게 시스템을 추상화. 모델링 목적 : 탁구 경기를 최대한 간단하게 표현.

추상화 결과 심판, 플레이어 : 모델

탁구공 : 메시지

탁구대, 탁구채 등은 추상화 결과 생략.

모델 사이의 인터페이스 정의 심판

플레이어에게 서브권 넘김.

플레이어 다른 플레이어에게 공을 넘김.

심판에게 공격 실패를 보고함.

각 모델을 자세하게 모델링 표현하고자 하는 정도에 따라 계층 구조로 자세하게 표현 가능.

Page 4: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

Ping-Pong Model

PlayerA PlayerB

Referee

SERVA

SERV_SELF SERV_OTHER

SERVB

SERV_OTHER SERV_SELF

OUTB

OUT_SELF OUT_OTHER

OUTA

OUT_SELF OUT_OTHER

BALL_SEND BALL_REV

BALL_REV BALL_SEND

Ping-Pong

Page 5: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

Atomic DEVS Model for Ping-Pong Player

State Variable

@1

DEFENSE

@∞

SERV

@∞

m_Prob rand_num

Model Player

SERV_SELF

SERV_OTHER

BALL_REV

BALL_SEND

OUT_SELF

ATTACK

OUT_OTHER

?BALL_SEND

?SERV_SELF

?SERV_OTHER

?OUT_OTHER

!OUT_SELF

[rand_num>m_Prob]

!BALL_SEND

[rand_num<m_Prob]

Page 6: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

Atomic DEVS Model for Ping-Pong Referee

State Variable

@0

IDLE

@

m_ScoreA

Model Referee

OUTA SERVA

SERVB

SCORE

OUTB

?OUTA or ?OUTB

!SERVA

[(m_ScoreA≥11&&m_ScoreB≥11&&|m_ScoreA=m_ScoreB|≥2&&m_ServF=0) ||

(!(m_ScoreA≥11&&m_ScoreB≥11&&|m_ScoreA=m_ScoreB|≥2)&&m_ServF=1))]

m_ScoreB m_ServF

!SERVB

[(m_ScoreA≥11&&m_ScoreB≥11&&|m_ScoreA=m_ScoreB|≥2&&m_ServF=1) ||

(!(m_ScoreA≥11&&m_ScoreB≥11&&|m_ScoreA=m_ScoreB|≥2)&&m_ServF=0))]

Page 7: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

PingPong 연동

Page 8: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

준비: 연동 관련 Tools

OMDT

HLA Class Generator

KHLAAdaptor

Network Library (in DEVSim++ v3.0)

Smart Adaptor

Page 9: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

Smart Adaptor: 만능형 연동 어댑터

시뮬레이터는 필요한 서비스/Callback 만을 사용함

만능형 연동 어댑터(연동 엔진)

(103개의 모든 RTI 서비스 사용 가능) (39개 모든 Callback 함수 구현)

SOM

시뮬레이터 응용프로그램 1

(독립 프로세스)

응용프로그램 2

(독립프로세스)

선언

관리

객체

관리

시간

관리

소유권

관리

페더레이션

관리

페더레이터 대사

SOM

페더레이션

관리

선언

관리

객체

관리

시간

관리

데이타

분산

관리

소유권

관리

기타

부수적인

관리

지역 RTI (LRC) 시각 동기용 데이터 교환용

선언

관리

객체

관리

시간

관리

소유권

관리

페더레이션

관리

4 4 13 9 9

RTI 대사

페더레이션

관리

선언

관리

객체

관리

시간

관리

데이타

분산

관리

소유권

관리

기타

부수적인

관리 13 8 9 19 9 12 33

사용 서비스

/Callback 목록

Page 10: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

스마트 어댑터 기반 연동 모델 개발 플랫폼

스마트 어댑터(연동 엔진)

통신 라이브러리

RTI

임의의 시뮬레이터

TCP/IP

TCP/IP

라이브러리 링크

FOM 변환기

사용 서비스/Callback 지정

시뮬레이터와의 인터페이스

연동 어플리케이션

FOM (OMDT)

C++ 클래스

연동 모델 개발 플랫폼 연동 체계 개발자가

채워 넣어야 할 부분

Page 11: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

OMDT (Object Model Development Tool)

FOM 형태의 파일을 생성

OMD (OMDT Document) 파일

페더레이션 객체 구조 정의 (상세한 정보)

Class 및 Interaction

데이터 타입 정의

Enumeration data, Complex data type

FED (Federation Execution Data) 파일

페더레이션 실행을 위한 객체 구조 정의

Page 12: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

HLA Class Generator FOM 형태의 파일과 사용자가 제공하는 template 파일을 읽어 FOM에 의해 정의된 객체

구조를 C++의 class로 바꾸어주는 역할

(Class (ID 30)

(Name "TORPEDO")

(PSCapabilities N)

(SuperClass 10)

(Attribute (Name "DEPTH")

(DataType "long")

(Cardinality "1")

(Accuracy "perfect")

(AccuracyCondition "always")

(UpdateType Conditional)

(TransferAccept N)

(UpdateReflect UR)

(DeliveryCategory "reliable")

(MessageOrdering "timestamp")

)

)

///////////////////////////////////////////////////////////////////

// OBJECT CLASS : #obj_name

//

class JTC_EXPORT #obj_class_name : public

#obj_base_class_name

{

public:

#obj_class_name();

virtual ~#obj_class_name() {}

public:

#for_all_attributes(

CAttr<#attr_class_name> #attr_variable;

)}; ///////////////////////////////////////////////////////////////////

// OBJECT CLASS : SEA.TORPEDO

//

class JTC_EXPORT CHLAObjSEA_TORPEDO : public CHLAObjSEA

{

public:

CHLAObjSEA_TORPEDO();

virtual ~CHLAObjSEA_TORPEDO() {}

public:

CAttr<JTCLongType> DEPTH;

};

.omd file에서의 Class

Object Class Template

출력 file에서의 Complex Data Type Class

적용

Page 13: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

Smart Adaptor (KHLAAdaptor)

Adaptor library

ApplicationDEVS Model

Inter-operational Object

HLA interface& callback

RTI method& callbacks

Application이 결정하는 interface(예: TCP/IP 통신) 방식으로 정보 교환

SimulationAlgorithm

DEVSim++ library

Data FormatConverting

ExternalInterface

AdaptorApplication

Callback 함수 호출 방식으로 정보 교환

Network Library

Simulator

Smart Adaptor

Page 14: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

Data Format Converting: Object

ADPObject

{

int index

char* name

encodeHLAObject();

decodeHLAObject();

}

HLAObject

{

ATTRIBUTE INDEX;

ATTRIBUTE NAME;

}

HLAObject: • HLA class generator에 의해 OMD file에 정의된 class이 자동 생성

ADPObject: • 개발자가 구현하는 HLAObject를 support하는 외부 interface 담당 class • 멤버변수: ATTRIBUTRE를 저장 • Encode/decodeHLAObject: 멤버변수를 ATTRIBUTE로 변환하거나 반대 과정을 통해 HLAObject를 update하는 process를 구현할 수 있도록 하는 virtual method override 필요

Page 15: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

HLA Interfaces & Callbacks HLA Interface

사용자가 메시지를 만들어서 직접 호출

RTI Callbacks

메시지 핸들러를 상속받아 내부를 구현

CADPMessage* pMsg = new CADPMessage; pMsg->m_uMsgID = CREATE_FEDERATION_EXECUTION; pMsg->SetArgument(2, new ADPString( "PingPongFederation" ), new ADPString( "PingPong.fed" )); ADPINTERFACE_PTR->Add(pMsg);

CFederateMgtHandler

CExFederateMgtHandler

상속

virtual void synchronizationPointRegistrationSucceeded(const char *label); virtual void synchronizationPointRegistrationFailed(const char *label); virtual void announceSynchronizationPoint(const char *label, const char *tag); virtual void federationSynchronized(const char *label); virtual void initiateFederateSave(const char *label); virtual void federationSaved(); virtual void federationNotSaved(); virtual void requestFederationRestoreSucceeded(const char *label); virtual void requestFederationRestoreFailed(const char *label,const char *reason); virtual void federationRestoreBegun(); virtual void initiateFederateRestore(const char *label, RTI::FederateHandle handle); virtual void federationRestored(); virtual void federationNotRestored();

Override되는 callback 함수 목록

이 함수의 경우 CFederateMgtHandler의 경우 아무 처리도 하지 않는다. CFederateMgtHandler를 상속한 CExFederateMgtHandler의 경우, 이 함수에 필요한 작업(화면에 NOT RESTORED 메시지 표시) 등을 수행하도록 함수 내부를 구현함으로써 Application에서 수행해야 할 작업을 추가가능하다.

Page 16: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

FEDEP (페더레이션 개발 및 실행 표준 프로세서)

페더레이션

실 행 및

출 력 수 집

데이타 분석

결 과 평 가

페더레이션

목적 정의

개 념 적

분 석

페더레이션

설 계

페더레이션

개 발

페더레이션

통 합/ 구 현

테 스 트

도메인 전문가

도메인 + M&S 전문가

M&S 전문가

설계 단계

구현 단계

실행 단계

Page 17: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

FEDEP 사용 모델 개발 예 (Ping Pong)

페더레이션 목적 정의 탁구 경기를 간단하게 표현

선수와 심판을 각각의 페더레이트로 구현

개념적 분석 기존의 PingPong 시뮬레이터를 재사용하면서 선수와 심판 시뮬레이터를

분리

선수와 선수 사이, 그리고 선수와 심판 사이에 공을 주고 받음

심판은 점수 관리

페더레이션 설계 통합된 PingPong 시뮬레이터 분리

각각의 시뮬레이터에 Adaptor 연결

페더레이션 개발 FOM 및 FED 파일 정의

Adaptor 구현 및 단독 엔진에 연동 관련 코드 삽입

페더레이션 통합 구현 및 테스트 2명의 선수와 심판 페더레이트가 RTI에 Join 후 시간 진행

탁구 경기 종료 조건에 의해 페더레이션 종료 체크

Page 18: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

페더레이션 구성도

HLA/RTI

Referee Adaptor

PlayerA Adaptor PlayerB Adaptor

Referee

Simulation Model

PlayerB

Simulation Model

PlayerA

Simulation Model

PingPong Federation

Page 19: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

기존 시뮬레이터 분리

PlayerA PlayerB

Referee

SERVA

SERV_SELF SERV_OTHER

SERVB

SERV_OTHER SERV_SELF

OUTB

OUT_SELF OUT_OTHER

OUTA

OUT_SELF OUT_OTHER

BALL_SEND BALL_REV

BALL_REV BALL_SEND

점수 관리

(A 점수, B 점수)

OUT,

SERVE

BALL, OUT

• 점수는 Referee가 관리하지만 Player들도 점수를 알고 있어야 함. Shared Object : SCORE (Attr: SCORE_A, SCORE_B)

• 시뮬레이터들 사이의 메시지 교환은 OUT, BALL, SERVE 이다. 하지만, 이것들은 모두 BALL로 볼 수 있고 FROM, TO 정보를 이용하여 구분할 수 있다. Interaction : BALL (Param: FROM, TO)

Page 20: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

FOM ///////////////////////////////////////////////////////////////////

// OBJECT CLASS : SCORE

//

class JTC_EXPORT CHLAObjSCORE : public CHLAObject

{

public:

CHLAObjSCORE();

CHLAObjSCORE(const char* theObjectClassStr);

CHLAObjSCORE( RTI::ObjectHandle theObject, const char *ObjectName,

RTI::ObjectClassHandle theObjectClass, const char objectClassName );

virtual ~CHLAObjSCORE() {}

CHLAObject* Create(RTI::ObjectHandle theObject,

RTI::ObjectClassHandle theObjectClass, const char *ObjectName );

virtual void RegisterAttributes();

public:

CAttr<JTCUShortType> SCORE_A;

CAttr<JTCUShortType> SCORE_B;

};

///////////////////////////////////////////////////////////////////

// INTERACTION CLASS : BALL

//

class JTC_EXPORT CIntBALL : public CInteraction

{

public:

CIntBALL();

CIntBALL(const char* name);

virtual ~CIntBALL() {}

virtual void RegisterParameters();

public:

CParam<JTCStringType> FROM;

CParam<JTCStringType> TO;

};

(Class (ID 4)

(Name "SCORE")

(PSCapabilities N)

(Attribute (Name "SCORE_A")

(DataType "unsigned short")

(Cardinality "1")

(Accuracy "perfect")

(AccuracyCondition "always")

(UpdateType Conditional)

(TransferAccept N)

(UpdateReflect UR)

)

(Attribute (Name "SCORE_B")

(DataType "unsigned short")

(Cardinality "1")

(Accuracy "perfect")

(AccuracyCondition "always")

(UpdateType Conditional)

(TransferAccept N)

(UpdateReflect UR)

)

)

(Interaction (ID 67)

(Name "BALL")

(ISRType IR)

(Parameter (Name "FROM")

(DataType "string")

(Cardinality "1")

(Accuracy "perfect")

(AccuracyCondition "always")

)

(Parameter (Name "TO")

(DataType "string")

(Cardinality "1")

(Accuracy "perfect")

(AccuracyCondition "always")

)

)

OMD PingPongFOM.h

HLA Class

Generator

Page 21: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

시뮬레이터와의 인터페이스 정의

MSG Name Sender Receiver Field_Name Field_Type Description

OUT_BALL Player Referee FIELD_TIME CBEDouble

FIELD_NAME CBEString Player의 이름

BALL Player Player FIELD_TIME CBEDouble

SCORE Referee Player

FIELD_TIME CBEDouble

FIELD_SCORE_A CBEInteger Player A의 점수

FIELD_SCORE_B CBEInteger Player B의 점수

SERVE Referee Player FIELD_TIME CBEDouble

FIELD_NAME CBEString Player의 이름

TIME_REQ Simulator Adaptor FIELD_TIME CBEDouble

TIME_GRANT Simulator Adaptor FIELD_TIME CBEDouble

1) 네트워크 패킷 정의

RegisterType( MSG_NAME, new SMSL::CIFPacket( FIELD_NAME1, FIELD_TYPE1, FIELD_NAME2, FIELD_TYPE2, … ) )

Ex.) RegisterType( OUT_BALL, new SMSL::CIFPacket(FIELD_TIME, CBEDouble, FIELD_NAME, CBEString) );

패킷 등록

패킷 송신 SMSL::CIFPacket* pBody = SMSL::CNetwork::GetFactory()->CloneBody<SMSL::CIFPacket>(OUT_BALL); pBody->Get<SMSL::CBEDouble>(FIELD_TIME) = 1.0; pBody->Get<SMSL::CBEString>(FIELD_NAME) = “PlayerA”; m_pConnection >Send( OUT_BALL, pBody );

Page 22: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

시뮬레이터와의 인터페이스 정의

2) 네트워크 핸들러 정의

• SMSL::CHandler 클래스 상속

• OnInitialize()

• 네트워크 시스템이 초기화된 후 호출됨.

• 일반적으로 사용자가 Listen() 함수 호출하도록 함.

• OnConnect()

• 연결이 되거나 연결 시도가 실패했을 경우 호출됨.

• OnSend()

• 데이터가 일정 부분 송신된 후 호출됨.

• OnReceive()

• 패킷을 수신한 후 호출됨.

• OnClose()

• 연결이 종료된 후 연결 관리 객체 (CConnection)가 삭제되기 전에 호출됨.

• OnSignal()

• Ctrl-C 등의 시그널을 받았을 경우 호출됨. 설정에서 시그널 핸들링을 하도록 하였을 때만 동작.

Page 23: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

서비스/Callback 지정

Federation Management

create, join, resign, destroy

Declaration Management

publish, subscribe

Object Management

update, reflect, send, receive

ADPObject/ADPInteraction의 Encode/Decode 함수 구현

Time Management

TAR, NER, TAG

시뮬레이터와의 시간 동기화

Callbacks

메시지 핸들러 상속 후 각각의 Callback에 대한 Action 구현

Page 24: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

PlayerFed 구성도

PlayerDisplay

(시뮬레이터)

PlayerFed

(연동 어댑터)

HLA/RTI

CDlgNetHandler

CFedNetHandler

CRTICallbackHandler CHLAAdapInterface

CObjScore

CIntBall

TCP/IP

CROHandler TimeAdvaceRequest() 함수 구현

연동 어댑터로 시간진행 요청 패킷 전송

Time Grant 시

시뮬레이터로 시간

진행 알림

Page 25: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

PlayerFed 코드

CObjScore Decode

bool CObjScore::decodeHLAObject(double time)

{

if( m_pHLAObject == NULL ) return false;

CHLAObjSCORE* pSrc = static_cast<CHLAObjSCORE*>( m_pHLAObject );

if( pSrc->SCORE_A.GetUpdate() )

{

m_nScoreA = pSrc->SCORE_A().GetValue();

}

if( pSrc->SCORE_B.GetUpdate() )

{

m_nScoreB = pSrc->SCORE_B().GetValue();

}

// 연동 --> 단독

CIFPacket* pBody = GLOBAL_PKT_FACTORY->CloneBody<CIFPacket>(SCORE);

pBody->Get<CBEDouble>(FIELD_TIME) = GLOBAL_ADP_PTR->GetEngineTime(time);

pBody->Get<CBEInteger>(FIELD_SCORE_A) = m_nScoreA;

pBody->Get<CBEInteger>(FIELD_SCORE_B) = m_nScoreB;

GLOBAL_NET_HANDLER->Send(SCORE, pBody);

return true;

}

Page 26: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

PlayerFed 코드

CIntBall Encode bool CInterBall::EncodeInteraction(unsigned int code, SMSL::CPacket* pBody)

{

if( m_pInteraction == NULL ) return false;

CIntBALL* pInter = static_cast<CIntBALL*>(m_pInteraction);

if( pInter == NULL ) return false;

pInter->SetAllParameterUpdateFlag(true);

// 패킷을 보고 Parameter 설정

if( code == BALL )

{

pInter->FROM().SetValue( "Player" );

pInter->TO().SetValue( "Player" );

}

else if( code == OUT_BALL )

{

std::string name = ((CIFPacket*)pBody)->Get<CBEString>(FIELD_NAME)();

pInter->FROM().SetValue( name.c_str() );

pInter->TO().SetValue( "Referee" );

}

else

{

return false;

}

return true;

}

Page 27: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

PlayerFed 코드

CIntBall Decode bool CInterBall::DecodeInteraction(double time, const char* theTag)

{

if( m_pInteraction == NULL ) return false;

CIntBALL *pInt = static_cast<CIntBALL*>(m_pInteraction);

std::string fromID = pInt->FROM().GetValue();

std::string toID = pInt->TO().GetValue();

if( fromID.compare("Referee") == 0 )

{

CIFPacket* pBody = GLOBAL_PKT_FACTORY->CloneBody<CIFPacket>(SERVE);

pBody->Get<CBEDouble>(FIELD_TIME) = GLOBAL_ADP_PTR->GetEngineTime(time);

pBody->Get<CBEString>(FIELD_NAME) = toID;

GLOBAL_NET_HANDLER->Send(SERVE, pBody);

}

// Referee로부터 오는 Interaction은 무시

else if( toID.compare("Referee") == 0 )

{

return false;

}

else

{

CIFPacket* pBody = GLOBAL_PKT_FACTORY->CloneBody<CIFPacket>(BALL);

pBody->Get<CBEDouble>(FIELD_TIME) = GLOBAL_ADP_PTR->GetEngineTime(time);

GLOBAL_NET_HANDLER->Send(BALL, pBody);

}

return true;

}

Page 28: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

PlayerFed 코드

RTICallbackHandler

Time Grant 시 시뮬레이터로 패킷 전송

void CPPTimeMgtHandler::timeAdvanceGrant(const RTI::FedTime& theTime, bool RTIGranted)

{

RTIfedTime fedTime(theTime);

double time = fedTime.getTime();

if( ADPINTERFACE_PTR->HLAOption.OperMode == CHLAOption::ALONE )

return;

time = GLOBAL_ADP_PTR->GetEngineTime(time);

CIFPacket* pBody = GLOBAL_PKT_FACTORY->CloneBody<CIFPacket>(TIME_GRANT);

pBody->Get<CBEDouble>(FIELD_TIME) = time;

GLOBAL_NET_HANDLER->Send(TIME_GRANT, pBody);

}

Page 29: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

PlayerDisplay 수정

ROHandler

연동 어댑터와의 시간 동기를 위해 함수 구현

void CROHandler::TimeAdvanceRequest(TimeType time)

{

CModel* pModel = m_pInterface->GetModel();

if( time <= pModel->GetTime() )

{

CDEVSimMessage *pMsg = new CDEVSimMessage();

pMsg->ID( DEVSIM_TIME_GRANT );

pMsg->SetArgument( 1, new TimeType( time ) );

DEVSINTERFACE_PTR->Add( pMsg );

return;

}

CIFPacket* pBody = SMSL::CNetwork::GetFactory()->CloneBody<CIFPacket>(TIME_REQ);

pBody->Get<CBEDouble>(FIELD_TIME) = time.GetValue();

m_pNetHandler->Send( TIME_REQ, pBody );

}

Page 30: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

실행 예

Page 31: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

연동 시뮬레이션 실행 순서

CHLAAdapInterface 객체 생성

RTI Callback 함수 핸들러 설정

메시지 핸들러 설정

전역 변수 설정

CGlobalInterface::SetGlobalInterface() 함수 이용

시뮬레이션 옵션 설정

엔진 시작

STATUS_RUNNIN 상태

시뮬레이션 시작

STATUS_SIMULATION 상태

시뮬레이션 종료

Page 32: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

연동 시뮬레이션 옵션(1/2) 멤버 변수 타입 범위(기본값) 의미

dInitialTime double 양의 실수(0) 시뮬레이션 시작 시간

CHLAAdapInterface 클래스의 SetInitialTime() 함수를 통해서만 설정

가능

bOutputFile bool (true)/false 로그를 파일에 기록할 것인지 여부

(true면 로그를 파일에 기록)

strLogFileName std::string 파일 이름

(HLA_ADAPTOR.log)

로그 파일 이름

lLogFileSize long 양의 정수

(2*1e9)

로그에 기록할 최대 파일 크기

lLogMask long 양의 정수(0) 로그 등급

TimeAdvanceMode _TimeAdvanceM

ode

(NER), TAR 시간 진행 모드 (NER: nextEventRequest, TAR: timeAdvanceRequest)

dTimeStep double 양의 실수

(1.0/60.0)

페더레이트의 시간 진행 스텝

dLookahead double 양의 실수

(59.0/3600.0)

Lookahead, TimeRegulating Federate가 TSO 이벤트를 발생시키기 위한 최소한의 delay time

bRealTime bool (true)/false Real-Time 모드로 동작할 것인지 여부 (true면 Real-Time으로 동작)

dTimeTick double 양의 실수 (0.1) RTI의 tick 함수 호출 시 maximum time

OperMode _OperMode ALONE, (INTER) 연동 어댑터 단독으로 실행할지, 시뮬레이터와의 통신을 통해 실행할지 여부

OperMode = ALONE인 경우, 연동 어댑터는 자체적으로 시간

진행을 하며, INTER인 경우 시간 진행을 시뮬레이터에 맡겨, 상호

통신을 통해 시뮬레이션 진행

Page 33: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

연동 시뮬레이션 옵션(2/2)

멤버 변수 타입 범위(기본값) 의미

TimeMode _TimeMode MSEC, SECOND,

MINUTE, (HOUR),

DAY

bRealTime = true 인 경우에, 시뮬레이션 시간 1을 실제 시간에 매핑할 단위. 예를 들어 SECOND이면 시뮬레이션 시간 1을 1초 흐르는 동안 실행하는 것이 Ratio 1이 된다.

dRatio double 양의 실수

(1.0)

bRealTime = true인 경우에, 실제 시간과 시뮬레이션 시간이 흐르는 비율을 정한다. TimeMode가 HOUR이고, dRatio=2이면 시뮬레이션 시간 1만큼 진행하는 데 실제 30분이 걸린다.

bMultiThread bool true/(false) Thread로 동작할 것인지 여부

(true면 Thread로 동작)

strSaveFileName std::string 파일 이름

(HLA_ADAPTOR.sav)

Save/Restore 시 사용할 파일 이름

bOutputConsole bool (true)/false 연동 어댑터가 실행되고 있는 콘솔창에 로그를 남길지 여부

(true면 콘솔창에 로그를 기록)

bTimeRegulation bool (true)/false 페더레이트가 TimeRegulating인지 여부

(true면 TimsRegulating Federate, TSO 이벤트를 발생시킨다.)

bTimeConstrained bool (true)/false 페더레이트가 TimeConstrained인지 여부

(true면 TimeConstrained Federate, TSO 이벤트를 받을 수 있다.)

Page 34: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

연동 시뮬레이션 실행 예 // CHLAAdapInterface 변수 선언 CHLAAdapInterface* m_pInterface;

// CHLAAdapInterface 객체 생성 m_pInterface = new CHLAAdapInterface();

// 사용자 재정의 핸들러 함수 설정 m_pInterface->SetFederateMgtHandler( new

CUserDefinedFederateMgtHandler() );

m_pInterface->SetObjectMgtHandler( new

CUserDefinedObjectMgtHandler() );

m_pInterface->SetOwnershipMgtHandler( new

CUserDefinedOwnershipMgtHandler() );

m_pInterface->SetTimeMgtHandler( new CUserDefinedTimeMgtHandler() );

m_pInterface->SetROMgtHandler( new CUserDefinedROHandler() );

m_pInterface->SetDefaultHandlers();

// 전역 변수로 설정 CGlobalInterface::SetGlobalInterface(m_pInterface);

// 시뮬레이션 옵션 설정

m_pInterface->HLAOption.bMultiThread = true;

m_pInterface->HLAOption.dTimeTick = 0.1;

Page 35: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

연동 시뮬레이션 실행 예 if( m_bNER )

{

m_pInterface->HLAOption.TimeAdvanceMode = CHLAOption::NER;

m_pInterface->HLAOption.dLookahead = 59.0/3600.0;

}

else

{

m_pInterface->HLAOption.TimeAdvanceMode = CHLAOption::TAR;

m_pInterface->HLAOption.dLookahead = 59.0/3600.0;

m_pInterface->SetTimeStep( 1.0/60.0 );

}

// 저장 파일 이름 설정 m_pInterface->HLAOption.strSaveFileName = "Converter";

// 로그 관련 설정 m_pInterface->HLAOption.bOutputConsole = true;

m_pInterface->HLAOption.bOutputFile = true;

m_pInterface->HLAOption.strLogFileName = “Converter.log”;

m_pInterface->HLAOption.lLogMask = _DEBUG_FLAG | INFO_FLAG |

_ERROR_FLAG | _SR_FLAG;

m_pInterface->HLAOption.lLogFileSize = 100*1024*1024;

m_pInterface->StartLogging();

// 엔진 시작 m_pInterface->Start();

// 시뮬레이션 시작 m_pInterface->SimulationStart();

// 시뮬레이션 종료 m_pInterface->Abort();

Page 36: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

PlayerDisplay.exe

Player 모델

이름 결정

Connect : 시뮬레이터와 연동 어댑터 연결.

Set Federate Name : 페더레이트 이름 설정.

START : 연동 어댑터 시작.

STOP : 연동 어댑터 종료.

Create : 페더레이션 생성.

Join : 페더레이트 참가.

Resign : 페더레이트 탈퇴.

Destroy : 페더레이션 소멸.

Simulation Start : 시뮬레이션 시작.

Simulation Stop : 시뮬레이션 종료.

Terminate Simulator : 시뮬레이션 프로그램 종료.

Page 37: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

Referee.exe

Connect : 시뮬레이터와 연동 어댑터 연결.

Set Federate Name : 페더레이트 이름 설정.

START : 연동 어댑터 시작.

STOP : 연동 어댑터 종료.

Object Register : 객체 등록.

Create : 페더레이션 생성.

Join : 페더레이트 참가.

Resign : 페더레이트 탈퇴.

Destroy : 페더레이션 소멸.

Simulation Start : 시뮬레이션 시작.

Simulation Stop : 시뮬레이션 종료.

Terminate Simulator : 시뮬레이션 프로그램 종료.

Page 38: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

시뮬레이션 순서

rtiExec 실행.

연동 어댑터 실행.

(PlayerFed.exe, RefereeFed.exe)

시뮬레이터 실행.

(PlayerDisplay.exe, RefereeDisplay.exe)

시뮬레이터와 연동 어댑터 연결.

IP 주소와 Listening 포트 설정하여 연결.

페더레이션 생성.

페더레이트 참가.

시뮬레이션 시작.

Referee 연동 엔진에 객체 등록.

연동 어댑터 시작.

Page 39: 예제를 통한 시뮬레이터 연동 이해 - Systems Modeling Simulation …sim.kaist.ac.kr/Course/IE801/2011/lecture_note/Lect22.pdf ·  · 2014-07-22m_Prob rand_num Model Player

IE801 – Lecture 22

시뮬레이션 순서

(1)

(2)

(5) (6)

(7)

(2) (3) (4)

(3) (4)

(5) (6)

(7)

(8)

(9)

(9)