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
| import asyncio import json from datetime import datetime, timedelta from typing import Dict, List, Optional from dataclasses import dataclass, asdict from enum import Enum import aioredis import asyncpg
class DeviceStatus(Enum): ONLINE = "online" OFFLINE = "offline" MAINTENANCE = "maintenance" ERROR = "error"
class TaskType(Enum): HEALTH_CHECK = "health_check" CONFIG_UPDATE = "config_update" FIRMWARE_UPDATE = "firmware_update" DATA_COLLECTION = "data_collection"
@dataclass class Device: id: str name: str type: str location: str status: DeviceStatus last_seen: datetime firmware_version: str config_version: str metadata: Dict[str, str]
@dataclass class MaintenanceTask: id: str device_ids: List[str] task_type: TaskType parameters: Dict[str, any] scheduled_time: datetime status: str created_by: str result: Optional[Dict[str, any]] = None
class LargeScaleIoTOperationsPlatform: def __init__(self, redis_url: str, postgres_url: str): self.redis = None self.postgres_pool = None self.redis_url = redis_url self.postgres_url = postgres_url self.devices = {} self.device_groups = {} self.maintenance_tasks = {} self.task_queue = asyncio.Queue(maxsize=10000) self.operation_stats = { 'total_devices': 0, 'online_devices': 0, 'error_devices': 0, 'maintenance_devices': 0, 'tasks_completed_today': 0, 'tasks_failed_today': 0 } self.alert_thresholds = { 'offline_device_percentage': 5.0, 'error_rate_threshold': 1.0, 'response_time_threshold': 5.0 } async def initialize(self): """初始化平台连接""" self.redis = await aioredis.from_url(self.redis_url) self.postgres_pool = await asyncpg.create_pool(self.postgres_url) asyncio.create_task(self.device_health_monitor()) asyncio.create_task(self.task_executor()) asyncio.create_task(self.statistics_collector()) asyncio.create_task(self.alert_processor()) print("大规模IoT运维平台已启动") async def register_devices_batch(self, devices: List[Device]) -> Dict[str, str]: """批量注册设备""" results = {} async with self.postgres_pool.acquire() as conn: for device in devices: try: await conn.execute(""" INSERT INTO devices (id, name, type, location, status, last_seen, firmware_version, config_version, metadata) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT (id) DO UPDATE SET name = $2, type = $3, location = $4, status = $5, last_seen = $6, firmware_version = $7, config_version = $8, metadata = $9 """, device.id, device.name, device.type, device.location, device.status.value, device.last_seen, device.firmware_version, device.config_version, json.dumps(device.metadata)) await self.redis.hset( f"device:{device.id}", mapping={ "name": device.name, "type": device.type, "location": device.location, "status": device.status.value, "last_seen": device.last_seen.isoformat(), "firmware_version": device.firmware_version, "config_version": device.config_version, "metadata": json.dumps(device.metadata) } ) self.devices[device.id] = device results[device.id] = "success" except Exception as e: results[device.id] = f"error: {str(e)}" await self.update_statistics() return results async def create_device_group(self, group_name: str, device_filter: Dict[str, str]) -> str: """创建设备组(按位置、类型等分组)""" group_id = f"group_{group_name}_{int(datetime.now().timestamp())}" matching_devices = [] for device in self.devices.values(): if self.device_matches_filter(device, device_filter): matching_devices.append(device.id) self.device_groups[group_id] = { 'name': group_name, 'filter': device_filter, 'devices': matching_devices, 'created_at': datetime.now() } async with self.postgres_pool.acquire() as conn: await conn.execute(""" INSERT INTO device_groups (id, name, filter_criteria, devices, created_at) VALUES ($1, $2, $3, $4, $5) """, group_id, group_name, json.dumps(device_filter), json.dumps(matching_devices), datetime.now()) return group_id def device_matches_filter(self, device: Device, filter_criteria: Dict[str, str]) -> bool: """检查设备是否匹配过滤条件""" for key, value in filter_criteria.items(): if key == 'type' and device.type != value: return False elif key == 'location' and value not in device.location: return False elif key == 'status' and device.status.value != value: return False elif key in device.metadata and device.metadata[key] != value: return False return True async def schedule_batch_maintenance(self, group_id: str, task_type: TaskType, parameters: Dict[str, any], scheduled_time: datetime) -> str: """批量调度维护任务""" if group_id not in self.device_groups: raise ValueError(f"Device group {group_id} not found") device_ids = self.device_groups[group_id]['devices'] task_id = f"task_{task_type.value}_{int(datetime.now().timestamp())}" task = MaintenanceTask( id=task_id, device_ids=device_ids, task_type=task_type, parameters=parameters, scheduled_time=scheduled_time, status='scheduled', created_by='system' ) self.maintenance_tasks[task_id] = task await self.task_queue.put(task) async with self.postgres_pool.acquire() as conn: await conn.execute(""" INSERT INTO maintenance_tasks (id, device_ids, task_type, parameters, scheduled_time, status, created_by) VALUES ($1, $2, $3, $4, $5, $6, $7) """, task_id, json.dumps(device_ids), task_type.value, json.dumps(parameters), scheduled_time, 'scheduled', 'system') print(f"已创建批量维护任务 {task_id},涉及 {len(device_ids)} 个设备") return task_id async def task_executor(self): """任务执行引擎""" while True: try: task = await asyncio.wait_for(self.task_queue.get(), timeout=5.0) if datetime.now() < task.scheduled_time: await self.task_queue.put(task) await asyncio.sleep(60) continue task.status = 'running' start_time = datetime.now() try: result = await self.execute_maintenance_task(task) task.status = 'completed' task.result = result self.operation_stats['tasks_completed_today'] += 1 except Exception as e: task.status = 'failed' task.result = {'error': str(e)} self.operation_stats['tasks_failed_today'] += 1 await self.update_task_status(task) execution_time = (datetime.now() - start_time).total_seconds() print(f"任务 {task.id} 执行完成,耗时 {execution_time:.2f} 秒") except asyncio.TimeoutError: continue except Exception as e: print(f"任务执行器错误: {e}") async def execute_maintenance_task(self, task: MaintenanceTask) -> Dict[str, any]: """执行具体的维护任务""" results = {} if task.task_type == TaskType.HEALTH_CHECK: results = await self.perform_health_check(task.device_ids) elif task.task_type == TaskType.CONFIG_UPDATE: results = await self.update_device_configs(task.device_ids, task.parameters) elif task.task_type == TaskType.FIRMWARE_UPDATE: results = await self.update_device_firmware(task.device_ids, task.parameters) elif task.task_type == TaskType.DATA_COLLECTION: results = await self.collect_device_data(task.device_ids, task.parameters) return results async def perform_health_check(self, device_ids: List[str]) -> Dict[str, any]: """执行设备健康检查""" results = {'successful': [], 'failed': [], 'summary': {}} tasks = [self.check_single_device_health(device_id) for device_id in device_ids] health_results = await asyncio.gather(*tasks, return_exceptions=True) for i, result in enumerate(health_results): device_id = device_ids[i] if isinstance(result, Exception): results['failed'].append({'device_id': device_id, 'error': str(result)}) else: if result.get('healthy', False): results['successful'].append(device_id) else: results['failed'].append({'device_id': device_id, 'issues': result.get('issues', [])}) results['summary'] = { 'total_devices': len(device_ids), 'healthy_devices': len(results['successful']), 'unhealthy_devices': len(results['failed']), 'success_rate': len(results['successful']) / len(device_ids) * 100 } return results async def check_single_device_health(self, device_id: str) -> Dict[str, any]: """检查单个设备健康状态""" await asyncio.sleep(0.1) device = self.devices.get(device_id) if not device: raise Exception(f"Device {device_id} not found") issues = [] if device.status == DeviceStatus.OFFLINE: issues.append("Device is offline") if (datetime.now() - device.last_seen).total_seconds() > 300: issues.append("No communication for over 5 minutes") if device.firmware_version < "1.0.0": issues.append("Firmware version is outdated") return { 'device_id': device_id, 'healthy': len(issues) == 0, 'issues': issues, 'timestamp': datetime.now().isoformat() } async def device_health_monitor(self): """设备健康监控后台任务""" while True: try: current_time = datetime.now() offline_devices = [] error_devices = [] for device in self.devices.values(): if (current_time - device.last_seen).total_seconds() > 600: if device.status != DeviceStatus.OFFLINE: device.status = DeviceStatus.OFFLINE offline_devices.append(device.id) if device.status == DeviceStatus.ERROR: error_devices.append(device.id) if offline_devices: await self.trigger_alert('device_offline', { 'count': len(offline_devices), 'devices': offline_devices[:10] }) if error_devices: await self.trigger_alert('device_error', { 'count': len(error_devices), 'devices': error_devices[:10] }) await asyncio.sleep(60) except Exception as e: print(f"设备健康监控错误: {e}") await asyncio.sleep(60) async def trigger_alert(self, alert_type: str, data: Dict[str, any]): """触发告警""" alert = { 'type': alert_type, 'data': data, 'timestamp': datetime.now().isoformat(), 'severity': self.get_alert_severity(alert_type, data) } await self.redis.lpush('alerts', json.dumps(alert)) print(f"告警触发: {alert_type}, 严重程度: {alert['severity']}") def get_alert_severity(self, alert_type: str, data: Dict[str, any]) -> str: """获取告警严重程度""" if alert_type == 'device_offline': if data['count'] > 100: return 'critical' elif data['count'] > 10: return 'major' else: return 'minor' elif alert_type == 'device_error': if data['count'] > 50: return 'critical' elif data['count'] > 5: return 'major' else: return 'minor' return 'info'
async def main(): platform = LargeScaleIoTOperationsPlatform( redis_url="redis://localhost:6379", postgres_url="postgresql://user:password@localhost/iot_ops" ) await platform.initialize() devices = [ Device( id=f"device_{i:06d}", name=f"Sensor {i}", type="temperature_sensor", location=f"Building A, Floor {i//100 + 1}", status=DeviceStatus.ONLINE, last_seen=datetime.now(), firmware_version="1.2.0", config_version="1.0", metadata={"zone": f"zone_{i%10}"} ) for i in range(10000) ] print("开始批量注册设备...") results = await platform.register_devices_batch(devices) print(f"设备注册完成,成功: {sum(1 for r in results.values() if r == 'success')}") group_id = await platform.create_device_group( "building_a_sensors", {"type": "temperature_sensor", "location": "Building A"} ) task_id = await platform.schedule_batch_maintenance( group_id, TaskType.HEALTH_CHECK, {"check_connectivity": True, "check_firmware": True}, datetime.now() + timedelta(minutes=1) ) print(f"已调度批量健康检查任务: {task_id}") await asyncio.sleep(3600)
if __name__ == "__main__": asyncio.run(main())
|