我编写了一个代码来从设备读取数据,然后将数据赋予可读性。现在我的同事告诉我把它做成一个库,这样他就可以从中获取数据,但我只是学习 javascript 和 node.js,所以我不知道怎么做。
这是我的代码:
// 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);
}
所以,如果我必须把它变成一个库,我应该删除 console.log 吗? 我真的对图书馆一无所知。