using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NLog;
using NcProgramManager.Cnc;
using NcProgramManager.Cnc.Models;
namespace NcProgramManager.Cnc.Mazak
{
///
/// Mazak CNC machine - EIA/ISO program transfer over FTP.
/// Targets Mazak Smooth/Matrix controls exposing an FTP server for the
/// NC program directory. EIA/ISO files are dropped/read by their exact
/// filename: there is no active-program channel over FTP.
///
public sealed class MazakMachine : ICncMachine
{
private static readonly Logger _log = LogManager.GetCurrentClassLogger();
private readonly MazakConnectionConfig _config;
private readonly IMazakFtpClient _ftp;
private readonly INcProgramValidator _validator;
private readonly List _errors = new List();
private readonly SemaphoreSlim _gate = new SemaphoreSlim(1, 1);
private ConnectionState _state = ConnectionState.Disconnected;
public MazakMachine(MazakConnectionConfig config)
{
_config = config ?? throw new ArgumentNullException("config");
_ftp = new MazakFtpClient(config);
_validator = new NcProgramValidator(CncManufacturer.Mazak);
}
internal MazakMachine(MazakConnectionConfig config, IMazakFtpClient ftpClient,
INcProgramValidator validator = null)
{
_config = config ?? throw new ArgumentNullException("config");
_ftp = ftpClient ?? throw new ArgumentNullException("ftpClient");
_validator = validator ?? new NcProgramValidator(CncManufacturer.Mazak);
}
public string Name { get { return _config.Name; } }
public ConnectionState State { get { return _state; } }
public event EventHandler StateChanged;
public Task> ConnectAsync(CancellationToken ct = default(CancellationToken))
{
return RunGuardedAsync(() =>
{
SetState(ConnectionState.Connecting);
if (!_ftp.Ping())
{
SetState(ConnectionState.Faulted);
_errors.Add(new CncError(0, "Connect",
string.Format("FTP server unreachable at {0}:{1}", _config.IpAddress, _config.Port)));
return false;
}
SetState(ConnectionState.Connected);
return true;
}, ct);
}
public Task DisconnectAsync()
{
return RunGuardedAsync(() =>
{
SetState(ConnectionState.Disconnected);
return true;
}, CancellationToken.None);
}
public Task> ReadProgramAsync(string path, CancellationToken ct = default(CancellationToken))
{
return RunGuardedAsync(() =>
{
EnsureConnected();
string ncPath = ResolvePath(path);
try { return _ftp.DownloadFile(ncPath); }
catch (Exception ex)
{
_errors.Add(new CncError(0, "ReadProgram", ex.Message));
return null;
}
}, ct);
}
public Task> WriteProgramAsync(string path, CncProgram program, CancellationToken ct = default(CancellationToken))
{
return RunGuardedAsync(() =>
{
EnsureConnected();
if (program == null || string.IsNullOrEmpty(program.Content))
{
_errors.Add(new CncError(0, "WriteProgram", "Content is empty"));
return false;
}
var vr = _validator.Validate(program.Name ?? path, program.Content);
if (!vr.Success)
{
string msg = string.Join("; ", vr.Errors
.Where(e => e.Severity == ValidationSeverity.Error)
.Select(e => e.Message));
_errors.Add(new CncError(0, "Validator", msg));
return false;
}
// ISS-020: resolve the write path the same way ReadProgramAsync does.
// `path` is the EIA/ISO filename verbatim (e.g. "O1234" -> /PRG/O1234)
// or a full FTP path, NOT a directory to combine with program.Name.
// Mazak addresses files by their exact filename; program.Name is used
// for validation only, not for path construction.
string ncPath = ResolvePath(path);
try { _ftp.UploadFile(ncPath, program.Content); return true; }
catch (Exception ex)
{
_errors.Add(new CncError(0, "WriteProgram", ex.Message));
return false;
}
}, ct);
}
public Task> DeleteProgramAsync(string path, CancellationToken ct = default(CancellationToken))
{
return RunGuardedAsync(() =>
{
EnsureConnected();
string ncPath = ResolvePath(path);
try { _ftp.DeleteFile(ncPath); return true; }
catch (Exception ex)
{
_errors.Add(new CncError(0, "DeleteProgram", ex.Message));
return false;
}
}, ct);
}
///
/// Lista una directory FTP del Mazak (un solo livello). Utile per sondare
/// la connessione e verificare che
/// sia vista correttamente e quali file EIA/ISO siano disponibili.
/// Path vuoto = ProgramDirectory configurata.
///
public Task>> ListDirectoryAsync(string path = null, CancellationToken ct = default(CancellationToken))
{
return RunGuardedAsync(() =>
{
EnsureConnected();
string dir = string.IsNullOrEmpty(path) ? _config.ProgramDirectory : path;
try { return _ftp.ListDirectory(dir); }
catch (Exception ex)
{
_errors.Add(new CncError(0, "ListDirectory", ex.Message));
return null;
}
}, ct);
}
///
/// Costruisce un albero testuale (tree) della directory FTP a partire da
/// , scendendo ricorsivamente fino a
/// livelli. Diagnostica: mostra come il server
/// FTP del Mazak espone la cartella programmi e quali file contiene.
/// Errori per singola sottocartella sono annotati inline e non interrompono
/// l'intero albero.
///
public Task> BuildTreeAsync(string path = null, int maxDepth = 2, CancellationToken ct = default(CancellationToken))
{
return RunGuardedAsync(() =>
{
EnsureConnected();
string root = string.IsNullOrEmpty(path) ? _config.ProgramDirectory : path;
var sb = new System.Text.StringBuilder();
sb.AppendLine(string.IsNullOrEmpty(root) ? "/" : root);
// Root-level list failure MUST propagate -> RunGuardedAsync -> Fail.
// A diagnostic probe that can't even list its root must not exit 0.
var rootEntries = _ftp.ListDirectory(root);
AppendEntries(sb, rootEntries, "", maxDepth - 1, ct);
return sb.ToString();
}, ct);
}
///
/// Rende gli entry di una directory e ricorre nelle sottocartelle finche'
/// > 0. Best-effort per i figli: gli errori
/// di lista delle sottocartelle sono annotati inline e non interrompono
/// l'intero albero (la root e' gestita a monte e propaga).
///
private void AppendEntries(System.Text.StringBuilder sb, IReadOnlyList entries, string prefix, int depthLeft, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
for (int i = 0; i < entries.Count; i++)
{
var e = entries[i];
bool last = i == entries.Count - 1;
string connector = last ? "└─ " : "├─ "; // "└─ " / "├─ "
sb.AppendLine(string.Format("{0}{1}{2}{3}",
prefix, connector, e.Name,
e.IsDirectory ? "/" : (e.Size >= 0 ? string.Format(" ({0} B)", e.Size) : "")));
if (e.IsDirectory && depthLeft > 0)
{
string childPrefix = prefix + (last ? " " : "│ "); // "│ "
IReadOnlyList childEntries;
try { childEntries = _ftp.ListDirectory(e.FullPath); }
catch (Exception ex)
{
sb.AppendLine(string.Format("{0}!! ", childPrefix, ex.Message));
continue;
}
AppendEntries(sb, childEntries, childPrefix, depthLeft - 1, ct);
}
}
}
public Task> ReadAsync(CancellationToken ct = default(CancellationToken))
{
return RunGuardedAsync(() =>
{
EnsureConnected();
return new MachineSnapshot
{
CapturedAt = DateTime.Now,
Mode = MachineMode.Unknown,
Run = RunState.Unknown,
Motion = MotionState.Unknown,
Alarms = new List(),
OperatorMessages = new List()
};
}, ct);
}
public Task> ReadActiveProgramAsync(CancellationToken ct = default(CancellationToken))
{
return Task.FromResult(CncResult.Fail("ReadActiveProgram", "Not supported via FTP"));
}
public Task> SelectMainProgramAsync(string path, CancellationToken ct = default(CancellationToken))
{
return Task.FromResult(CncResult.Fail("SelectMainProgram", "Not supported via FTP"));
}
public void Dispose()
{
try { DisconnectAsync().GetAwaiter().GetResult(); } catch { /* cleanup - intentionally swallowed */ }
try { _gate.Dispose(); } catch { /* cleanup - intentionally swallowed */ }
}
private async Task> RunGuardedAsync(Func body, CancellationToken ct)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
return await Task.Run(() =>
{
_errors.Clear();
try
{
T value = body();
return _errors.Count > 0
? CncResult.Fail(_errors.ToArray())
: CncResult.Ok(value);
}
catch (OperationCanceledException) { return CncResult.Cancelled(); }
catch (Exception ex)
{
_errors.Add(new CncError(0, "MazakMachine", ex.Message));
return CncResult.Fail(_errors.ToArray());
}
}, ct).ConfigureAwait(false);
}
finally { _gate.Release(); }
}
private void EnsureConnected()
{
if (_state != ConnectionState.Connected)
throw new InvalidOperationException("MazakMachine is not connected.");
}
private void SetState(ConnectionState next)
{
if (_state == next) return;
_state = next;
var h = StateChanged;
if (h != null)
{
try { h(this, next); } catch (Exception ex) { _log.Warn(ex, "StateChanged handler threw"); }
}
}
///
/// Build full FTP path. Mazak EIA/ISO files are addressed by their exact
/// filename verbatim - there is NO extension append (the operator supplies
/// the filename as it lives on the control). A bare identifier ("O1234") is
/// combined with ; an
/// explicit path containing '/' is used as-is. Read and write resolve
/// identically (ISS-020 symmetric path).
///
private string ResolvePath(string path)
{
if (string.IsNullOrEmpty(path)) return _config.ProgramDirectory;
if (path.Contains("/")) return path;
string dir = _config.ProgramDirectory ?? "/";
if (!dir.EndsWith("/")) dir += "/";
return dir + path;
}
}
}