1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
| import asyncio import socket import struct import logging from datetime import datetime from collections import deque from .config_loader import ConfigLoader from .db_handler import AsyncDBServer from .cache_manager import DataCache from .event_manager import EventManager
class AsyncDTUServer: def __init__(self, config_loader, event_manager): self.config_loader = config_loader self.event_manager = event_manager self.server_config = config_loader.get_server_config() self.query_tasks = config_loader.get_query_tasks() self.data_points = config_loader.get_data_points() self.host = self.server_config.get('host', '0.0.0.0') self.port = self.server_config.get('main_port', 22334) self.heartbeat_timeout = self.server_config.get('heartbeat_timeout', 60) self.max_missed = self.server_config.get('max_missed', 3) self.max_connections = self.server_config.get('max_connections', 1000) self.connection_pool_size = self.server_config.get('connection_pool_size', 100) self.server = None self.connections = {} self.connection_pool = deque(maxlen=self.connection_pool_size) self.running = False mysql_config = config_loader.get_mysql_config() self.db = AsyncDBServer(mysql_config) if mysql_config else None cache_config = config_loader.get_cache_config() self.cache = DataCache( max_size=cache_config.get('max_size', 10000), flush_interval=cache_config.get('flush_interval', 10), db_handler=self.db, event_manager=event_manager ) self._init_connection_pool() def _init_connection_pool(self): """初始化连接池""" for _ in range(self.connection_pool_size): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.connection_pool.append(sock) async def start(self): """启动服务器""" self.running = True self.server = await asyncio.start_server( self._handle_client, self.host, self.port, reuse_port=True, backlog=self.max_connections ) addr = self.server.sockets[0].getsockname() logging.info(f"异步DTU服务器启动,监听 {addr[0]}:{addr[1]}") logging.info(f"最大连接数: {self.max_connections}, 连接池大小: {self.connection_pool_size}") asyncio.create_task(self._monitor_heartbeats()) asyncio.create_task(self._execute_query_tasks()) asyncio.create_task(self.cache.start()) async with self.server: await self.server.serve_forever() async def stop(self): """停止服务器""" self.running = False for device_id, conn in list(self.connections.items()): await self._close_connection(device_id) await self.cache.stop() if self.server: self.server.close() await self.server.wait_closed() logging.info("DTU服务器已停止") async def _handle_client(self, reader, writer): """处理客户端连接""" addr = writer.get_extra_info('peername') device_id = None try: reg_data = await reader.read(4) if len(reg_data) < 4: logging.warning(f"无效注册包: {addr[0]}:{addr[1]}") writer.close() await writer.wait_closed() return device_id = struct.unpack('>I', reg_data)[0] logging.info(f"设备注册: ID={device_id} ({addr[0]}:{addr[1]})") await self.cache.add_raw_packet(device_id, 'register', reg_data) self.connections[device_id] = { 'reader': reader, 'writer': writer, 'last_heartbeat': asyncio.get_running_loop().time(), 'missed': 0, 'address': addr, 'task_status': self._init_task_status() } writer.write(b'\x01') await writer.drain() await self.event_manager.trigger_event('device_online', { 'device_id': device_id, 'ip': addr[0], 'port': addr[1] }) while self.running: try: header = await reader.read(2) if len(header) < 2: break pkt_type, pkt_len = struct.unpack('>BB', header) data = b'' while len(data) < pkt_len: chunk = await reader.read(pkt_len - len(data)) if not chunk: break data += chunk if len(data) != pkt_len: break if pkt_type == 0x02: await self._process_heartbeat(device_id) elif pkt_type == 0x03: await self._process_data(device_id, data) elif pkt_type == 0x04: await self._process_modbus_response(device_id, data) else: logging.warning(f"未知包类型: 0x{pkt_type:02X} 来自设备 {device_id}") except (ConnectionResetError, asyncio.IncompleteReadError): logging.warning(f"连接重置: 设备 {device_id}") break except Exception as e: logging.error(f"处理设备 {device_id} 时出错: {str(e)}") break except Exception as e: logging.error(f"处理连接时出错: {str(e)}") finally: if device_id: await self.event_manager.trigger_event('device_offline', { 'device_id': device_id, 'ip': addr[0], 'port': addr[1] }) await self._close_connection(device_id) logging.info(f"连接关闭: 设备 {device_id if device_id else '未知'}") def _init_task_status(self): """初始化任务状态""" task_status = {} for task_id in self.query_tasks: task_status[task_id] = { 'last_query': 0, 'last_response': 0, 'response_count': 0, 'error_count': 0 } return task_status async def _process_heartbeat(self, device_id): """处理心跳包""" if device_id not in self.connections: return conn = self.connections[device_id] conn['last_heartbeat'] = asyncio.get_running_loop().time() conn['missed'] = 0 logging.debug(f"收到心跳: 设备 {device_id}") await self.cache.add_raw_packet(device_id, 'heartbeat', b'') try: conn['writer'].write(b'\x02') await conn['writer'].drain() except: await self._close_connection(device_id) return await self._trigger_heartbeat_queries(device_id) async def _trigger_heartbeat_queries(self, device_id): """触发心跳相关的查询任务""" if device_id not in self.connections: return for task_id, task_info in self.query_tasks.items(): trigger_type = task_info.get('trigger', 'timer') if trigger_type == "heartbeat": await self._send_modbus_query(device_id, task_id) async def _process_data(self, device_id, data): """处理普通数据包""" logging.info(f"来自设备 {device_id} 的数据: {data.hex()}") await self.cache.add_raw_packet(device_id, 'data', data) try: conn = self.connections[device_id] conn['writer'].write(b'\x03') await conn['writer'].drain() except: await self._close_connection(device_id) async def _process_modbus_response(self, device_id, data): """处理Modbus响应""" if device_id not in self.connections: return try: await self.cache.add_raw_packet(device_id, 'modbus', data) if len(data) < 5: logging.warning(f"设备 {device_id} 的Modbus响应过短: {data.hex()}") return slave_id = data[0] function_code = data[1] if function_code & 0x80: error_code = data[2] logging.error(f"设备 {device_id} Modbus错误响应: 功能码 0x{function_code:02X}, 错误码 {error_code}") return if function_code == 0x03: byte_count = data[2] reg_data = data[3:3+byte_count] conn = self.connections[device_id] for task_id, task_info in self.query_tasks.items(): start_addr = task_info['start_addr'] length = task_info['length'] for addr, dp_info in self.data_points.items(): if start_addr <= addr < start_addr + length: await self._parse_data_point(device_id, addr, reg_data, addr - start_addr) logging.info(f"设备 {device_id} Modbus数据: {reg_data.hex()}") elif function_code == 0x10: start_addr = struct.unpack('>H', data[2:4])[0] reg_count = struct.unpack('>H', data[4:6])[0] logging.info(f"设备 {device_id} 写入成功: 地址 {start_addr}, 数量 {reg_count}") else: logging.warning(f"设备 {device_id} 未知Modbus功能码: 0x{function_code:02X}") except Exception as e: logging.error(f"解析设备 {device_id} Modbus响应出错: {str(e)}") async def _parse_data_point(self, device_id, address, reg_data, offset): """解析数据点并保存到缓存""" if address not in self.data_points: return dp_config = self.data_points[address] name = dp_config['name'] dtype = dp_config['type'] length = dp_config['length'] scale = dp_config.get('scale') try: start_index = offset * 2 end_index = start_index + length if end_index > len(reg_data): logging.warning(f"设备 {device_id} 数据点 {name} 数据不足") return data_bytes = reg_data[start_index:end_index] raw_value = int.from_bytes(data_bytes, 'big') if dtype == "int": if length == 2: value = struct.unpack('>h', data_bytes)[0] elif length == 4: value = struct.unpack('>i', data_bytes)[0] else: logging.warning(f"设备 {device_id} 不支持的长度 {length} 的整数") return if scale is not None: value = value * scale elif dtype == "float": if length == 4: value = struct.unpack('>f', data_bytes)[0] else: logging.warning(f"设备 {device_id} 不支持的长度 {length} 的浮点数") return else: logging.warning(f"设备 {device_id} 未知数据类型: {dtype}") return timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") log_msg = f"{timestamp} 设备 {device_id} {name}: {value}" if scale is not None and dtype == "int": log_msg += f" (原始值: {value/scale})" logging.info(log_msg) await self.cache.add_data_point(device_id, name, value, raw_value) await self.event_manager.trigger_event('data_received', { 'device_id': device_id, 'data_point': name, 'value': value, 'raw_value': raw_value }) except Exception as e: logging.error(f"解析设备 {device_id} 数据点 {name} 出错: {str(e)}") async def _execute_query_tasks(self): """执行定时查询任务""" while self.running: try: current_time = asyncio.get_running_loop().time() for device_id, conn in list(self.connections.items()): for task_id, task_info in self.query_tasks.items(): trigger_type = task_info.get('trigger', 'timer') if trigger_type != "timer": continue interval = task_info.get('interval', 0) if interval <= 0: continue task_status = conn['task_status'][task_id] last_query = task_status['last_query'] if current_time - last_query >= interval: await self._send_modbus_query(device_id, task_id) task_status['last_query'] = current_time await asyncio.sleep(1) except Exception as e: logging.error(f"执行查询任务出错: {str(e)}") await asyncio.sleep(5) async def _send_modbus_query(self, device_id, task_id): """发送Modbus查询""" if device_id not in self.connections: return task_info = self.query_tasks.get(task_id) if not task_info: return start_addr = task_info['start_addr'] length = task_info['length'] try: conn = self.connections[device_id] writer = conn['writer'] slave_id = 0x01 func_code = 0x03 pdu = struct.pack('>BHH', func_code, start_addr, length) frame = struct.pack('B', slave_id) + pdu crc = self._calculate_crc(frame) modbus_frame = frame + crc pkt_type = 0x04 pkt_len = len(modbus_frame) header = struct.pack('>BB', pkt_type, pkt_len) packet = header + modbus_frame writer.write(packet) await writer.drain() logging.info(f"向设备 {device_id} 发送Modbus查询: 任务 {task_id}, 地址 {start_addr}, 长度 {length}") conn['task_status'][task_id]['last_query'] = asyncio.get_running_loop().time() except Exception as e: logging.error(f"向设备 {device_id} 发送Modbus查询失败: {str(e)}") await self._close_connection(device_id) def _calculate_crc(self, data): """计算Modbus CRC16校验""" crc = 0xFFFF for byte in data: crc ^= byte for _ in range(8): if crc & 0x0001: crc >>= 1 crc ^= 0xA001 else: crc >>= 1 return struct.pack('<H', crc) async def _monitor_heartbeats(self): """监控心跳状态""" while self.running: await asyncio.sleep(self.heartbeat_timeout / 2) current_time = asyncio.get_running_loop().time() devices_to_remove = [] for device_id, conn in list(self.connections.items()): elapsed = current_time - conn['last_heartbeat'] if elapsed > self.heartbeat_timeout: conn['missed'] += 1 logging.warning(f"设备 {device_id} 丢失心跳 #{conn['missed']}") if conn['missed'] >= self.max_missed: logging.error(f"设备 {device_id} 心跳超时,断开连接") devices_to_remove.append(device_id) else: conn['missed'] = 0 for device_id in devices_to_remove: await self._close_connection(device_id) async def _close_connection(self, device_id): """关闭连接""" if device_id in self.connections: conn = self.connections.pop(device_id) try: conn['writer'].close() await conn['writer'].wait_closed() except: pass logging.info(f"设备 {device_id} 从连接列表移除")
|