I have made a code to read data from a device then confert the data to be readable. Now my co-worker told me to make it as a library so he can get the data from it, but I just learn javascript and node.js so I don’t know how.
This is my code:
// create an empty modbus client
const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();
let timeoutRunRefHoldings = null;
// open connection to a serial port
client.connectRTUBuffered("/dev/ttyUSB0", { baudRate: 9600 })
.then(setClient1)
.then(function() {
console.log("Connected"); })
async function setClient1() {
// set the client's unit id
// set a timout for requests default is null (no timeout)
client.setID(1);
// run program
console.log("Flow rate:", await ReadReg(0,2) + " m³/h");
console.log("Velocity:", await ReadReg(4,2) + " m/s"),
console.log("Fluid sound speed:", await ReadReg(6,2) + " m/s");
console.log("Temperature #1/inlet:", await ReadReg(32,2) + " °C");
console.log("Temperature #2/inlet:", await ReadReg(34,2) + " °C");
}
async function ReadReg(addr, len) {
let regVal = await client.readHoldingRegisters(addr, len)
return REAL4(...regVal.data)
}
function REAL4(reg1, reg2){
// i) Convert the first register into binary
const value1=parseInt(reg1,10);
var binaryVl1=value1.toString(2);
while (binaryVl1.length < 16) {
binaryVl1 = '0'+binaryVl1;
}
// ii) Convert the second register into binary
const value2=parseInt(reg2,10);
var binaryVl2=value2.toString(2);
while (binaryVl2.length < 16) {
binaryVl2 = '0'+binaryVl2;
}
// iii) Combine Reg1 & Reg2
const combine=binaryVl2+binaryVl1;
const cb16x=(parseInt(combine, 2)).toString(16);
const buffer = new ArrayBuffer(4);
const bytes = new Uint8Array(buffer);
bytes[0] = '0x'+cb16x.substring(0,2);
bytes[1] = '0x'+cb16x.substring(2,4);
bytes[2] = '0x'+cb16x.substring(4,6);
bytes[3] = '0x'+cb16x.substring(6);
// iv) Convert combine into float(IEEE 754 floating point)
var view = new DataView(buffer);
const result=(view.getFloat32(0, false)).toPrecision(6);
return(result);
}
So, if I have to make it into a library should I remove console.log ?
I really don’t know anything about libraries.