AbstractModbusRequest.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package wei.yigulu.modbus.domain.request;
  2. import lombok.Data;
  3. import lombok.experimental.Accessors;
  4. import wei.yigulu.modbus.domain.FunctionCode;
  5. import wei.yigulu.modbus.domain.datatype.numeric.P_AB;
  6. import wei.yigulu.modbus.exceptiom.ModbusException;
  7. import java.math.BigDecimal;
  8. import java.nio.ByteBuffer;
  9. import java.util.List;
  10. /**
  11. * modbus请求数据报文的数据帧的抽象类
  12. *
  13. * @author: xiuwei
  14. * @version:
  15. */
  16. @Data
  17. @Accessors(chain = true)
  18. public class AbstractModbusRequest {
  19. /**
  20. * 客户端地址 一字节
  21. */
  22. protected Integer slaveId = 01;
  23. /**
  24. * 功能码 一字节
  25. */
  26. protected FunctionCode functionCode = FunctionCode.READ_HOLDING_REGISTERS;
  27. /**
  28. * 请求数据的起始地址位 两字节
  29. */
  30. protected Integer startAddress;
  31. /**
  32. * 请求的寄存器的数量 两字节
  33. */
  34. protected Integer quantity;
  35. /**
  36. * 编码
  37. *
  38. * @param bytes 字节
  39. */
  40. public void encode(List<Byte> bytes) {
  41. bytes.add((byte) (slaveId & 0xff));
  42. bytes.add((byte) (functionCode.getCode() & 0xff));
  43. new P_AB(BigDecimal.valueOf(startAddress)).encode(bytes);
  44. new P_AB(BigDecimal.valueOf(quantity)).encode(bytes);
  45. }
  46. /**
  47. * 解码
  48. *
  49. * @param byteBuf 字节缓冲
  50. */
  51. public AbstractModbusRequest decode(ByteBuffer byteBuf) throws ModbusException {
  52. this.setSlaveId(byteBuf.get() & 0xff);
  53. this.setFunctionCode(FunctionCode.valueOf(byteBuf.get() & 0xff));
  54. this.setStartAddress(new P_AB().decode(byteBuf).getValue().intValue());
  55. this.setQuantity(new P_AB().decode(byteBuf).getValue().intValue());
  56. return this;
  57. }
  58. }