wanshenmean
2026-03-13 58376d519aeb76ef78d38b737c0c57f8d982fb52
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
using System.Collections.Concurrent;
using HslCommunication;
using HslCommunication.Profinet.Siemens;
using HslCommunication.Reflection;
using Microsoft.Extensions.Logging;
using WIDESEAWCS_S7Simulator.Core.Entities;
using WIDESEAWCS_S7Simulator.Core.Enums;
using WIDESEAWCS_S7Simulator.Core.Interfaces;
using WIDESEAWCS_S7Simulator.Core.Memory;
 
namespace WIDESEAWCS_S7Simulator.Core.Server
{
    /// <summary>
    /// S7服务器实例实现
    /// 使用HSL Communication库实现S7 PLC仿真服务器
    /// </summary>
    public class S7ServerInstance : IS7ServerInstance
    {
        private readonly ILogger<S7ServerInstance> _logger;
        private readonly object _lock = new();
        private SiemensS7Server? _server;
        private bool _disposed;
 
        /// <inheritdoc/>
        public InstanceConfig Config { get; }
 
        /// <inheritdoc/>
        public InstanceState State { get; private set; }
 
        /// <inheritdoc/>
        public IMemoryStore MemoryStore { get; }
 
        /// <summary>
        /// 客户端连接追踪
        /// </summary>
        private readonly ConcurrentDictionary<string, S7ClientConnection> _clients = new();
 
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="config">实例配置</param>
        /// <param name="logger">日志记录器</param>
        public S7ServerInstance(InstanceConfig config, ILogger<S7ServerInstance> logger)
        {
            Config = config ?? throw new ArgumentNullException(nameof(config));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 
            // 初始化内存存储
            MemoryStore = new MemoryStore(config.MemoryConfig);
 
            // 初始化状态
            State = new InstanceState
            {
                InstanceId = config.Id,
                Status = InstanceStatus.Stopped,
                ClientCount = 0,
                TotalRequests = 0
            };
 
            _logger.LogInformation("S7服务器实例 {InstanceId} ({InstanceName}) 已创建,PLC类型: {PLCType}, 端口: {Port}",
                config.Id, config.Name, config.PLCType, config.Port);
        }
 
        /// <inheritdoc/>
        public bool Start()
        {
            lock (_lock)
            {
                if (_disposed)
                {
                    _logger.LogError("无法启动已释放的实例 {InstanceId}", Config.Id);
                    return false;
                }
 
                if (State.Status == InstanceStatus.Running)
                {
                    _logger.LogWarning("实例 {InstanceId} 已在运行中", Config.Id);
                    return true;
                }
 
                try
                {
                    // 创建S7服务器
                    _server = new SiemensS7Server();
 
                    // 设置激活码
                    if (!string.IsNullOrWhiteSpace(Config.ActivationKey))
                    {
                        HslCommunication.Authorization.SetAuthorizationCode(Config.ActivationKey);
                        _logger.LogDebug("已设置激活码");
                    }
 
                    // 初始化DB块(根据配置)
                    InitializeDbBlocks();
 
                    // 从MemoryStore同步初始数据到服务器
                    SynchronizeMemoryToServer();
 
                    // 启动服务器
                    try
                    {
                        _server.ServerStart(Config.Port);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "启动S7服务器失败");
                        State.Status = InstanceStatus.Error;
                        State.ErrorMessage = ex.Message;
                        return false;
                    }
 
                    // 更新状态
                    State.Status = InstanceStatus.Running;
                    State.StartTime = DateTime.Now;
                    State.ErrorMessage = null;
 
                    _logger.LogInformation("S7服务器实例 {InstanceId} 已成功启动,监听端口: {Port}", Config.Id, Config.Port);
                    return true;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "启动S7服务器实例 {InstanceId} 时发生异常", Config.Id);
                    State.Status = InstanceStatus.Error;
                    State.ErrorMessage = ex.Message;
                    return false;
                }
            }
        }
 
        /// <inheritdoc/>
        public void Stop()
        {
            lock (_lock)
            {
                if (_disposed || State.Status == InstanceStatus.Stopped)
                {
                    return;
                }
 
                try
                {
                    if (_server != null)
                    {
                        // 停止前同步服务器数据到MemoryStore
                        SynchronizeServerToMemory();
 
                        _server.ServerClose();
                        _server = null;
                    }
 
                    // 清空客户端连接
                    _clients.Clear();
 
                    // 更新状态
                    State.Status = InstanceStatus.Stopped;
                    State.ClientCount = 0;
                    State.StartTime = null;
 
                    _logger.LogInformation("S7服务器实例 {InstanceId} 已停止", Config.Id);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "停止S7服务器实例 {InstanceId} 时发生异常", Config.Id);
                    State.Status = InstanceStatus.Error;
                    State.ErrorMessage = ex.Message;
                }
            }
        }
 
        /// <inheritdoc/>
        public bool Restart()
        {
            Stop();
            return Start();
        }
 
        /// <inheritdoc/>
        public InstanceState GetState()
        {
            lock (_lock)
            {
                // 更新客户端连接数
                State.ClientCount = _clients.Count;
                State.Clients = _clients.Values.ToList();
 
                // 返回状态副本
                return new InstanceState
                {
                    InstanceId = State.InstanceId,
                    Status = State.Status,
                    ClientCount = State.ClientCount,
                    TotalRequests = State.TotalRequests,
                    StartTime = State.StartTime,
                    LastActivityTime = State.LastActivityTime,
                    Clients = new List<S7ClientConnection>(State.Clients),
                    ErrorMessage = State.ErrorMessage
                };
            }
        }
 
        /// <inheritdoc/>
        public void ClearMemory()
        {
            lock (_lock)
            {
                MemoryStore.Clear();
 
                // 同时清空服务器内部数据
                if (_server != null && State.Status == InstanceStatus.Running)
                {
                    // 清空各内存区域
                    for (int i = 0; i < 100; i++)
                    {
                        _server.Write($"M{i}", (byte)0);
                        _server.Write($"I{i}", (byte)0);
                        _server.Write($"Q{i}", (byte)0);
                    }
 
                    // 清空DB块
                    for (ushort db = 1; db <= Config.MemoryConfig.DBBlockCount; db++)
                    {
                        for (int i = 0; i < 10; i++)
                        {
                            _server.Write($"DB{db}.DBD{i}", (byte)0);
                        }
                    }
                }
 
                _logger.LogInformation("实例 {InstanceId} 内存已清空", Config.Id);
            }
        }
 
        /// <inheritdoc/>
        public Dictionary<string, byte[]> ExportMemory()
        {
            lock (_lock)
            {
                // 先同步服务器数据到MemoryStore
                if (_server != null && State.Status == InstanceStatus.Running)
                {
                    SynchronizeServerToMemory();
                }
                return MemoryStore.Export();
            }
        }
 
        /// <inheritdoc/>
        public void ImportMemory(Dictionary<string, byte[]> data)
        {
            lock (_lock)
            {
                MemoryStore.Import(data);
 
                // 同步到服务器
                if (_server != null && State.Status == InstanceStatus.Running)
                {
                    SynchronizeMemoryToServer();
                }
 
                _logger.LogInformation("实例 {InstanceId} 内存数据已导入", Config.Id);
            }
        }
 
        /// <summary>
        /// 初始化DB块
        /// </summary>
        private void InitializeDbBlocks()
        {
            if (_server == null)
                return;
 
            try
            {
                // 根据配置添加DB块
                for (ushort i = 1; i <= Config.MemoryConfig.DBBlockCount; i++)
                {
                    _server.AddDbBlock(i, Config.MemoryConfig.DBBlockSize);
                    _logger.LogDebug("已添加DB块: DB{DbNumber}, 大小: {Size}", i, Config.MemoryConfig.DBBlockSize);
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "初始化DB块时发生警告");
            }
        }
 
        /// <summary>
        /// 从MemoryStore同步数据到服务器
        /// </summary>
        private void SynchronizeMemoryToServer()
        {
            if (_server == null)
                return;
 
            try
            {
                var data = MemoryStore.Export();
 
                // 同步M区
                if (data.ContainsKey("M"))
                {
                    var mBytes = data["M"];
                    for (int i = 0; i < Math.Min(mBytes.Length, Config.MemoryConfig.MRegionSize); i++)
                    {
                        _server.Write($"M{i}", mBytes[i]);
                    }
                }
 
                // 同步I区
                if (data.ContainsKey("I"))
                {
                    var iBytes = data["I"];
                    for (int i = 0; i < Math.Min(iBytes.Length, Config.MemoryConfig.IRegionSize); i++)
                    {
                        _server.Write($"I{i}", iBytes[i]);
                    }
                }
 
                // 同步Q区
                if (data.ContainsKey("Q"))
                {
                    var qBytes = data["Q"];
                    for (int i = 0; i < Math.Min(qBytes.Length, Config.MemoryConfig.QRegionSize); i++)
                    {
                        _server.Write($"Q{i}", qBytes[i]);
                    }
                }
 
                // 同步DB区
                if (data.ContainsKey("DB"))
                {
                    var dbBytes = data["DB"];
                    int offset = 0;
                    for (ushort db = 1; db <= Config.MemoryConfig.DBBlockCount; db++)
                    {
                        int blockSize = Math.Min(Config.MemoryConfig.DBBlockSize, dbBytes.Length - offset);
                        for (int i = 0; i < blockSize; i++)
                        {
                            _server.Write($"DB{db}.DBD{i}", dbBytes[offset + i]);
                        }
                        offset += Config.MemoryConfig.DBBlockSize;
                    }
                }
 
                _logger.LogDebug("已将MemoryStore数据同步到S7服务器");
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "同步数据到服务器时发生警告");
            }
        }
 
        /// <summary>
        /// 从服务器同步数据到MemoryStore
        /// </summary>
        private void SynchronizeServerToMemory()
        {
            if (_server == null)
                return;
 
            try
            {
                var data = new Dictionary<string, byte[]>();
 
                // 读取M区
                var mResult = _server.Read("M0", (ushort)Config.MemoryConfig.MRegionSize);
                if (mResult.IsSuccess)
                {
                    data["M"] = mResult.Content;
                }
 
                // 读取I区
                var iResult = _server.Read("I0", (ushort)Config.MemoryConfig.IRegionSize);
                if (iResult.IsSuccess)
                {
                    data["I"] = iResult.Content;
                }
 
                // 读取Q区
                var qResult = _server.Read("Q0", (ushort)Config.MemoryConfig.QRegionSize);
                if (qResult.IsSuccess)
                {
                    data["Q"] = qResult.Content;
                }
 
                // 读取DB区
                var dbBytes = new List<byte>();
                for (ushort db = 1; db <= Config.MemoryConfig.DBBlockCount; db++)
                {
                    var dbResult = _server.Read($"DB{db}.DBD0", (ushort)Config.MemoryConfig.DBBlockSize);
                    if (dbResult.IsSuccess)
                    {
                        dbBytes.AddRange(dbResult.Content);
                    }
                }
                data["DB"] = dbBytes.ToArray();
 
                // 导入到MemoryStore
                MemoryStore.Import(data);
 
                _logger.LogDebug("已将S7服务器数据同步到MemoryStore");
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "从服务器同步数据时发生警告");
            }
        }
 
        /// <summary>
        /// 增加请求计数并更新活动时间
        /// </summary>
        private void IncrementRequestCount()
        {
            State.TotalRequests++;
            State.LastActivityTime = DateTime.Now;
        }
 
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
 
        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="disposing">是否正在释放托管资源</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    Stop();
                    MemoryStore?.Dispose();
                }
                _disposed = true;
            }
        }
    }
}