예시: 이벤트 모드의 프로토콜 구성

예시: 이벤트 모드의 프로토콜 구성

이벤트 모드를 사용하여 장치에서 비동기적으로 전송된 데이터를 읽는 직렬
Port
개체에 포함된 NetLogic의 예입니다. 버튼 누름 이벤트에 연결된
OnClick
메서드를 사용하면 현재 읽기를 중지하고 새 읽기를 시작할 수 있습니다.
이벤트 모드를 사용하려면
0
속성을
Timeout
으로 설정해야 합니다. 이렇게 하면
ReadBytes
는 요청된 데이터가 직렬 포트에 도착하지 않는 한 차단됩니다.
CancelRead
메서드 또는
Close
메서드를 사용하여 읽기를 중단할 수 있습니다. 두 경우 모두
ReadCanceledException
예외가 생성됩니다. NetLogic을 완전히 닫으려면 NetLogic
Stop
에서
Close
메서드를 호출하여 보류 중인 읽기 작업을 종료해야 합니다.
샘플 프로젝트는 SerialPortDemoEventMode.zip에서 다운로드할 수 있습니다.
public class RuntimeNetlogic1 : BaseNetLogic { private SerialPort serialPort; private LongRunningTask task; public override void Start() { serialPort = (SerialPort)Owner; serialPort.Timeout = TimeSpan.FromMilliseconds(0.0); task = new LongRunningTask(Run, Owner); task.Start(); } [ExportMethod] public void OnClick() { // Cancel current read serialPort.CancelRead(); task.Cancel(); // Start new read task = new LongRunningTask(Run, Owner); task.Start(); } private void Run() { while(!task.IsCancellationRequested) { try { // Block until 3 bytes arrive on serial var result = serialPort.ReadBytes(3); foreach (var b in result) Log.Info(String.Format("0x{0:x2}", b)); } catch (ReadCanceledException ex) { // In case of read canceled, exit from the loop Log.Info(ex.Message); return; } catch (Exception e) { Log.Error(e.Message); } } } public override void Stop() { // Explicit call to Close to cancel pending read (if any) serialPort.Close(); task.Cancel(); } }
의견을 작성 부탁드립니다.
이 자료에 대한 문의사항이나 요청사항이 있습니까? 여기에 요청사항을 작성 부탁드립니다.