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
| import mysql.connector from mysql.connector import Error from mysql.connector.pooling import MySQLConnectionPool import logging
class DBServer: """MySQL数据库管理类""" def __init__(self, config): self.config = config self.connection_pool = None self._initialize_pool() self._create_tables()
def _initialize_pool(self): """初始化数据库连接池""" try: pool_config = { 'host': self.config.get('host'), 'port': self.config.get('port', 3306), 'user': self.config.get('user'), 'password': self.config.get('password'), 'database': self.config.get('database'), 'pool_name': 'dtu_pool', 'pool_size': self.config.get('pool_size', 5), 'autocommit': True } self.connection_pool = MySQLConnectionPool(**pool_config) logging.info("MySQL连接池初始化成功") except Error as e: logging.error(f"创建MySQL连接池失败: {str(e)}") self.connection_pool = None
def _create_tables(self): """创建必要的数据库表""" if not self.connection_pool: return try: conn = self.connection_pool.get_connection() cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS devices ( id INT AUTO_INCREMENT PRIMARY KEY, device_id INT NOT NULL, ip_address VARCHAR(20) NOT NULL, port INT NOT NULL, first_seen DATETIME NOT NULL, last_seen DATETIME NOT NULL, status ENUM('online', 'offline') DEFAULT 'online', UNIQUE KEY unique_device (device_id) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS device_data ( id BIGINT AUTO_INCREMENT PRIMARY KEY, device_id INT NOT NULL, data_point VARCHAR(50) NOT NULL, value FLOAT NOT NULL, raw_value BIGINT, timestamp DATETIME NOT NULL, INDEX idx_device (device_id), INDEX idx_timestamp (timestamp) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS connection_history ( id BIGINT AUTO_INCREMENT PRIMARY KEY, device_id INT NOT NULL, event ENUM('connect', 'disconnect', 'heartbeat_timeout') NOT NULL, timestamp DATETIME NOT NULL, details VARCHAR(255) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS heartbeat_log ( id BIGINT AUTO_INCREMENT PRIMARY KEY, device_id INT NOT NULL, timestamp DATETIME NOT NULL, INDEX idx_device (device_id), INDEX idx_timestamp (timestamp) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS raw_packets ( id BIGINT AUTO_INCREMENT PRIMARY KEY, device_id INT NOT NULL, packet_type ENUM('register', 'heartbeat', 'data', 'modbus') NOT NULL, raw_data BLOB, timestamp DATETIME NOT NULL, INDEX idx_device (device_id), INDEX idx_timestamp (timestamp) ) """) conn.commit() logging.info("数据库表创建/验证成功") except Error as e: logging.error(f"创建数据库表失败: {str(e)}") finally: if conn.is_connected(): cursor.close() conn.close()
def log_device_connection(self, device_id, ip, port, event, details=None): """记录设备连接事件""" if not self.connection_pool: return try: conn = self.connection_pool.get_connection() cursor = conn.cursor() cursor.execute(""" INSERT INTO connection_history (device_id, event, timestamp, details) VALUES (%s, %s, %s, %s) """, (device_id, event, datetime.now(), details)) if event == 'connect': cursor.execute(""" INSERT INTO devices (device_id, ip_address, port, first_seen, last_seen, status) VALUES (%s, %s, %s, %s, %s, 'online') ON DUPLICATE KEY UPDATE ip_address = VALUES(ip_address), port = VALUES(port), last_seen = VALUES(last_seen), status = 'online' """, (device_id, ip, port, datetime.now(), datetime.now())) elif event in ('disconnect', 'heartbeat_timeout'): cursor.execute(""" UPDATE devices SET status = 'offline' WHERE device_id = %s """, (device_id,)) conn.commit() except Error as e: logging.error(f"记录设备连接事件失败: {str(e)}") finally: if conn.is_connected(): cursor.close() conn.close()
def log_heartbeat(self, device_id): """记录设备心跳""" if not self.connection_pool: return try: conn = self.connection_pool.get_connection() cursor = conn.cursor() cursor.execute(""" INSERT INTO heartbeat_log (device_id, timestamp) VALUES (%s, %s) """, (device_id, datetime.now())) cursor.execute(""" UPDATE devices SET last_seen = %s WHERE device_id = %s """, (datetime.now(), device_id)) conn.commit() except Error as e: logging.error(f"记录心跳失败: {str(e)}") finally: if conn.is_connected(): cursor.close() conn.close()
def save_data_point(self, device_id, data_point, value, raw_value): """保存数据点到数据库""" if not self.connection_pool: return False try: conn = self.connection_pool.get_connection() cursor = conn.cursor() cursor.execute(""" INSERT INTO device_data (device_id, data_point, value, raw_value, timestamp) VALUES (%s, %s, %s, %s, %s) """, (device_id, data_point, value, raw_value, datetime.now())) conn.commit() return True except Error as e: logging.error(f"保存数据点失败: {str(e)}") return False finally: if conn.is_connected(): cursor.close() conn.close() def save_raw_packet(self, device_id, packet_type, raw_data): """保存原始数据包到数据库""" if not self.connection_pool: return False try: conn = self.connection_pool.get_connection() cursor = conn.cursor() cursor.execute(""" INSERT INTO raw_packets (device_id, packet_type, raw_data, timestamp) VALUES (%s, %s, %s, %s) """, (device_id, packet_type, raw_data, datetime.now())) conn.commit() return True except Error as e: logging.error(f"保存原始数据包失败: {str(e)}") return False finally: if conn.is_connected(): cursor.close() conn.close() def get_connected_devices(self): """获取在线设备列表""" if not self.connection_pool: return [] try: conn = self.connection_pool.get_connection() cursor = conn.cursor(dictionary=True) cursor.execute(""" SELECT * FROM devices WHERE status = 'online' ORDER BY last_seen DESC """) return cursor.fetchall() except Error as e: logging.error(f"获取在线设备失败: {str(e)}") return [] finally: if conn.is_connected(): cursor.close() conn.close() def get_device_data(self, device_id, limit=100): """获取设备数据""" if not self.connection_pool: return [] try: conn = self.connection_pool.get_connection() cursor = conn.cursor(dictionary=True) cursor.execute(""" SELECT * FROM device_data WHERE device_id = %s ORDER BY timestamp DESC LIMIT %s """, (device_id, limit)) return cursor.fetchall() except Error as e: logging.error(f"获取设备数据失败: {str(e)}") return [] finally: if conn.is_connected(): cursor.close() conn.close() def get_connection_history(self, limit=100): """获取连接历史""" if not self.connection_pool: return [] try: conn = self.connection_pool.get_connection() cursor = conn.cursor(dictionary=True) cursor.execute(""" SELECT * FROM connection_history ORDER BY timestamp DESC LIMIT %s """, (limit,)) return cursor.fetchall() except Error as e: logging.error(f"获取连接历史失败: {str(e)}") return [] finally: if conn.is_connected(): cursor.close() conn.close() def get_raw_packets(self, device_id=None, limit=100): """获取原始数据包""" if not self.connection_pool: return [] try: conn = self.connection_pool.get_connection() cursor = conn.cursor(dictionary=True) if device_id: cursor.execute(""" SELECT * FROM raw_packets WHERE device_id = %s ORDER BY timestamp DESC LIMIT %s """, (device_id, limit)) else: cursor.execute(""" SELECT * FROM raw_packets ORDER BY timestamp DESC LIMIT %s """, (limit,)) return cursor.fetchall() except Error as e: logging.error(f"获取原始数据包失败: {str(e)}") return [] finally: if conn.is_connected(): cursor.close() conn.close()
|