wenxiangchao
3 天以前 b544d5cccd76735e034c8055918a50927b437474
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
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using HMI.Core.Util;
using log4net;
using Plugin.DeviceDebug.Entity;
 
namespace Plugin.DeviceDebug.Model
{
    /// <summary>
    /// 数据访问层 - 管理调试会话和操作审计的持久化
    /// </summary>
    public class DeviceDebugModel
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(DeviceDebugModel));
        private SqliteHelper? _sqliteHelper;
        private string _dbPath = string.Empty;
 
        /// <summary>
        /// 初始化数据库,创建必要的表结构
        /// </summary>
        public void InitDatabase(string dbPath)
        {
            try
            {
                _dbPath = dbPath;
 
                // 确保目录存在
                string? dir = Path.GetDirectoryName(dbPath);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
 
                // 如果数据库文件不存在,创建它
                if (!File.Exists(dbPath))
                {
                    SqliteHelper.CreateDatabase(dbPath);
                    log.Info($"创建调试数据库: {dbPath}");
                }
 
                _sqliteHelper = new SqliteHelper(dbPath);
 
                // 创建 debug_session 表
                string createSessionTable = @"
                    CREATE TABLE IF NOT EXISTS debug_session (
                        session_id TEXT PRIMARY KEY,
                        device_id TEXT NOT NULL,
                        operator_id TEXT NOT NULL,
                        operator_name TEXT,
                        effective_version TEXT,
                        state INTEGER NOT NULL DEFAULT 0,
                        reservation_ref TEXT,
                        created_at TEXT NOT NULL,
                        closed_at TEXT
                    )";
 
                // 创建 debug_operation 表
                string createOperationTable = @"
                    CREATE TABLE IF NOT EXISTS debug_operation (
                        operation_id TEXT PRIMARY KEY,
                        session_id TEXT NOT NULL,
                        command_type TEXT NOT NULL,
                        parameters TEXT,
                        outcome TEXT NOT NULL,
                        device_readback TEXT,
                        error_code TEXT,
                        error_message TEXT,
                        timestamp TEXT NOT NULL,
                        FOREIGN KEY (session_id) REFERENCES debug_session(session_id)
                    )";
 
                _sqliteHelper.ExecuteSql(createSessionTable);
                _sqliteHelper.ExecuteSql(createOperationTable);
 
                log.Info("调试数据库表初始化完成");
            }
            catch (Exception ex)
            {
                log.Error($"初始化调试数据库失败: {ex.Message}", ex);
                throw;
            }
        }
 
        #region 会话 CRUD
 
        /// <summary>
        /// 创建会话
        /// </summary>
        public void CreateSession(DebugSession session)
        {
            try
            {
                if (_sqliteHelper == null)
                    throw new InvalidOperationException("数据库未初始化,请先调用 InitDatabase");
 
                string sql = $@"
                    INSERT INTO debug_session (
                        session_id, device_id, operator_id, operator_name, 
                        effective_version, state, reservation_ref, created_at, closed_at
                    ) VALUES (
                        '{EscapeSql(session.SessionId)}',
                        '{EscapeSql(session.DeviceId)}',
                        '{EscapeSql(session.OperatorId)}',
                        '{EscapeSql(session.OperatorName)}',
                        '{EscapeSql(session.EffectiveVersion)}',
                        {(int)session.State},
                        '{EscapeSql(session.ReservationRef)}',
                        '{session.CreatedAt:yyyy-MM-dd HH:mm:ss}',
                        {(session.ClosedAt.HasValue ? $"'{session.ClosedAt.Value:yyyy-MM-dd HH:mm:ss}'" : "NULL")}
                    )";
 
                _sqliteHelper.ExecuteSql(sql);
                log.Debug($"创建会话: {session.SessionId}, 设备: {session.DeviceId}");
            }
            catch (Exception ex)
            {
                log.Error($"创建会话失败: {ex.Message}", ex);
                throw;
            }
        }
 
        /// <summary>
        /// 获取会话
        /// </summary>
        public DebugSession? GetSession(string sessionId)
        {
            try
            {
                if (_sqliteHelper == null)
                    throw new InvalidOperationException("数据库未初始化,请先调用 InitDatabase");
 
                string sql = $"SELECT * FROM debug_session WHERE session_id = '{EscapeSql(sessionId)}'";
                DataTable dt = _sqliteHelper.GetDataTable(sql);
 
                if (dt.Rows.Count == 0)
                    return null;
 
                return MapToDebugSession(dt.Rows[0]);
            }
            catch (Exception ex)
            {
                log.Error($"获取会话失败: {ex.Message}", ex);
                return null;
            }
        }
 
        /// <summary>
        /// 更新会话
        /// </summary>
        public void UpdateSession(DebugSession session)
        {
            try
            {
                if (_sqliteHelper == null)
                    throw new InvalidOperationException("数据库未初始化,请先调用 InitDatabase");
 
                string sql = $@"
                    UPDATE debug_session SET
                        device_id = '{EscapeSql(session.DeviceId)}',
                        operator_id = '{EscapeSql(session.OperatorId)}',
                        operator_name = '{EscapeSql(session.OperatorName)}',
                        effective_version = '{EscapeSql(session.EffectiveVersion)}',
                        state = {(int)session.State},
                        reservation_ref = '{EscapeSql(session.ReservationRef)}',
                        closed_at = {(session.ClosedAt.HasValue ? $"'{session.ClosedAt.Value:yyyy-MM-dd HH:mm:ss}'" : "NULL")}
                    WHERE session_id = '{EscapeSql(session.SessionId)}'";
 
                _sqliteHelper.ExecuteSql(sql);
                log.Debug($"更新会话: {session.SessionId}, 状态: {session.State}");
            }
            catch (Exception ex)
            {
                log.Error($"更新会话失败: {ex.Message}", ex);
                throw;
            }
        }
 
        /// <summary>
        /// 获取设备的所有活跃会话(未关闭的)
        /// </summary>
        public List<DebugSession> GetActiveSessionsByDevice(string deviceId)
        {
            try
            {
                if (_sqliteHelper == null)
                    throw new InvalidOperationException("数据库未初始化,请先调用 InitDatabase");
 
                string sql = $@"
                    SELECT * FROM debug_session 
                    WHERE device_id = '{EscapeSql(deviceId)}' 
                    AND state != {(int)DebugSessionState.Closed}
                    ORDER BY created_at DESC";
 
                DataTable dt = _sqliteHelper.GetDataTable(sql);
                return dt.Rows.Cast<DataRow>().Select(MapToDebugSession).ToList();
            }
            catch (Exception ex)
            {
                log.Error($"获取设备活跃会话失败: {ex.Message}", ex);
                return new List<DebugSession>();
            }
        }
 
        /// <summary>
        /// 获取所有会话
        /// </summary>
        public List<DebugSession> GetAllSessions()
        {
            try
            {
                if (_sqliteHelper == null)
                    throw new InvalidOperationException("数据库未初始化,请先调用 InitDatabase");
 
                string sql = "SELECT * FROM debug_session ORDER BY created_at DESC";
                DataTable dt = _sqliteHelper.GetDataTable(sql);
                return dt.Rows.Cast<DataRow>().Select(MapToDebugSession).ToList();
            }
            catch (Exception ex)
            {
                log.Error($"获取所有会话失败: {ex.Message}", ex);
                return new List<DebugSession>();
            }
        }
 
        #endregion
 
        #region 审计 CRUD
 
        /// <summary>
        /// 记录操作
        /// </summary>
        public void RecordOperation(DebugOperation operation)
        {
            try
            {
                if (_sqliteHelper == null)
                    throw new InvalidOperationException("数据库未初始化,请先调用 InitDatabase");
 
                string sql = $@"
                    INSERT INTO debug_operation (
                        operation_id, session_id, command_type, parameters,
                        outcome, device_readback, error_code, error_message, timestamp
                    ) VALUES (
                        '{EscapeSql(operation.OperationId)}',
                        '{EscapeSql(operation.SessionId)}',
                        '{EscapeSql(operation.CommandType)}',
                        '{EscapeSql(operation.Parameters)}',
                        '{EscapeSql(operation.Outcome)}',
                        '{EscapeSql(operation.DeviceReadback)}',
                        '{EscapeSql(operation.ErrorCode)}',
                        '{EscapeSql(operation.ErrorMessage)}',
                        '{operation.Timestamp:yyyy-MM-dd HH:mm:ss}'
                    )";
 
                _sqliteHelper.ExecuteSql(sql);
                log.Debug($"记录操作: {operation.OperationId}, 类型: {operation.CommandType}, 结果: {operation.Outcome}");
            }
            catch (Exception ex)
            {
                log.Error($"记录操作失败: {ex.Message}", ex);
                throw;
            }
        }
 
        /// <summary>
        /// 获取会话的所有操作
        /// </summary>
        public List<DebugOperation> GetOperationsBySession(string sessionId)
        {
            try
            {
                if (_sqliteHelper == null)
                    throw new InvalidOperationException("数据库未初始化,请先调用 InitDatabase");
 
                string sql = $@"
                    SELECT * FROM debug_operation 
                    WHERE session_id = '{EscapeSql(sessionId)}'
                    ORDER BY timestamp DESC";
 
                DataTable dt = _sqliteHelper.GetDataTable(sql);
                return dt.Rows.Cast<DataRow>().Select(MapToDebugOperation).ToList();
            }
            catch (Exception ex)
            {
                log.Error($"获取会话操作失败: {ex.Message}", ex);
                return new List<DebugOperation>();
            }
        }
 
        /// <summary>
        /// 获取设备最近的操作
        /// </summary>
        public List<DebugOperation> GetRecentOperations(string deviceId, int count)
        {
            try
            {
                if (_sqliteHelper == null)
                    throw new InvalidOperationException("数据库未初始化,请先调用 InitDatabase");
 
                string sql = $@"
                    SELECT o.* FROM debug_operation o
                    INNER JOIN debug_session s ON o.session_id = s.session_id
                    WHERE s.device_id = '{EscapeSql(deviceId)}'
                    ORDER BY o.timestamp DESC
                    LIMIT {count}";
 
                DataTable dt = _sqliteHelper.GetDataTable(sql);
                return dt.Rows.Cast<DataRow>().Select(MapToDebugOperation).ToList();
            }
            catch (Exception ex)
            {
                log.Error($"获取最近操作失败: {ex.Message}", ex);
                return new List<DebugOperation>();
            }
        }
 
        #endregion
 
        #region 辅助方法
 
        /// <summary>
        /// 将 DataRow 映射为 DebugSession
        /// </summary>
        private DebugSession MapToDebugSession(DataRow row)
        {
            return new DebugSession
            {
                SessionId = row["session_id"].ToString() ?? string.Empty,
                DeviceId = row["device_id"].ToString() ?? string.Empty,
                OperatorId = row["operator_id"].ToString() ?? string.Empty,
                OperatorName = row["operator_name"]?.ToString() ?? string.Empty,
                EffectiveVersion = row["effective_version"]?.ToString() ?? string.Empty,
                State = (DebugSessionState)Convert.ToInt32(row["state"]),
                ReservationRef = row["reservation_ref"]?.ToString() ?? string.Empty,
                CreatedAt = DateTime.Parse(row["created_at"].ToString() ?? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                ClosedAt = row["closed_at"] != DBNull.Value && !string.IsNullOrEmpty(row["closed_at"].ToString())
                    ? DateTime.Parse(row["closed_at"].ToString()!)
                    : null
            };
        }
 
        /// <summary>
        /// 将 DataRow 映射为 DebugOperation
        /// </summary>
        private DebugOperation MapToDebugOperation(DataRow row)
        {
            return new DebugOperation
            {
                OperationId = row["operation_id"].ToString() ?? string.Empty,
                SessionId = row["session_id"].ToString() ?? string.Empty,
                CommandType = row["command_type"].ToString() ?? string.Empty,
                Parameters = row["parameters"]?.ToString() ?? string.Empty,
                Outcome = row["outcome"].ToString() ?? string.Empty,
                DeviceReadback = row["device_readback"]?.ToString() ?? string.Empty,
                ErrorCode = row["error_code"]?.ToString() ?? string.Empty,
                ErrorMessage = row["error_message"]?.ToString() ?? string.Empty,
                Timestamp = DateTime.Parse(row["timestamp"].ToString() ?? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
            };
        }
 
        /// <summary>
        /// SQL 字符串转义(防止注入)
        /// </summary>
        private string EscapeSql(string value)
        {
            return value.Replace("'", "''");
        }
 
        #endregion
    }
}