|
| 1 | +import { Service } from 'typedi'; |
| 2 | +import SerialPort from 'serialport'; |
| 3 | +import { PubSubEngine } from 'graphql-subscriptions'; |
| 4 | +import SerialPortInformation from '../../models/SerialPortInformation'; |
| 5 | +import PubSubTopic from '../../pubsub/enum/PubSubTopic'; |
| 6 | +import { LoggerService } from '../../logger'; |
| 7 | + |
| 8 | +@Service() |
| 9 | +export default class SerialMonitorService { |
| 10 | + port: SerialPort | null; |
| 11 | + |
| 12 | + constructor(private pubSub: PubSubEngine, private logger: LoggerService) { |
| 13 | + this.port = null; |
| 14 | + } |
| 15 | + |
| 16 | + private async sendLogs(data: string): Promise<void> { |
| 17 | + this.logger?.log('serial monitor stream message', { |
| 18 | + data, |
| 19 | + }); |
| 20 | + return this.pubSub!.publish(PubSubTopic.SerialMonitorStream, { |
| 21 | + data, |
| 22 | + }); |
| 23 | + } |
| 24 | + |
| 25 | + async getAvailableDevices(): Promise<SerialPortInformation[]> { |
| 26 | + const list = await SerialPort.list(); |
| 27 | + return list.map( |
| 28 | + (item) => new SerialPortInformation(item.path, item.manufacturer || '') |
| 29 | + ); |
| 30 | + } |
| 31 | + |
| 32 | + async connect(device: string, baudRate: number): Promise<void> { |
| 33 | + if (this.port !== null) { |
| 34 | + throw new Error('serial port is already being used'); |
| 35 | + } |
| 36 | + |
| 37 | + this.port = new SerialPort(device, { |
| 38 | + baudRate, |
| 39 | + }); |
| 40 | + |
| 41 | + // Open errors will be emitted as an error event |
| 42 | + this.port.on('error', (err) => { |
| 43 | + this.sendLogs(`Serial port error: ${err.message}`); |
| 44 | + this.port = null; |
| 45 | + }); |
| 46 | + |
| 47 | + // this.port.on(''); |
| 48 | + } |
| 49 | + |
| 50 | + async disconnect(): Promise<void> { |
| 51 | + if (this.port === null) { |
| 52 | + throw new Error('not connected'); |
| 53 | + } |
| 54 | + return new Promise((resolve, reject) => { |
| 55 | + this.port?.close((err) => { |
| 56 | + if (err) { |
| 57 | + reject(err); |
| 58 | + } else { |
| 59 | + resolve(); |
| 60 | + } |
| 61 | + }); |
| 62 | + }); |
| 63 | + } |
| 64 | +} |
0 commit comments