transport-helpers.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const {
  2. MODBUS_CRC_OPTIONS,
  3. hasValidCrc16Modbus
  4. } = require('./modbus-rtu/frame.js')
  5. const {
  6. getReadBufferHint,
  7. parseModbusRequest,
  8. readResponseFromBuffer
  9. } = require('./modbus-rtu/response.js')
  10. const {
  11. getBootloaderResponseLength,
  12. isBootloaderFrame
  13. } = require('./bootloader/frame.js')
  14. const {
  15. BYTE_ORDER_HIGH,
  16. hasValidCrc16Ccitt
  17. } = require('../utils/crc.js')
  18. function inspectReceivedBytes(rawBytes, context = {}) {
  19. if (!Array.isArray(rawBytes) || rawBytes.length < 4) return ''
  20. if (isBootloaderFrame(rawBytes)) {
  21. const expectedLength = getBootloaderResponseLength(rawBytes)
  22. if (expectedLength && rawBytes.length < expectedLength) return '片段'
  23. return hasValidCrc16Ccitt(rawBytes, { byteOrder: BYTE_ORDER_HIGH }) ? 'CRC OK' : 'CRC ERR'
  24. }
  25. return hasValidCrc16Modbus(rawBytes, MODBUS_CRC_OPTIONS) ? 'CRC OK' : (context.pendingRequest ? '片段' : 'CRC ERR')
  26. }
  27. function parseSendExpected(bytes) {
  28. const expected = parseModbusRequest(bytes)
  29. if (!expected) return expected
  30. if (expected.slaveAddress === 0x00 && [0x05, 0x06, 0x10, 0x42].includes(expected.functionCode)) return null
  31. if (expected.slaveAddress === 0x00 && [0x01, 0x02, 0x03, 0x04, 0x40, 0x41].includes(expected.functionCode)) return null
  32. return expected
  33. }
  34. module.exports = {
  35. getResponseBufferHint: getReadBufferHint,
  36. inspectReceivedBytes,
  37. parseSendExpected,
  38. readResponseFromBuffer
  39. }