using Microsoft.AspNetCore.Mvc;
using WIDESEAWCS_S7Simulator.Core.Interfaces;
namespace WIDESEAWCS_S7Simulator.Server.Controllers
{
///
/// 内存操作控制器
///
[ApiController]
[Route("api/[controller]")]
public class MemoryController : ControllerBase
{
private readonly ISimulatorInstanceManager _instanceManager;
private readonly ILogger _logger;
public MemoryController(
ISimulatorInstanceManager instanceManager,
ILogger logger)
{
_instanceManager = instanceManager ?? throw new ArgumentNullException(nameof(instanceManager));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
///
/// 读取内存数据
///
[HttpGet("ReadMemory")]
[ProducesResponseType(typeof(Dictionary), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult> 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" });
}
}
///
/// 写入内存数据
///
[HttpPost("WriteMemory")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult WriteMemory(string id, Dictionary 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" });
}
}
///
/// 清空内存数据
///
[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" });
}
}
///
/// 保存内存快照
///
[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" });
}
}
///
/// 加载内存快照
///
[HttpPost("LoadMemorySnapshot")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult LoadMemorySnapshot(string id, Dictionary 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" });
}
}
}
}