47 lines
1.3 KiB
TypeScript
47 lines
1.3 KiB
TypeScript
import * as serialport from 'serialport';
|
|
|
|
// interface ISerial {
|
|
// moisture: number;
|
|
// parser: serialport.ReadlineParser
|
|
// }
|
|
|
|
export default class Serial {
|
|
private moisture0: number;
|
|
private moisture1: number;
|
|
|
|
public constructor(path = '/dev/ttyUSB0', baudRate = 9600, delimiter = '\n') {
|
|
const port = new serialport.SerialPort({ path, baudRate });
|
|
const readline = new serialport.ReadlineParser({ delimiter });
|
|
const parser = port.pipe(readline);
|
|
parser.on('data', line => {
|
|
const data = JSON.parse(line)
|
|
const moisture0 = parseInt(data['A0'], 10);
|
|
const moisture1 = parseInt(data['A1'], 10);
|
|
if (!isNaN(moisture0) && !isNaN(moisture1)) {
|
|
this.moisture0 = moisture0;
|
|
this.moisture1 = moisture1;
|
|
}
|
|
else {
|
|
console.error("Error reading analog data")
|
|
}
|
|
});
|
|
port.on('error', err => {
|
|
console.error('Serial Error:', err.message);
|
|
});
|
|
}
|
|
|
|
private scale = (value: number) => {
|
|
const percent = (value / 1024) * 100;
|
|
return Math.min(Math.max(percent, 0), 100); // Clamp to 0-100 just in case
|
|
}
|
|
|
|
public getMoisture() {
|
|
return { moisture0: this.scale(this.moisture0), moisture1: this.scale(this.moisture1) };
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
} |