using System; using System.Collections.Generic; using System.Threading.Tasks; using IOB_UT_NEXT.Config; using IOB_UT_NEXT.Config.Mem; using IOB_UT_NEXT.Objects; using IOB_UT_NEXT.Services.Core; using NLog; namespace IOB_UT_NEXT.Services.Machine { /// /// MachineCommunicationService: Orchestratore per il dominio MACCHINA (_machineThread). /// Gestisce l'interazione con tcMan e memMap, incapsulando la logica di "maneggio" dei dati. /// public class MachineCommunicationService { #region Public Constructors public MachineCommunicationService(IobConfTree config, TCMan tcMan, plcMemMapExt memMap) { _config = config ?? throw new ArgumentNullException(nameof(config)); _tcMan = tcMan ?? throw new ArgumentNullException(nameof(tcMan)); _memMap = memMap ?? throw new ArgumentNullException(nameof(memMap)); } #endregion Public Constructors #region Public Methods /// /// Ottiene la media dei tempi ciclo (TC) rilevati. /// public double GetAverageTc() => _tcMan.avgTC > 0 ? _tcMan.avgTC : 1.0; /// /// Ottiene l'ultimo timestamp osservato dal PLC. /// public DateTime GetLastObservedData() => _tcMan.lastObservedData; /// /// Gestione conteggio pezzi attuale dal driver della macchina. /// /// public int ContapezziIOB { get => _tcMan.pzCountIOB; set => _tcMan.pzCountIOB=value; } /// /// Gestione conteggio pezzi attuale dal PLC. /// public int ContapezziPLC { get => _tcMan.pzCountPLC; set => _tcMan.pzCountPLC = value; } /// /// Legge un valore dalla memoria condivisa (MemMap) ricevuta dal PLC. /// public string ReadFromMemMap(string key) { if (_memMap != null && _memMap.mMapRead != null && _memMap.mMapRead.ContainsKey(key)) { return _memMap.mMapRead[key].value; } return null; } /// /// Scrive un valore nella memoria condivisa (MemMap) per l'invio al PLC. /// public void WriteToMemMap(string key, string value) { if (_memMap != null && _memMap.mMapWrite != null) { if (_memMap.mMapWrite.ContainsKey(key)) { _memMap.mMapWrite[key].value = value; logger.Debug($"[MachineComm] MemMap Write: {key} = {value}"); } else { logger.Warn($"[MachineComm] Attempted write to non-existent MemMap key: {key}"); } } } #endregion Public Methods #region Private Fields private static readonly Logger logger = LogManager.GetCurrentClassLogger(); private readonly IobConfTree _config; private readonly plcMemMapExt _memMap; private readonly TCMan _tcMan; #endregion Private Fields } }