I have code below that is pulling a byte from a modbus which I need to now get the bits MSB to LSB. I cannot seem to find a way to make that happen. The end result will I will know which but is On and which is Off. After this I will want to be able to write back but that is another day.
function readbool(slv, from, numcoils, func) {
local endaddress = (numcoils/8)-1;
local reqblob = blob();
/* Construct the request */
reqblob.writen(slv, 'b'); // Slave address
reqblob.writen(func, 'b'); // Function code
reqblob.writen(swap2(from), 'w'); // Start address
reqblob.writen(swap2(endaddress), 'w'); // End address
reqblob.writen(crc16(reqblob), 'w'); // CRC
/* Collaborate and listen */
local rspblob = this.dataTxRx(reqblob);
checkForException(rspblob, func);
rspblob.seek(2);
local numbytes = rspblob.readn('b');
if(numbytes != (numcoils/8)) {
throw "Unexpected response length: " + numbytes + " != " + numcoils;
}
server.log("readbool " + numbytes);
rspblob.seek(3);
local valblob = rspblob.readblob(2*numcoils);
valblob.swap2();
local valarr = [];
for(local i = 0; i < numbytes; i++) {
valarr.append(valblob.readn('b'));
}
return valarr;
}