using System; using System.Collections.Generic; using System.Threading.Tasks; using IOB_UT_NEXT.Config; using IOB_UT_NEXT.Objects; using IOB_UT_NEXT.Services.Core; using MapoSDK; using NLog; namespace IOB_UT_NEXT.Services.Machine { /// /// MachineCommunicationService: Orchestratore per il dominio MACCHINA (_machineThread). /// Gestisce l'interazione a bassa latenza con PLC/CNC e la gestione della memoria condivisa (MemMap). /// public class MachineCommunicationService { private readonly IobConfTree _config; private readonly TCMan _tcMan; private readonly plcMemMap _memMap; private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public MachineCommunicationService(IobConfTree config, TCMan tcMan, plcMemMap memMap) { _config = config ?? throw new ArgumentNullException(nameof(config)); _tcMan = tcMan ?? throw new ArgumentNullException(nameof(tcMan)); _memMap = memMap ?? throw new ArgumentNullException(nameof(memMap)); } #region PLC / CNC Operations (Real-Time Domain) /// /// Legge il conteggio pezzi attuale dal driver della macchina. /// public int GetPzCountIOB() => _tcMan.pzCountIOB; /// /// Legge il conteggio pezzi attuale dal PLC. /// public int GetPzCountPLC() => _tcMan.pzCountPLC; /// /// 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; #endregion #region Memory Map Operations (Shared Memory Domain) /// /// 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}"); } } } /// /// 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; } #endregion } }