wanshenmean
2026-03-24 ab2076893b8df3c14f1a126d47e9eee132a38f4b
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
using Microsoft.AspNetCore.Mvc;
using WIDESEAWCS_S7Simulator.Core.Interfaces;
 
namespace WIDESEAWCS_S7Simulator.Server.Controllers
{
    /// <summary>
    /// 内存操作控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class MemoryController : ControllerBase
    {
        private readonly ISimulatorInstanceManager _instanceManager;
        private readonly ILogger<MemoryController> _logger;
 
        public MemoryController(
            ISimulatorInstanceManager instanceManager,
            ILogger<MemoryController> logger)
        {
            _instanceManager = instanceManager ?? throw new ArgumentNullException(nameof(instanceManager));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }
 
        /// <summary>
        /// 读取内存数据
        /// </summary>
        [HttpGet("ReadMemory")]
        [ProducesResponseType(typeof(Dictionary<string, byte[]>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public ActionResult<Dictionary<string, byte[]>> ReadMemory(string id)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return BadRequest(new { error = "Instance ID is required" });
                }
 
                var instance = _instanceManager.GetInstance(id);
                if (instance == null)
                {
                    return NotFound(new { error = $"Instance with ID '{id}' not found" });
                }
 
                var memoryData = instance.ExportMemory();
                return Ok(memoryData);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to read memory for instance {InstanceId}", id);
                return StatusCode(StatusCodes.Status500InternalServerError, new { error = "Failed to read memory" });
            }
        }
 
        /// <summary>
        /// 写入内存数据
        /// </summary>
        [HttpPost("WriteMemory")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public ActionResult WriteMemory(string id,  Dictionary<string, byte[]> data)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return BadRequest(new { error = "Instance ID is required" });
                }
 
                if (data == null || data.Count == 0)
                {
                    return BadRequest(new { error = "Memory data is required" });
                }
 
                var instance = _instanceManager.GetInstance(id);
                if (instance == null)
                {
                    return NotFound(new { error = $"Instance with ID '{id}' not found" });
                }
 
                instance.ImportMemory(data);
                return Ok(new { message = "Memory data written successfully" });
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning(ex, "Invalid memory data for instance {InstanceId}", id);
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to write memory for instance {InstanceId}", id);
                return StatusCode(StatusCodes.Status500InternalServerError, new { error = "Failed to write memory" });
            }
        }
 
        /// <summary>
        /// 清空内存数据
        /// </summary>
        [HttpDelete("ClearMemory")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public ActionResult ClearMemory(string id)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return BadRequest(new { error = "Instance ID is required" });
                }
 
                var instance = _instanceManager.GetInstance(id);
                if (instance == null)
                {
                    return NotFound(new { error = $"Instance with ID '{id}' not found" });
                }
 
                instance.ClearMemory();
                return Ok(new { message = "Memory cleared successfully" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to clear memory for instance {InstanceId}", id);
                return StatusCode(StatusCodes.Status500InternalServerError, new { error = "Failed to clear memory" });
            }
        }
 
        /// <summary>
        /// 保存内存快照
        /// </summary>
        [HttpPost("SaveMemorySnapshot")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public ActionResult SaveMemorySnapshot(string id,  string? snapshotName = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return BadRequest(new { error = "Instance ID is required" });
                }
 
                var instance = _instanceManager.GetInstance(id);
                if (instance == null)
                {
                    return NotFound(new { error = $"Instance with ID '{id}' not found" });
                }
 
                var memoryData = instance.ExportMemory();
                var fileName = string.IsNullOrWhiteSpace(snapshotName)
                    ? $"snapshot_{id}_{DateTime.UtcNow:yyyyMMdd_HHmmss}.json"
                    : snapshotName;
 
                // In a real implementation, you would save this to a file system or database
                // For now, we'll return the data that would be saved
                return Ok(new
                {
                    message = "Memory snapshot captured successfully",
                    fileName = fileName,
                    timestamp = DateTime.UtcNow,
                    dataSize = memoryData.Sum(kvp => kvp.Value.Length),
                    regions = memoryData.Keys.ToList()
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to save memory snapshot for instance {InstanceId}", id);
                return StatusCode(StatusCodes.Status500InternalServerError, new { error = "Failed to save memory snapshot" });
            }
        }
 
        /// <summary>
        /// 加载内存快照
        /// </summary>
        [HttpPost("LoadMemorySnapshot")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public ActionResult LoadMemorySnapshot(string id,  Dictionary<string, byte[]> snapshotData)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return BadRequest(new { error = "Instance ID is required" });
                }
 
                if (snapshotData == null || snapshotData.Count == 0)
                {
                    return BadRequest(new { error = "Snapshot data is required" });
                }
 
                var instance = _instanceManager.GetInstance(id);
                if (instance == null)
                {
                    return NotFound(new { error = $"Instance with ID '{id}' not found" });
                }
 
                instance.ImportMemory(snapshotData);
                return Ok(new
                {
                    message = "Memory snapshot loaded successfully",
                    timestamp = DateTime.UtcNow,
                    regions = snapshotData.Keys.ToList()
                });
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning(ex, "Invalid snapshot data for instance {InstanceId}", id);
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to load memory snapshot for instance {InstanceId}", id);
                return StatusCode(StatusCodes.Status500InternalServerError, new { error = "Failed to load memory snapshot" });
            }
        }
    }
}