AbstractModbusResponse.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package wei.yigulu.modbus.domain.response;
  2. import com.google.common.primitives.Bytes;
  3. import lombok.Getter;
  4. import lombok.Setter;
  5. import wei.yigulu.modbus.domain.FunctionCode;
  6. import wei.yigulu.modbus.domain.ModbusPacketInterface;
  7. import wei.yigulu.modbus.exceptiom.ModbusException;
  8. import java.nio.ByteBuffer;
  9. import java.util.List;
  10. /**
  11. * modbus的响应报文 包含数据的 报文 的抽象类
  12. *
  13. * @author: xiuwei
  14. * @version:
  15. */
  16. @Setter
  17. @Getter
  18. public class AbstractModbusResponse implements ModbusPacketInterface {
  19. /**
  20. * 设备号 1字节
  21. */
  22. protected Integer slaveId;
  23. /**
  24. * 功能码 1字节
  25. */
  26. protected FunctionCode functionCode;
  27. /**
  28. * 表示数据的 字节 数量 1字节
  29. */
  30. protected Integer dataBitNum;
  31. /**
  32. * 用于表示数据的字节
  33. */
  34. protected byte[] dataBytes;
  35. @Override
  36. public AbstractModbusResponse decode(ByteBuffer byteBuf) throws ModbusException {
  37. this.slaveId = (int) byteBuf.get() & 0xff;
  38. this.functionCode = FunctionCode.valueOf((int) byteBuf.get() & 0xff);
  39. this.dataBitNum = (int) byteBuf.get() & 0xff;
  40. this.dataBytes = new byte[this.dataBitNum];
  41. byteBuf.get(this.dataBytes);
  42. return this;
  43. }
  44. @Override
  45. public AbstractModbusResponse encode(List<Byte> bytes) throws ModbusException {
  46. bytes.add((byte) (slaveId & 0xff));
  47. bytes.add((byte) (functionCode.getCode() & 0xff));
  48. bytes.add((byte) (dataBytes.length & 0xff));
  49. bytes.addAll(Bytes.asList(dataBytes));
  50. return this;
  51. }
  52. }