87 lines
2.1 KiB
TypeScript
87 lines
2.1 KiB
TypeScript
import net from 'node:net'
|
|
|
|
interface LineConfig {
|
|
id: number
|
|
port: number
|
|
lineNumber: number
|
|
ip: string
|
|
stationId: number
|
|
apcName?: string
|
|
}
|
|
|
|
export default class LineConnection {
|
|
public client: net.Socket
|
|
public readonly config: LineConfig
|
|
public readonly socketIO: any
|
|
|
|
constructor(config: LineConfig, socketIO: any) {
|
|
this.config = config
|
|
this.socketIO = socketIO
|
|
this.client = new net.Socket()
|
|
}
|
|
|
|
connect() {
|
|
return new Promise<void>((resolve, reject) => {
|
|
const { ip, port, lineNumber, id, stationId } = this.config
|
|
|
|
this.client.connect(port, ip, () => {
|
|
console.log(`✅ Connected to line ${lineNumber} (${ip}:${port})`)
|
|
this.socketIO.emit('line_connected', {
|
|
stationId,
|
|
lineId: id,
|
|
lineNumber,
|
|
status: 'connected',
|
|
})
|
|
resolve()
|
|
})
|
|
|
|
this.client.on('data', (data) => {
|
|
const message = data.toString().trim()
|
|
console.log(`📨 [${this.config.apcName}] ${message}`)
|
|
this.socketIO.emit('line_output', {
|
|
stationId,
|
|
lineId: id,
|
|
data: message,
|
|
})
|
|
})
|
|
|
|
this.client.on('error', (err) => {
|
|
console.error(`❌ Error line ${lineNumber}:`, err.message)
|
|
this.socketIO.emit('line_error', {
|
|
stationId,
|
|
lineId: id,
|
|
error: err.message,
|
|
})
|
|
reject(err)
|
|
})
|
|
|
|
this.client.on('close', () => {
|
|
console.log(`🔌 Line ${lineNumber} disconnected`)
|
|
this.socketIO.emit('line_disconnected', {
|
|
stationId,
|
|
lineId: id,
|
|
lineNumber,
|
|
})
|
|
})
|
|
})
|
|
}
|
|
|
|
sendCommand(cmd: string) {
|
|
if (this.client.destroyed) {
|
|
console.log(`⚠️ Cannot send, line ${this.config.lineNumber} is closed`)
|
|
return
|
|
}
|
|
console.log(`➡️ [${this.config.apcName}] SEND:`, cmd)
|
|
this.client.write(`${cmd}\r\n`)
|
|
}
|
|
|
|
disconnect() {
|
|
try {
|
|
this.client.destroy()
|
|
console.log(`🔻 Closed connection to line ${this.config.lineNumber}`)
|
|
} catch (e) {
|
|
console.error('Error closing line:', e)
|
|
}
|
|
}
|
|
}
|