본문 바로가기
C++

패킷(RTU) 구조 만들기 예시

by 돌맹96 2023. 6. 25.
728x90
반응형

패킷 구조별 data struct를 구성할 필요가 있다.

Slave ID Function Code Address Number of Data Data Size Data CRC
1Byte 1Byte 2Bytes 2Bytes 1Bytes n Bytes 2 Bytes

예를 들어 RTU의 패킷이 다음과 같이 구성되어 있다면 RTU Request의 구조체는 다음과 같이 정의할 수 있다.

typedef struct{
	UINT8 unUnitId; // Slave ID
	UINT8 unFunctionCode; // Function Code
	UINT16 unAddress; // Address
	UINT16 unData;
	UINT16 unCrc; // Data Size
}ModbusRtuRequest;

패킷의 값이 아래 그림과 같다면

패킷 예제 1

* Master(Poll)가 Slave에게 주소 0x0부터 3개의 데이터 읽기를 요청하는 예제

  *Master -> Slave

Slave ID Function Address Number of Data CRC
01 03 00 00 00 03 05 CB

다음과 같이 넣어 줄 수 있다.

void Test(){
	ModbusRtuRequest req;
	BYTE *pp = (BYTE*)&req;
	
	memset(&req, 0, sizeof(ModbusRtuRequest));	

	req.unUnitId = 0x01;
	req.unFunctionCode = 0x03;
	req.unAddress = 0x0000;
	req.unCount = 0x0003;
	req.unCrc = 0x05CB;

	return;
}

Response의 경우

* Slave -> Master

Slave ID Function Data Size(Byte) Data CRC
01 03 06 00 01 00 02 00 03 FD 74

Data의 사이즈가 가변적이라 다르게 처리해야한다.

 

typedef struct
{
	UINT8 unUnitId; // Slave ID
	UINT8 unFunctionCode; // Function Code
	UINT8 unByteCount; // Data size
	UINT8 Data; // Data pointer
}ModbusRtuResponse;

 

이상으로 패킷 만드는 예시를 봤다.

728x90
반응형