在 NestJS 中添加串口和 USB?
Adding serialport and usb in NestJS?
NestJS可以加串口和USB包吗?我似乎找不到任何关于这些的东西。
- 在您的 serial.module.ts 中,通过自定义工厂提供商创建您的自定义串行处理程序服务
import { SerialHandlerService } from './serial-handler.service';
@Module({
providers: [
{
provide: 'SerialHandlerService',
useFactory: SerialHandlerService,
},
],
})
export class SerialModule {}
- 在同一文件夹中创建序列号-handler.service.ts
import * as SerialPort from 'serialport';
const Readline = SerialPort.parsers.Readline;
export const SerialHandlerService = () => {
const port = new SerialPort(
{YOUR_SERIAL_PORT},
{
baudRate: {YOUR_SERIAL_BOADRATE},
dataBits: {YOUR_SERIAL_DATABITS},
stopBits: {YOUR_SERIAL_STOPBITS},
parity: {YOUR_SERIAL_PARITY},
},
(err) => {
if (err) {
console.error(err)
// Handle Error
}
console.log('success')
},
);
// I'm using Readline parser here. But, You can change parser that you want!
const parser = new Readline({ delimiter: '\r\n' });
port.pipe(parser);
port.on('open', () => {
console.info('port opened');
});
parser.on('data', (data) => {
console.log(data);
// Data is string, process your data below!
}
}
- 将您的 serial.module.ts 添加到您的 app.module.ts
@Module({
imports: [
// your other modules...
SerialModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
[参考:https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory]
NestJS可以加串口和USB包吗?我似乎找不到任何关于这些的东西。
- 在您的 serial.module.ts 中,通过自定义工厂提供商创建您的自定义串行处理程序服务
import { SerialHandlerService } from './serial-handler.service';
@Module({
providers: [
{
provide: 'SerialHandlerService',
useFactory: SerialHandlerService,
},
],
})
export class SerialModule {}
- 在同一文件夹中创建序列号-handler.service.ts
import * as SerialPort from 'serialport';
const Readline = SerialPort.parsers.Readline;
export const SerialHandlerService = () => {
const port = new SerialPort(
{YOUR_SERIAL_PORT},
{
baudRate: {YOUR_SERIAL_BOADRATE},
dataBits: {YOUR_SERIAL_DATABITS},
stopBits: {YOUR_SERIAL_STOPBITS},
parity: {YOUR_SERIAL_PARITY},
},
(err) => {
if (err) {
console.error(err)
// Handle Error
}
console.log('success')
},
);
// I'm using Readline parser here. But, You can change parser that you want!
const parser = new Readline({ delimiter: '\r\n' });
port.pipe(parser);
port.on('open', () => {
console.info('port opened');
});
parser.on('data', (data) => {
console.log(data);
// Data is string, process your data below!
}
}
- 将您的 serial.module.ts 添加到您的 app.module.ts
@Module({
imports: [
// your other modules...
SerialModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
[参考:https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory]