1
0

control-service.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. const {
  2. buildReadFrame,
  3. buildWriteMultipleRegistersFrame,
  4. buildWriteSingleCoilFrame,
  5. buildWriteSingleRegisterFrame,
  6. MAX_READ_REGISTER_QUANTITY
  7. } = require('./modbus-rtu')
  8. const controlState = require('./control-page-state')
  9. const transport = require('./ble-transport')
  10. const {
  11. addCoilReadValues
  12. } = require('./register-value-utils')
  13. let state = controlState.createInitialState()
  14. let autoReadTimer = null
  15. let unsubscribeTransport = null
  16. const subscribers = []
  17. function getState() {
  18. return {
  19. ...state
  20. }
  21. }
  22. function notify() {
  23. const nextState = getState()
  24. subscribers.slice().forEach((subscriber) => {
  25. subscriber(nextState)
  26. })
  27. }
  28. function setState(changedData) {
  29. state = {
  30. ...state,
  31. ...changedData
  32. }
  33. notify()
  34. }
  35. function splitReadChunks(startAddress, quantity) {
  36. const chunks = []
  37. let offset = 0
  38. while (offset < quantity) {
  39. const chunkQuantity = Math.min(quantity - offset, MAX_READ_REGISTER_QUANTITY)
  40. chunks.push({
  41. address: startAddress + offset,
  42. quantity: chunkQuantity
  43. })
  44. offset += chunkQuantity
  45. }
  46. return chunks
  47. }
  48. async function readRegisterChunks(slaveAddress, functionCode, startAddress, quantity, label, expectedKind, options = {}) {
  49. const chunks = splitReadChunks(startAddress, quantity)
  50. const words = []
  51. for (const chunk of chunks) {
  52. const response = await transport.sendManagedFrame(
  53. buildReadFrame(slaveAddress, functionCode, chunk.address, chunk.quantity),
  54. chunks.length > 1 ? `${label} ${chunk.address.toString(16).toUpperCase()}-${(chunk.address + chunk.quantity - 1).toString(16).toUpperCase()}` : label,
  55. {
  56. address: chunk.address,
  57. functionCode,
  58. kind: expectedKind,
  59. quantity: chunk.quantity,
  60. slaveAddress
  61. },
  62. {
  63. showModal: options.showModal
  64. }
  65. )
  66. if (!response) return null
  67. const chunkWords = response.words || []
  68. chunkWords.forEach((word, index) => {
  69. words[chunk.address - startAddress + index] = Number(word) & 0xFFFF
  70. })
  71. if (typeof options.onChunk === 'function') {
  72. options.onChunk(response, chunk)
  73. }
  74. }
  75. return words
  76. }
  77. function subscribe(subscriber) {
  78. if (typeof subscriber !== 'function') return () => {}
  79. subscribers.push(subscriber)
  80. subscriber(getState())
  81. return () => {
  82. const index = subscribers.indexOf(subscriber)
  83. if (index >= 0) subscribers.splice(index, 1)
  84. }
  85. }
  86. function init() {
  87. transport.init()
  88. if (unsubscribeTransport) return
  89. unsubscribeTransport = transport.subscribe((transportState) => {
  90. const nextState = controlState.applyTransportState(state, transportState)
  91. if (nextState.autoReadStatus === false) {
  92. stopAutoReadStatus()
  93. }
  94. setState(nextState)
  95. })
  96. }
  97. function syncSharedInputs() {
  98. controlState.setSharedInputValues(state.motorParameterInputRegisters)
  99. }
  100. function applyControlReadValues(coilValues) {
  101. setState(controlState.applyControlReadValues(state, coilValues))
  102. }
  103. function applyMotorReadWords(words, startAddress = controlState.MOTOR_PARAM_START_ADDRESS) {
  104. const registerWordCache = controlState.getRegisterWordCache(startAddress, words)
  105. const motorState = controlState.applyMotorParameterReadValues(state, registerWordCache)
  106. const nextState = {
  107. ...state,
  108. ...motorState
  109. }
  110. setState({
  111. ...motorState,
  112. ...controlState.applySpeedCommandReadValue(nextState, registerWordCache[0x68])
  113. })
  114. }
  115. function applyDriverReadWords(words) {
  116. setState(controlState.applyDriverParameterReadValues(state, words))
  117. }
  118. function applyStatusReadWords(words, startAddress = controlState.STATUS_START_ADDRESS) {
  119. setState(controlState.applyStatusReadValues(words, startAddress))
  120. }
  121. function getSharedSlaveAddress() {
  122. try {
  123. return transport.getSlaveAddress()
  124. } catch (error) {
  125. transport.showCommandAlert('从机地址错误', error.message)
  126. return null
  127. }
  128. }
  129. function updateMotorParameterInput(index, value) {
  130. setState(controlState.applyMotorParameterInput(state, index, value))
  131. }
  132. function updateMotorParameterBlur(index, value) {
  133. setState(controlState.applyMotorParameterBlur(state, index, value))
  134. }
  135. function updateSpeedCommandInput(value) {
  136. setState(controlState.applySpeedCommandInput(state, value))
  137. }
  138. function updateSpeedCommandBlur(value) {
  139. setState(controlState.applySpeedCommandBlur(state, value))
  140. sendSpeedCommand()
  141. }
  142. function getSpeedCommandWriteWord() {
  143. const writeValue = Number(state.speedCommand.writeValue)
  144. if (!Number.isFinite(writeValue)) return null
  145. const word = Math.round(writeValue)
  146. return word >= 0 && word <= 0xFFFF ? word : null
  147. }
  148. async function sendSpeedCommand() {
  149. const slaveAddress = getSharedSlaveAddress()
  150. if (slaveAddress === null) return false
  151. const writeWord = getSpeedCommandWriteWord()
  152. if (writeWord === null) {
  153. transport.showCommandAlert('转速命令错误', '请检查转速命令输入值')
  154. return false
  155. }
  156. const address = parseInt(state.speedCommand.address, 16)
  157. const response = await transport.sendManagedFrame(
  158. buildWriteSingleRegisterFrame(slaveAddress, address, writeWord),
  159. '转速命令',
  160. {
  161. address,
  162. functionCode: 0x06,
  163. kind: 'speed-command-write',
  164. quantity: 1,
  165. value: writeWord,
  166. slaveAddress
  167. }
  168. )
  169. if (response) {
  170. setState({
  171. ...controlState.clearSpeedCommandDirty(state),
  172. systemTip: '转速命令已下发'
  173. })
  174. return true
  175. }
  176. return false
  177. }
  178. async function sendControlCommand(key) {
  179. const button = state.controlButtons
  180. .concat(state.controlActionButtons || [])
  181. .find((item) => item.key === key)
  182. if (!button) return
  183. const slaveAddress = getSharedSlaveAddress()
  184. if (slaveAddress === null) return
  185. const writeValue = controlState.getControlButtonWriteValue(button)
  186. const address = parseInt(button.address, 16)
  187. const coilEnabled = Number(writeValue) !== 0
  188. const response = await transport.sendManagedFrame(
  189. buildWriteSingleCoilFrame(slaveAddress, address, coilEnabled),
  190. button.name,
  191. {
  192. address,
  193. functionCode: 0x05,
  194. kind: 'control-write',
  195. quantity: 1,
  196. value: coilEnabled ? 0xFF00 : 0x0000,
  197. slaveAddress
  198. }
  199. )
  200. if (response) {
  201. setState(controlState.applyControlSuccess(state, button))
  202. }
  203. }
  204. async function readControlStatus() {
  205. const slaveAddress = getSharedSlaveAddress()
  206. if (slaveAddress === null) return false
  207. const startAddress = 0x00
  208. const quantity = 3
  209. const response = await transport.sendManagedFrame(
  210. buildReadFrame(slaveAddress, 0x01, startAddress, quantity),
  211. '控制状态读取',
  212. {
  213. address: startAddress,
  214. functionCode: 0x01,
  215. kind: 'control-status-read',
  216. quantity,
  217. slaveAddress
  218. }
  219. )
  220. if (!response) return false
  221. const readValues = {
  222. coils: {}
  223. }
  224. addCoilReadValues(readValues, startAddress, quantity, response)
  225. setState({
  226. ...controlState.applyControlReadValues(state, readValues.coils),
  227. systemTip: '控制状态读取完成'
  228. })
  229. return true
  230. }
  231. async function readMotorParameters() {
  232. if (state.isReadingMotor) return
  233. const slaveAddress = getSharedSlaveAddress()
  234. if (slaveAddress === null) return
  235. setState({
  236. errorText: '',
  237. isReadingMotor: true,
  238. systemTip: ''
  239. })
  240. try {
  241. const words = await readRegisterChunks(
  242. slaveAddress,
  243. 0x03,
  244. controlState.MOTOR_PARAM_START_ADDRESS,
  245. controlState.MOTOR_PARAM_WORD_COUNT,
  246. '电机参数读取',
  247. 'motor-main-read',
  248. { showModal: true }
  249. )
  250. if (!words) return
  251. const registerWordCache = controlState.getRegisterWordCache(controlState.MOTOR_PARAM_START_ADDRESS, words)
  252. setState({
  253. ...controlState.applyMotorParameterReadValues(state, registerWordCache),
  254. systemTip: '电机参数读取完成'
  255. })
  256. } finally {
  257. setState({
  258. isReadingMotor: false
  259. })
  260. }
  261. }
  262. async function writeMotorParameters() {
  263. if (state.isWritingMotor) return
  264. const slaveAddress = getSharedSlaveAddress()
  265. if (slaveAddress === null) return
  266. const mainWrite = controlState.buildMotorMainWriteValues(state)
  267. if (!mainWrite.values) {
  268. transport.showCommandAlert('参数错误', mainWrite.errorText)
  269. return
  270. }
  271. setState({
  272. errorText: '',
  273. isWritingMotor: true,
  274. systemTip: ''
  275. })
  276. try {
  277. const mainResponse = await transport.sendManagedFrame(
  278. buildWriteMultipleRegistersFrame(
  279. slaveAddress,
  280. controlState.MOTOR_PARAM_START_ADDRESS,
  281. mainWrite.values
  282. ),
  283. '电机参数写入',
  284. {
  285. address: controlState.MOTOR_PARAM_START_ADDRESS,
  286. functionCode: 0x10,
  287. kind: 'motor-main-write',
  288. quantity: mainWrite.values.length,
  289. slaveAddress
  290. }
  291. )
  292. if (!mainResponse) return
  293. setState({
  294. ...controlState.clearMotorParameterDirty(state),
  295. systemTip: '电机参数写入完成'
  296. })
  297. } finally {
  298. setState({
  299. isWritingMotor: false
  300. })
  301. }
  302. }
  303. async function readDriverParameters() {
  304. if (state.isReadingDriver) return
  305. const slaveAddress = getSharedSlaveAddress()
  306. if (slaveAddress === null) return
  307. setState({
  308. errorText: '',
  309. isReadingDriver: true,
  310. systemTip: ''
  311. })
  312. try {
  313. const words = await readRegisterChunks(
  314. slaveAddress,
  315. 0x04,
  316. controlState.DRIVER_PARAM_START_ADDRESS,
  317. controlState.DRIVER_PARAM_WORD_COUNT,
  318. '驱动器硬件参数读取',
  319. 'driver-read',
  320. { showModal: true }
  321. )
  322. if (words) {
  323. setState({
  324. ...controlState.applyDriverParameterReadValues(state, words),
  325. systemTip: '驱动器硬件参数读取完成'
  326. })
  327. }
  328. } finally {
  329. setState({
  330. isReadingDriver: false
  331. })
  332. }
  333. }
  334. function setAutoReadStatus(autoReadStatus) {
  335. setState({
  336. autoReadStatus
  337. })
  338. if (autoReadStatus) {
  339. scheduleAutoReadStatus(0)
  340. return
  341. }
  342. stopAutoReadStatus()
  343. }
  344. function setAutoReadInterval(value) {
  345. const autoReadInterval = controlState.clampNumber(
  346. value,
  347. controlState.AUTO_READ_MIN_INTERVAL,
  348. controlState.AUTO_READ_MAX_INTERVAL,
  349. state.autoReadInterval
  350. )
  351. setState({
  352. autoReadInterval
  353. })
  354. if (state.autoReadStatus) {
  355. scheduleAutoReadStatus(autoReadInterval)
  356. }
  357. }
  358. async function readStatus(options = {}) {
  359. if (options.auto && !state.connectedDevice) return false
  360. const slaveAddress = getSharedSlaveAddress()
  361. if (slaveAddress === null) return false
  362. const words = await readRegisterChunks(
  363. slaveAddress,
  364. 0x04,
  365. controlState.STATUS_START_ADDRESS,
  366. controlState.STATUS_WORD_COUNT,
  367. '状态读取',
  368. 'status-read',
  369. { showModal: !options.auto }
  370. )
  371. if (words) {
  372. setState({
  373. ...controlState.applyStatusReadValues(words, controlState.STATUS_START_ADDRESS),
  374. systemTip: options.auto ? '' : '状态读取完成'
  375. })
  376. }
  377. return words
  378. }
  379. function scheduleAutoReadStatus(delay) {
  380. stopAutoReadStatus()
  381. autoReadTimer = setTimeout(async () => {
  382. if (!state.autoReadStatus) return
  383. await readStatus({
  384. auto: true
  385. })
  386. scheduleAutoReadStatus(state.autoReadInterval)
  387. }, delay)
  388. }
  389. function stopAutoReadStatus() {
  390. if (!autoReadTimer) return
  391. clearTimeout(autoReadTimer)
  392. autoReadTimer = null
  393. }
  394. module.exports = {
  395. getState,
  396. init,
  397. applyControlReadValues,
  398. applyDriverReadWords,
  399. applyMotorReadWords,
  400. applyStatusReadWords,
  401. readControlStatus,
  402. readDriverParameters,
  403. readMotorParameters,
  404. readStatus,
  405. sendControlCommand,
  406. sendSpeedCommand,
  407. setAutoReadInterval,
  408. setAutoReadStatus,
  409. stopAutoReadStatus,
  410. subscribe,
  411. syncSharedInputs,
  412. updateMotorParameterBlur,
  413. updateMotorParameterInput,
  414. updateSpeedCommandBlur,
  415. updateSpeedCommandInput,
  416. writeMotorParameters
  417. }