/** * Edge 管理多个设备的示例 * 展示一个 Edge 如何代理和管理多个不同类型的设备 */ import { EdgeProxy, EdgeProxyUtils, ManagedDevice, MessageFactory, CommandMessage, ClientType } from '../src'; /** * 地铁站 Edge 节点 * 管理一个站点的所有设备 */ export class SubwayStationEdge extends EdgeProxy { // 设备分组管理 private deviceGroups = { platform: new Set(), // 站台设备 escalator: new Set(), // 扶梯设备 ventilation: new Set(), // 通风设备 lighting: new Set(), // 照明设备 security: new Set() // 安防设备 }; constructor(stationId: string) { super(`edge-${stationId}`); } /** * 初始化站点所有设备 */ async initializeStation() { console.log(`Initializing station ${this.edgeId}`); // 添加站台设备 await this.addPlatformDevices(); // 添加扶梯设备 await this.addEscalatorDevices(); // 添加通风设备 await this.addVentilationDevices(); // 添加照明设备 await this.addLightingDevices(); // 添加安防设备 await this.addSecurityDevices(); console.log(`Station initialized with ${this.devices.size} devices`); this.reportDeviceStatistics(); } /** * 添加站台设备 */ private async addPlatformDevices() { const platformDevices = [ { id: 'psd-01', name: '1号站台屏蔽门-A', type: 'platform_door' }, { id: 'psd-02', name: '1号站台屏蔽门-B', type: 'platform_door' }, { id: 'psd-03', name: '2号站台屏蔽门-A', type: 'platform_door' }, { id: 'psd-04', name: '2号站台屏蔽门-B', type: 'platform_door' }, { id: 'dis-01', name: '1号站台显示屏', type: 'display' }, { id: 'dis-02', name: '2号站台显示屏', type: 'display' }, { id: 'pa-01', name: '站台广播系统', type: 'pa_system' } ]; for (const dev of platformDevices) { const device: ManagedDevice = { deviceId: dev.id, deviceType: dev.type, status: 'online', lastSeen: new Date().toISOString(), capabilities: this.getDeviceCapabilities(dev.type), metadata: { name: dev.name, group: 'platform', location: 'platform_area' } }; this.addDevice(device); this.deviceGroups.platform.add(dev.id); } } /** * 添加扶梯设备 */ private async addEscalatorDevices() { const escalators = [ { id: 'esc-01', name: 'A出口上行扶梯', direction: 'up', location: 'exit_a' }, { id: 'esc-02', name: 'A出口下行扶梯', direction: 'down', location: 'exit_a' }, { id: 'esc-03', name: 'B出口上行扶梯', direction: 'up', location: 'exit_b' }, { id: 'esc-04', name: 'B出口下行扶梯', direction: 'down', location: 'exit_b' } ]; for (const esc of escalators) { const device: ManagedDevice = { deviceId: esc.id, deviceType: 'escalator', status: 'online', lastSeen: new Date().toISOString(), capabilities: ['start', 'stop', 'emergency_stop', 'speed_control', 'status_read'], metadata: { name: esc.name, direction: esc.direction, location: esc.location, group: 'escalator' } }; this.addDevice(device); this.deviceGroups.escalator.add(esc.id); } } /** * 添加通风设备 */ private async addVentilationDevices() { const ventilationDevices = [ { id: 'fan-01', name: '站台通风机1', power: 50 }, { id: 'fan-02', name: '站台通风机2', power: 50 }, { id: 'fan-03', name: '隧道通风机1', power: 100 }, { id: 'fan-04', name: '隧道通风机2', power: 100 }, { id: 'ac-01', name: '站厅空调系统', type: 'ac_unit' }, { id: 'ac-02', name: '设备房空调系统', type: 'ac_unit' } ]; for (const vent of ventilationDevices) { const device: ManagedDevice = { deviceId: vent.id, deviceType: vent.type || 'ventilation_fan', status: 'online', lastSeen: new Date().toISOString(), capabilities: ['start', 'stop', 'speed_control', 'power_read', 'temperature_read'], metadata: { name: vent.name, power: vent.power, group: 'ventilation' } }; this.addDevice(device); this.deviceGroups.ventilation.add(vent.id); } } /** * 添加照明设备 */ private async addLightingDevices() { const lightingZones = [ { id: 'light-01', name: '站台照明A区', zone: 'platform_a' }, { id: 'light-02', name: '站台照明B区', zone: 'platform_b' }, { id: 'light-03', name: '站厅照明', zone: 'hall' }, { id: 'light-04', name: '通道照明', zone: 'passage' }, { id: 'light-05', name: '应急照明', zone: 'emergency', type: 'emergency_light' } ]; for (const light of lightingZones) { const device: ManagedDevice = { deviceId: light.id, deviceType: light.type || 'lighting_zone', status: 'online', lastSeen: new Date().toISOString(), capabilities: ['on', 'off', 'dimming', 'brightness_read', 'power_read'], metadata: { name: light.name, zone: light.zone, group: 'lighting' } }; this.addDevice(device); this.deviceGroups.lighting.add(light.id); } } /** * 添加安防设备 */ private async addSecurityDevices() { const securityDevices = [ { id: 'cam-01', name: '站台监控摄像头1', type: 'camera', location: 'platform_1' }, { id: 'cam-02', name: '站台监控摄像头2', type: 'camera', location: 'platform_2' }, { id: 'cam-03', name: '站厅监控摄像头', type: 'camera', location: 'hall' }, { id: 'gate-01', name: '进站闸机组', type: 'gate', count: 6 }, { id: 'gate-02', name: '出站闸机组', type: 'gate', count: 6 }, { id: 'alarm-01', name: '火灾报警系统', type: 'fire_alarm' }, { id: 'alarm-02', name: '紧急呼叫系统', type: 'emergency_call' } ]; for (const sec of securityDevices) { const device: ManagedDevice = { deviceId: sec.id, deviceType: sec.type, status: 'online', lastSeen: new Date().toISOString(), capabilities: this.getSecurityDeviceCapabilities(sec.type), metadata: { name: sec.name, location: sec.location, count: sec.count, group: 'security' } }; this.addDevice(device); this.deviceGroups.security.add(sec.id); } } /** * 获取设备能力列表 */ private getDeviceCapabilities(deviceType: string): string[] { const capabilityMap: Record = { platform_door: ['open', 'close', 'emergency_open', 'status_read', 'fault_read'], display: ['show_message', 'clear', 'brightness_control', 'status_read'], pa_system: ['broadcast', 'stop', 'volume_control', 'zone_select'], escalator: ['start', 'stop', 'emergency_stop', 'speed_control', 'status_read'], ventilation_fan: ['start', 'stop', 'speed_control', 'power_read'], ac_unit: ['start', 'stop', 'temperature_set', 'mode_set', 'status_read'], lighting_zone: ['on', 'off', 'dimming', 'brightness_read'], emergency_light: ['on', 'off', 'test', 'battery_read'] }; return capabilityMap[deviceType] || ['status_read']; } /** * 获取安防设备能力 */ private getSecurityDeviceCapabilities(deviceType: string): string[] { const capabilityMap: Record = { camera: ['stream_start', 'stream_stop', 'snapshot', 'ptz_control', 'status_read'], gate: ['open', 'close', 'emergency_open', 'passenger_count', 'status_read'], fire_alarm: ['status_read', 'test', 'reset', 'zone_status'], emergency_call: ['status_read', 'answer', 'broadcast', 'test'] }; return capabilityMap[deviceType] || ['status_read']; } /** * 报告设备统计信息 */ private reportDeviceStatistics() { console.log('\n=== 站点设备统计 ==='); console.log(`总设备数: ${this.devices.size}`); for (const [group, deviceIds] of Object.entries(this.deviceGroups)) { console.log(`${group}: ${deviceIds.size} 台设备`); } // 按类型统计 const typeCount = new Map(); for (const device of this.devices.values()) { const count = typeCount.get(device.deviceType) || 0; typeCount.set(device.deviceType, count + 1); } console.log('\n按设备类型统计:'); for (const [type, count] of typeCount) { console.log(` ${type}: ${count}`); } } /** * 执行设备组命令 */ async executeGroupCommand( group: keyof typeof this.deviceGroups, command: Partial ) { const deviceIds = Array.from(this.deviceGroups[group]); if (deviceIds.length === 0) { throw new Error(`No devices in group: ${group}`); } console.log(`Executing command on ${group} group (${deviceIds.length} devices)`); // 创建批量命令 const batchCommand = EdgeProxyUtils.createEdgeBatchCommand( `group-${group}-${Date.now()}`, this.edgeId, deviceIds, { commandCode: command.commandCode || 'STATUS_READ', deviceType: command.deviceType || 'generic', operationType: command.operationType || 'read', parameters: command.parameters || {} }, { failureStrategy: 'continue_on_failure' } ); // 执行命令 return await this.handleGatewayCommand(batchCommand); } /** * 紧急响应场景 */ async executeEmergencyResponse(scenario: 'fire' | 'evacuation' | 'power_failure') { console.log(`Executing emergency response: ${scenario}`); switch (scenario) { case 'fire': // 火灾响应 await Promise.all([ // 打开所有屏蔽门 this.executeGroupCommand('platform', { commandCode: 'EMERGENCY_OPEN', operationType: 'write' }), // 停止所有扶梯 this.executeGroupCommand('escalator', { commandCode: 'EMERGENCY_STOP', operationType: 'write' }), // 启动应急照明 this.executeDeviceCommand('light-05', { commandCode: 'ON', operationType: 'write' }), // 启动排烟模式 this.executeGroupCommand('ventilation', { commandCode: 'SMOKE_EXHAUST_MODE', operationType: 'write' }) ]); break; case 'evacuation': // 疏散响应 await Promise.all([ // 广播疏散信息 this.executeDeviceCommand('pa-01', { commandCode: 'BROADCAST', operationType: 'write', parameters: { message: 'evacuation_announcement' } }), // 显示疏散指引 this.executeGroupCommand('platform', { commandCode: 'SHOW_MESSAGE', operationType: 'write', parameters: { message: 'evacuation_guide' } }), // 打开所有闸机 this.executeDeviceCommands(['gate-01', 'gate-02'], { commandCode: 'EMERGENCY_OPEN', operationType: 'write' }) ]); break; case 'power_failure': // 停电响应 await Promise.all([ // 切换到应急电源模式 this.switchToEmergencyPower(), // 关闭非必要设备 this.shutdownNonEssentialDevices() ]); break; } } /** * 批量执行设备命令 */ private async executeDeviceCommands( deviceIds: string[], command: Partial ) { const promises = deviceIds.map(deviceId => this.executeDeviceCommand(deviceId, command) ); return await Promise.all(promises); } /** * 切换到应急电源 */ private async switchToEmergencyPower() { // 实现应急电源切换逻辑 console.log('Switching to emergency power mode'); } /** * 关闭非必要设备 */ private async shutdownNonEssentialDevices() { // 保持应急照明和通风 const essentialDevices = new Set(['light-05', 'fan-01', 'fan-02']); for (const [deviceId, device] of this.devices) { if (!essentialDevices.has(deviceId) && (device.deviceType === 'lighting_zone' || device.deviceType === 'ac_unit')) { await this.executeDeviceCommand(deviceId, { commandCode: 'OFF', operationType: 'write' }); } } } /** * 生成设备状态报告 */ generateDeviceReport(): any { const report = { stationId: this.edgeId, timestamp: new Date().toISOString(), summary: { totalDevices: this.devices.size, onlineDevices: 0, offlineDevices: 0, errorDevices: 0 }, groups: {} as Record, alerts: [] as any[] }; // 统计设备状态 for (const device of this.devices.values()) { switch (device.status) { case 'online': report.summary.onlineDevices++; break; case 'offline': report.summary.offlineDevices++; break; case 'error': report.summary.errorDevices++; report.alerts.push({ deviceId: device.deviceId, deviceType: device.deviceType, message: `Device ${device.deviceId} is in error state` }); break; } } // 按组统计 for (const [group, deviceIds] of Object.entries(this.deviceGroups)) { const groupDevices = Array.from(deviceIds).map(id => this.devices.get(id)); report.groups[group] = { total: deviceIds.size, online: groupDevices.filter(d => d?.status === 'online').length, offline: groupDevices.filter(d => d?.status === 'offline').length, error: groupDevices.filter(d => d?.status === 'error').length }; } return report; } } // 使用示例 async function demonstrateMultiDeviceEdge() { // 创建地铁站 Edge const stationEdge = new SubwayStationEdge('station-001'); // 初始化所有设备 await stationEdge.initializeStation(); // 注册到 Gateway await stationEdge.connectToGateway('ws://gateway:3001'); stationEdge.registerToGateway(); // 执行日常操作 console.log('\n执行早高峰模式...'); await Promise.all([ // 增加通风 stationEdge.executeGroupCommand('ventilation', { commandCode: 'SET_SPEED', operationType: 'write', parameters: { speed: 80 } }), // 增加照明亮度 stationEdge.executeGroupCommand('lighting', { commandCode: 'SET_BRIGHTNESS', operationType: 'write', parameters: { brightness: 100 } }), // 加快扶梯速度 stationEdge.executeGroupCommand('escalator', { commandCode: 'SET_SPEED', operationType: 'write', parameters: { speed: 'fast' } }) ]); // 模拟紧急情况 console.log('\n模拟火灾紧急响应...'); await stationEdge.executeEmergencyResponse('fire'); // 生成报告 const report = stationEdge.generateDeviceReport(); console.log('\n设备状态报告:', JSON.stringify(report, null, 2)); } export { SubwayStationEdge, demonstrateMultiDeviceEdge };