register-value-utils.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const {
  2. toFiniteNumber
  3. } = require('./calculation-context')
  4. function toAddressKey(address) {
  5. if (typeof address === 'number' && Number.isFinite(address)) {
  6. return Math.round(address).toString(16).toUpperCase()
  7. }
  8. const text = String(address || '').trim().toUpperCase()
  9. if (!text) return ''
  10. const hexText = text.startsWith('0X') ? text.slice(2) : text
  11. if (/^[0-9A-F]+$/.test(hexText)) {
  12. return parseInt(hexText, 16).toString(16).toUpperCase()
  13. }
  14. const numberValue = Number(text)
  15. if (Number.isFinite(numberValue)) {
  16. return Math.round(numberValue).toString(16).toUpperCase()
  17. }
  18. return text
  19. }
  20. function wordsToFloat(highWord, lowWord) {
  21. const highValue = Number(highWord)
  22. const lowValue = Number(lowWord)
  23. if (!Number.isInteger(highValue) || !Number.isInteger(lowValue)) return null
  24. const buffer = new ArrayBuffer(4)
  25. const view = new DataView(buffer)
  26. view.setUint16(0, highValue & 0xFFFF, false)
  27. view.setUint16(2, lowValue & 0xFFFF, false)
  28. return view.getFloat32(0, false)
  29. }
  30. function floatToWords(value) {
  31. const numberValue = toFiniteNumber(value, NaN)
  32. if (!Number.isFinite(numberValue)) return null
  33. const buffer = new ArrayBuffer(4)
  34. const view = new DataView(buffer)
  35. view.setFloat32(0, numberValue, false)
  36. return [view.getUint16(0, false), view.getUint16(2, false)]
  37. }
  38. function addCoilReadValues(readValues, startAddress, quantity, response) {
  39. if (!readValues || !readValues.coils || !response || !Array.isArray(response.dataBytes)) return
  40. for (let offset = 0; offset < quantity; offset += 1) {
  41. const byte = response.dataBytes[Math.floor(offset / 8)] || 0
  42. const bit = (byte >> (offset % 8)) & 0x01
  43. readValues.coils[toAddressKey(startAddress + offset)] = bit
  44. }
  45. }
  46. function addWordReadValues(readValues, startAddress, response) {
  47. if (!readValues || !readValues.words || !response || !Array.isArray(response.words)) return
  48. response.words.forEach((word, index) => {
  49. readValues.words[toAddressKey(startAddress + index)] = Number(word) & 0xFFFF
  50. })
  51. }
  52. function getRegisterWordCache(startAddress, words) {
  53. if (!Array.isArray(words)) return {}
  54. return words.reduce((result, word, index) => {
  55. result[startAddress + index] = Number(word) & 0xFFFF
  56. return result
  57. }, {})
  58. }
  59. module.exports = {
  60. addCoilReadValues,
  61. addWordReadValues,
  62. floatToWords,
  63. getRegisterWordCache,
  64. toAddressKey,
  65. wordsToFloat
  66. }