Files
Mapo-IOB-WIN/IOB-UT-NEXT/Iob/Services/Machine/MachineCommunicationService.cs
T
2026-05-22 16:13:28 +02:00

90 lines
3.0 KiB
C#

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
{
/// <summary>
/// MachineCommunicationService: Orchestratore per il dominio MACCHINA (_machineThread).
/// Gestisce l'interazione a bassa latenza con PLC/CNC e la gestione della memoria condivisa (MemMap).
/// </summary>
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)
/// <summary>
/// Legge il conteggio pezzi attuale dal driver della macchina.
/// </summary>
public int GetPzCountIOB() => _tcMan.pzCountIOB;
/// <summary>
/// Legge il conteggio pezzi attuale dal PLC.
/// </summary>
public int GetPzCountPLC() => _tcMan.pzCountPLC;
/// <summary>
/// Ottiene la media dei tempi ciclo (TC) rilevati.
/// </summary>
public double GetAverageTc() => _tcMan.avgTC > 0 ? _tcMan.avgTC : 1.0;
/// <summary>
/// Ottiene l'ultimo timestamp osservato dal PLC.
/// </summary>
public DateTime GetLastObservedData() => _tcMan.lastObservedData;
#endregion
#region Memory Map Operations (Shared Memory Domain)
/// <summary>
/// Scrive un valore nella memoria condivisa (MemMap) per l'invio al PLC.
/// </summary>
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}");
}
}
}
/// <summary>
/// Legge un valore dalla memoria condivisa (MemMap) ricevuta dal PLC.
/// </summary>
public string ReadFromMemMap(string key)
{
if (_memMap != null && _memMap.mMapRead != null && _memMap.mMapRead.ContainsKey(key))
{
return _memMap.mMapRead[key].value;
}
return null;
}
#endregion
}
}