Update apc

This commit is contained in:
nguyentrungthat 2025-11-04 16:52:26 +07:00
parent abda7c4e99
commit d031c1e93e
7 changed files with 685 additions and 676 deletions

View File

@ -5,7 +5,7 @@ interface APCOptions {
port?: number
username: string
password: string
onData?: (data: string) => void
onData?: (data: string, status: string) => void
number?: number
keep_connect?: boolean
}
@ -26,7 +26,7 @@ class APCController {
private buffer: string
private output: string
private promptCallbacks: PromptCallback[]
private onData: (data: string) => void
private onData: (data: string, status: string) => void
private retryConnect: number
constructor({ host, port = 23, username, password, onData, number }: APCOptions) {
@ -80,7 +80,7 @@ class APCController {
this.buffer += data
this.buffer = this.buffer.slice(-1000)
this.onData(this.buffer)
this.onData(this.buffer, this.status)
if (this.promptCallbacks.length > 0) {
const { prompt, callback } = this.promptCallbacks[0]
@ -95,14 +95,14 @@ class APCController {
private _handleClose(): void {
this.status = 'DISCONNECTED'
this.output += '\r\n\r\n[DISCONNECTED] Socket closed'
this.onData(this.output)
this.onData(this.output, this.status)
this._cleanup()
}
private async _handleTimeout(): Promise<void> {
this.status = 'TIMEOUT'
this.output += '\r\n\r\n[TIMEOUT] Connection timed out'
this.onData(this.output)
this.onData(this.output, this.status)
if (this.retryConnect <= 5) {
await this.sleep(5000)
@ -114,7 +114,7 @@ class APCController {
private _handleError(err: NodeJS.ErrnoException): void {
this.output += `\r\n\r\n[ERROR] ${err.message}`
this.onData(this.output)
this.onData(this.output, this.status)
if (err.code === 'ECONNRESET') {
setTimeout(() => {
console.log('[ECONNRESET] Trying reconnect apc:', this.apc_ip)

View File

@ -235,17 +235,14 @@ export default class LineConnection {
}, script.timeout || 300000)
const runStep = async (index: number) => {
console.log('Running step', index, Date.now())
if (index >= steps.length) {
clearTimeout(timeoutTimer)
if (this.waitingScenario) {
this.waitingScenario = false
setTimeout(() => {
this.waitingScenario = false
runStep(index)
}, 5000)
return
}
console.log('End step', Date.now())
} else clearTimeout(timeoutTimer)
this.isRunningScript = false
this.outputBuffer = ''
appendLog(
@ -397,12 +394,14 @@ export default class LineConnection {
username,
password,
number: this.config.lineNumber,
onData: (data: string) => {
onData: (data: string, status: string) => {
this.config.output += data
this.socketIO.emit('line_output', {
this.socketIO.emit('apc_output', {
stationId: this.config.stationId,
lineId: this.config.id,
data: data,
apcNumber: apcName === 'apc_1' ? 1 : 2,
data,
status,
})
appendLog(
cleanData(data),

View File

@ -7,6 +7,7 @@ import env from '#start/env'
import { CustomServer, CustomSocket } from '../app/ultils/types.js'
import Line from '#models/line'
import Station from '#models/station'
import APCController from '#services/apc_connection'
interface HandleOptions {
command?: string
@ -62,6 +63,7 @@ export class WebSocketIo {
lineMap: Map<number, LineConnection> = new Map() // key = lineId
lineConnecting: number[] = [] // key = lineId
userConnecting: Map<number, { userId: number; userName: string }> = new Map()
apcsControl: Map<string, APCController> = new Map()
constructor(protected app: ApplicationService) {}
@ -123,7 +125,7 @@ export class WebSocketIo {
stationId,
lineIds,
async (line) => line.writeCommand(command),
{ command, timeout: 180000 }
{ command, timeout: 120000 }
)
})
@ -137,7 +139,7 @@ export class WebSocketIo {
async (line) => line.runScript(scenario),
{
scenario,
timeout: scenario?.timeout ? Number(scenario.timeout) + 180000 : 300000,
timeout: scenario?.timeout ? Number(scenario.timeout) + 120000 : 300000,
}
)
})
@ -201,7 +203,6 @@ export class WebSocketIo {
// Get file stats
const stats = fs.statSync(filePath)
const fileSizeInBytes = stats.size
console.log('File size (bytes):', fileSizeInBytes)
if (fileSizeInBytes / 1024 / 1024 > 0.5) {
// File is larger than 0.5 MB
const fileId = Date.now() // Mã định danh file
@ -242,9 +243,17 @@ export class WebSocketIo {
stationId,
lineIds,
async (line) => line.apcControl(action),
{ actionApc: action, timeout: 180000 }
{ actionApc: action, timeout: 120000 }
)
})
socket.on('connect_apc', async (data) => {
const { apcIp, station, apcName } = data
if (this.apcsControl.has(apcIp)) {
return
}
await this.connectApc(io, apcName, station)
})
})
socketServer.listen(SOCKET_IO_PORT, () => {
@ -286,7 +295,7 @@ export class WebSocketIo {
}
}
private setTimeoutConnect = (lineId: number, lineConn: LineConnection, timeout = 180000) => {
private setTimeoutConnect = (lineId: number, lineConn: LineConnection, timeout = 120000) => {
if (this.intervalMap[`${lineId}`]) {
clearInterval(this.intervalMap[`${lineId}`])
delete this.intervalMap[`${lineId}`]
@ -351,4 +360,38 @@ export class WebSocketIo {
}
}
}
private async connectApc(socket: any, apcName: string, station: Station) {
try {
const ip = (station as any)[`${apcName}_ip`] as string
const port = (station as any)[`${apcName}_port`] as number
const username = (station as any)[`${apcName}_username`] as string
const password = (station as any)[`${apcName}_password`] as string
if (!ip || !port || !username || !password)
throw new Error(`Missing APC configuration for ${apcName}`)
// Tạo APC Controller instance
const apc = new APCController({
host: ip,
port,
username,
password,
onData: (data: string, status: string) => {
socket.emit('apc_output', {
stationId: station.id,
apcNumber: apcName === 'apc_1' ? 1 : 2,
data,
status,
})
},
})
// Connect và login
await apc.connect()
await apc.login()
this.apcsControl.set(ip, apc)
} catch (error) {
console.log(error)
}
}
}

View File

@ -14,8 +14,6 @@ import {
Grid,
ScrollArea,
LoadingOverlay,
Button,
Box,
} from "@mantine/core";
import type {
IDataTakeOver,
@ -338,7 +336,7 @@ function App() {
};
});
},
[activeTab]
[]
);
// const getLine = (lineId: number, stationId: number) => {

View File

@ -270,7 +270,25 @@ export default function DraggableTabs({
fz={"sm"}
variant="filled"
onClick={() => {
const station = tabs.find(
(el) => el.id.toString() === active
);
if (!station) return;
setOpenedAPC(true);
if (station?.apc_1_ip && station?.apc_1_port) {
socket?.emit("connect_apc", {
station: station,
apcIp: station?.apc_1_ip,
apcName: "apc_1",
});
}
if (station?.apc_2_ip && station?.apc_2_port) {
socket?.emit("connect_apc", {
station: station,
apcIp: station?.apc_2_ip,
apcName: "apc_2",
});
}
}}
>
APC

File diff suppressed because it is too large Load Diff

View File

@ -45,7 +45,9 @@ export type TStation = {
owner_id: number;
owner: TUser;
users: TUser[];
apcs?: APCProps[];
apcs: APCProps[];
apc1: APCProps;
apc2: APCProps;
master_control?: boolean;
switch_control_ip?: string; // Optional
switch_control_port?: number; // Optional