1
0

generic-modbus-poller.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const genericModbusService = require('./generic-modbus-service')
  2. const POLL_TIMER_ID = '__genericPoll'
  3. function shouldPoll(data) {
  4. return !!data
  5. && data.activeParamView === 'genericModbus'
  6. && !!data.connectedDevice
  7. && !!data.genericModbusAutoPollEnabled
  8. }
  9. function getPollableGroups(data) {
  10. return (data.genericModbusGroups || []).filter((group) => group.isReadOnly && !group.addressOverflow)
  11. }
  12. function createGenericModbusPoller(getData) {
  13. const timers = {}
  14. function clearTimer(timerId) {
  15. if (!timers[timerId]) return
  16. clearTimeout(timers[timerId])
  17. delete timers[timerId]
  18. }
  19. function clearAll() {
  20. Object.keys(timers).forEach(clearTimer)
  21. }
  22. function schedule(delay) {
  23. clearTimer(POLL_TIMER_ID)
  24. timers[POLL_TIMER_ID] = setTimeout(async () => {
  25. const data = getData()
  26. if (!shouldPoll(data)) {
  27. clearTimer(POLL_TIMER_ID)
  28. return
  29. }
  30. for (const group of getPollableGroups(data)) {
  31. const latestData = getData()
  32. if (!shouldPoll(latestData)) break
  33. await genericModbusService.readGroup(group.id, {
  34. maxPacketLength: latestData.genericModbusMaxPacketLength,
  35. showModal: false
  36. })
  37. }
  38. const latestData = getData()
  39. if (shouldPoll(latestData)) {
  40. schedule(latestData.genericModbusPollInterval || 100)
  41. }
  42. }, delay)
  43. }
  44. function scheduleVisible() {
  45. const data = getData()
  46. if (!shouldPoll(data)) {
  47. clearAll()
  48. return
  49. }
  50. schedule(data.genericModbusPollInterval || 100)
  51. }
  52. return {
  53. clearAll,
  54. clearTimer,
  55. schedule,
  56. scheduleVisible
  57. }
  58. }
  59. module.exports = {
  60. createGenericModbusPoller
  61. }