diff --git a/src/handler/client/WriteMultipleCoils.js b/src/handler/client/WriteMultipleCoils.js index 75a8218..c04ed3c 100644 --- a/src/handler/client/WriteMultipleCoils.js +++ b/src/handler/client/WriteMultipleCoils.js @@ -31,51 +31,50 @@ module.exports = stampit() }.bind(this) this.writeMultipleCoils = function (startAddress, coils, N) { - var defer = Promise.defer() - var fc = 15 - var basePdu = Buffer.allocUnsafe(6) - var pdu - - basePdu.writeUInt8(fc, 0) - basePdu.writeUInt16BE(startAddress, 1) - - if (coils instanceof Buffer) { - basePdu.writeUInt16BE(N, 3) - basePdu.writeUInt8(coils.length, 5) - pdu = Buffer.concat([basePdu, coils]) - } else if (coils instanceof Array) { - if (coils.length > 1968) { - defer.reject() - return - } + return new Promise(function (resolve, reject) { + var fc = 15 + var basePdu = Buffer.allocUnsafe(6) + var pdu + + basePdu.writeUInt8(fc, 0) + basePdu.writeUInt16BE(startAddress, 1) + + if (coils instanceof Buffer) { + basePdu.writeUInt16BE(N, 3) + basePdu.writeUInt8(coils.length, 5) + pdu = Buffer.concat([basePdu, coils]) + } else if (coils instanceof Array) { + if (coils.length > 1968) { + reject() + return + } - var byteCount = Math.ceil(coils.length / 8) - var curByte = 0 - var curByteIdx = 0 - var cntr = 0 - var payloadPdu = Buffer.allocUnsafe(byteCount) + var byteCount = Math.ceil(coils.length / 8) + var curByte = 0 + var curByteIdx = 0 + var cntr = 0 + var payloadPdu = Buffer.allocUnsafe(byteCount) - basePdu.writeUInt16BE(coils.length, 3) - basePdu.writeUInt8(byteCount, 5) + basePdu.writeUInt16BE(coils.length, 3) + basePdu.writeUInt8(byteCount, 5) - for (var i = 0; i < coils.length; i += 1) { - curByte += coils[i] ? Math.pow(2, cntr) : 0 + for (var i = 0; i < coils.length; i += 1) { + curByte += coils[i] ? Math.pow(2, cntr) : 0 - cntr = (cntr + 1) % 8 + cntr = (cntr + 1) % 8 - if (cntr === 0 || i === coils.length - 1) { - payloadPdu.writeUInt8(curByte, curByteIdx) - curByteIdx = curByteIdx + 1 - curByte = 0 + if (cntr === 0 || i === coils.length - 1) { + payloadPdu.writeUInt8(curByte, curByteIdx) + curByteIdx = curByteIdx + 1 + curByte = 0 + } } - } - pdu = Buffer.concat([basePdu, payloadPdu]) - } - - this.queueRequest(fc, pdu, defer) + pdu = Buffer.concat([basePdu, payloadPdu]) + } - return defer.promise + this.queueRequest(fc, pdu, { resolve: resolve, reject: reject }) + }.bind(this)) } init()