initialize

This commit is contained in:
Pruefer
2025-06-06 09:15:13 +02:00
commit fa7c2730f1
5817 changed files with 1339670 additions and 0 deletions

View File

@@ -0,0 +1,266 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{CF1DDACB-CCBC-464C-A946-23B526E766CA}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>com.itac.mes.proxy</RootNamespace>
<AssemblyName>AdapterApplication5x</AssemblyName>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>4.0</OldToolsVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<ManifestCertificateThumbprint>866A2DE643095EA59F094BA8FFCA188CAA8AAE48</ManifestCertificateThumbprint>
<ManifestKeyFile>siemens.oib.proxy_TemporaryKey.pfx</ManifestKeyFile>
<GenerateManifests>true</GenerateManifests>
<SignManifests>false</SignManifests>
<ApplicationIcon>icon_itac_logo_oib.ico</ApplicationIcon>
<StartupObject>com.itac.mes.proxy.winservice.WindowsService</StartupObject>
<TargetFrameworkProfile />
<PublishUrl>C:\projects_jee\product\mainline\mes.suite\interfaces\datainterface\siemens.oib.publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>false</MapFileExtensions>
<SupportUrl>http://www.itacsoftware.com</SupportUrl>
<ProductName>MES.Suite OIB Adapter</ProductName>
<PublisherName>iTAC Software AG</PublisherName>
<OpenBrowserOnPublish>false</OpenBrowserOnPublish>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.3.0.0</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<DocumentationFile>
</DocumentationFile>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
<NoWarn>
</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>2</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<PlatformTarget>x86</PlatformTarget>
<NoWarn>436</NoWarn>
<DocumentationFile>
</DocumentationFile>
<CodeAnalysisIgnoreGeneratedCode>false</CodeAnalysisIgnoreGeneratedCode>
<RunCodeAnalysis>false</RunCodeAnalysis>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup />
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ItemGroup>
<Reference Include="artes-dotnet">
<HintPath>..\libs\itac\artes-dotnet.dll</HintPath>
</Reference>
<Reference Include="ASM.AS.OIB.Client">
<HintPath>..\libs\asm5client\ASM.AS.OIB.Client.dll</HintPath>
</Reference>
<Reference Include="ASM.AS.OIB.Client.CustomExtensions">
<HintPath>..\libs\asm5client\ASM.AS.OIB.Client.CustomExtensions.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.Common">
<HintPath>..\libs\oib5\Asm.As.Oib.Common.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.Common.Proxy">
<HintPath>..\libs\oib5\Asm.As.Oib.Common.Proxy.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.ConfigurationManager.Contracts">
<HintPath>..\libs\oib5\Asm.As.Oib.ConfigurationManager.Contracts.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.ConfigurationManager.Proxy">
<HintPath>..\libs\oib5\Asm.As.Oib.ConfigurationManager.Proxy.dll</HintPath>
</Reference>
<Reference Include="ASM.AS.OIB.DisplayService.Contracts">
<HintPath>..\libs\oib5\ASM.AS.OIB.DisplayService.Contracts.dll</HintPath>
</Reference>
<Reference Include="ASM.AS.OIB.DisplayService.Proxy">
<HintPath>..\libs\oib5\ASM.AS.OIB.DisplayService.Proxy.dll</HintPath>
</Reference>
<Reference Include="ASM.AS.OIB.HealthCheck.Contracts">
<HintPath>..\libs\oib5\ASM.AS.OIB.HealthCheck.Contracts.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.Monitoring.Contracts">
<HintPath>..\libs\oib5\Asm.As.Oib.Monitoring.Contracts.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.Monitoring.Proxy">
<HintPath>..\libs\oib5\Asm.As.Oib.Monitoring.Proxy.dll</HintPath>
</Reference>
<Reference Include="ASM.AS.OIB.ServiceLocator.Contracts">
<HintPath>..\libs\oib5\ASM.AS.OIB.ServiceLocator.Contracts.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.SIPLACEPro.Contracts">
<HintPath>..\libs\oib5\Asm.As.Oib.SIPLACEPro.Contracts.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.SIPLACEPro.LineControl.Contracts">
<HintPath>..\libs\oib5\Asm.As.Oib.SIPLACEPro.LineControl.Contracts.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.SIPLACEPro.LineControl.Proxy">
<HintPath>..\libs\oib5\Asm.As.Oib.SIPLACEPro.LineControl.Proxy.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.SIPLACEPro.Optimizer.Contracts">
<HintPath>..\libs\oib5\Asm.As.Oib.SIPLACEPro.Optimizer.Contracts.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.SIPLACEPro.Optimizer.Proxy">
<HintPath>..\libs\oib5\Asm.As.Oib.SIPLACEPro.Optimizer.Proxy.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.SIPLACEPro.Proxy">
<HintPath>..\libs\oib5\Asm.As.Oib.SIPLACEPro.Proxy.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.SIPLACESetupCenter.Contracts">
<HintPath>..\libs\oib5\Asm.As.Oib.SIPLACESetupCenter.Contracts.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.SiplaceSetupCenter.Proxy">
<HintPath>..\libs\oib5\Asm.As.Oib.SiplaceSetupCenter.Proxy.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.WS.Common">
<HintPath>..\libs\oib5\Asm.As.Oib.WS.Common.dll</HintPath>
</Reference>
<Reference Include="Asm.As.Oib.WS.Eventing.Contracts">
<HintPath>..\libs\oib5\Asm.As.Oib.WS.Eventing.Contracts.dll</HintPath>
</Reference>
<Reference Include="AsmApi5x">
<HintPath>..\libs\itac\AsmApi5x.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\libs\itac\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Runtime.Serialization">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\WINDOWS\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\System.ServiceModel.dll</HintPath>
</Reference>
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="com.itac.mes.proxy.sockets\IhapEventChannel.cs" />
<Compile Include="com.itac.mes.proxy.sockets\IhapHandler.cs" />
<Compile Include="com.itac.mes.proxy.sockets\SocketAdapter.cs" />
<Compile Include="com.itac.mes.proxy.winservice\WindowsService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="com.itac.mes.proxy.winservice\WindowsServiceInstaller.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="com.itac.oib.client\OibClientService.cs" />
<Compile Include="com.itac.oib.client\OibLineControlAccess.cs" />
<Compile Include="com.itac.oib.client\OibService.cs" />
<Compile Include="com.itac.oib.siplacepro.service\SiplacePro.cs" />
<Compile Include="Itac.Oib\DekPrinterExternalControlReceiver.cs" />
<Compile Include="Itac.Oib\DisplayServiceReceiver.cs" />
<Compile Include="Itac.Oib\LineControlMesInterceptorReceiver.cs" />
<Compile Include="Itac.Oib\ReceiverTemplate.cs" />
<Compile Include="Itac.Oib\IReceiver.cs" />
<Compile Include="com.itac.mes.domain\OIBEvents.cs" />
<Compile Include="com.itac.mes.domain\OIBService.cs" />
<Compile Include="com.itac.oib\IAdapterControl.cs" />
<Compile Include="com.itac.oib\IAdapterNotify.cs" />
<Compile Include="com.itac.oib\QueueInfo.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Itac.Oib\ChangeoverReceiver.cs" />
<Compile Include="Itac.Oib\BoardGateKeeperReceiver.cs" />
<Compile Include="Itac.Oib\SpiReceiver.cs" />
<Compile Include="Itac.Oib\SetupCenterReceiver.cs" />
<Compile Include="Itac.Oib\MonitoringReceiver.cs" />
<Compile Include="com.itac.oib\AdapterControl.cs" />
<Compile Include="com.itac.mes.proxy.business\OIBServiceImpl.cs" />
<Compile Include="com.itac.mes.proxy.business\OIBEventHandler.cs" />
<Compile Include="Itac.Oib\SetupCenterExternalControlReceiver.cs" />
<Compile Include="Itac.Oib\TraceabilityReceiver.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.2.0">
<Visible>False</Visible>
<ProductName>.NET Framework 2.0 %28x86%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
<Visible>False</Visible>
<ProductName>.NET Framework 3.0 %28x86%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
<Content Include="icon_itac_logo_oib.ico" />
<Content Include="Readme.txt" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ItacTools\ItacTools.csproj">
<Project>{db6626c3-81a3-49f4-9117-b20c9b87a2c4}</Project>
<Name>ItacTools</Name>
</ProjectReference>
<ProjectReference Include="..\Oib5xMapper\Oib5xMapper.csproj">
<Project>{9c9a30e3-68e7-4cd5-9dbb-4e54e70fb22c}</Project>
<Name>Oib5xMapper</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup />
</Project>

View File

@@ -0,0 +1,149 @@
#region Namespace
using System;
using System.Diagnostics;
using com.itac.mes.proxy.business;
using com.itac.mes.tools;
using com.itac.oib.client.customextensions;
using Constants = com.itac.mes.tools.Constants;
using OibClient = Asm.As.Oib.Client;
#endregion
namespace Itac.Oib
{
/// <summary>
/// Receiver class for the TraceService events
/// </summary>
public class BoardGateKeeperReceiver : IDisposable, IReceiver
{
#region Fields
OIBEventHandler _eventHandler;
readonly OibClient.OibBoardGateKeeperEvents _oibBoardGateKeeperEvents;
public static string DefaultMachineFullPath { get; internal set; }
public BoardGateKeeperReceiver(OibClient.OibBoardGateKeeperEvents oibBoardGateKeeperEvents,
OIBEventHandler eventHandler)
{
if (oibBoardGateKeeperEvents == null) throw new ArgumentNullException("oibBoardGateKeeperEvents");
if (eventHandler == null) throw new ArgumentNullException("eventHandler");
this._oibBoardGateKeeperEvents = oibBoardGateKeeperEvents;
this._eventHandler = eventHandler;
}
#endregion
#region Start/Stop
public void Start()
{
_oibBoardGateKeeperEvents.Start();
}
public void Stop()
{
_oibBoardGateKeeperEvents.Stop();
}
#endregion
#region IDisposeable
public void Dispose()
{
if (_oibBoardGateKeeperEvents != null) { _oibBoardGateKeeperEvents.Dispose(); }
}
#endregion
public void virtualInkspotData(OibClient.CustomExtensions.VirtualInkspotHandlerBoardRequest virtualInkspotHandlerBoardRequest)
{
try
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "BoardGateKeeperReceiver.VirtualInkspotData");
if (_eventHandler == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "calling BoardGateKeeperReceiver.VirtualInkspotData not performed, no eventHandler available");
return;
}
// map asm call values to itac struct
com.itac.oib.client.customextensions.VirtualInkspotHandlerBoardRequest virtInkspotBoardRequest = VirtualInkspotHandlerBoardRequestMapper.get(virtualInkspotHandlerBoardRequest);
// OIB 5.3 has a station information, oib 3 doesn't. If not available provide the first smt machines path to imsInterfaces.
if (virtInkspotBoardRequest.BoardRequestData.Position.Station == null)
{
virtInkspotBoardRequest.BoardRequestData.Position.Station = DefaultMachineFullPath;
}
// execute call ar imsInterfaces
com.itac.oib.boardgatekeeper.contracts.data.BoardRequestResult itacResult = _eventHandler.virtualInkspotBoardRequest(virtInkspotBoardRequest);
// itacResult ist null: call to imsInterface failed (imsInterfaces not available).
if (itacResult == null)
{
// setzen default Fehlertext
virtualInkspotHandlerBoardRequest.BoardRequestResult.Reason = "no results from iTAC.MES.Suite";
virtualInkspotHandlerBoardRequest.BoardRequestResult.RequestResult = "Rejected";
for (int i = 0; i < virtualInkspotHandlerBoardRequest.BoardRequestResult.VIHResult.SubPanelStates.Length; i++)
{
virtualInkspotHandlerBoardRequest.BoardRequestResult.VIHResult.SubPanelStates[i].Place = false;
virtualInkspotHandlerBoardRequest.BoardRequestResult.VIHResult.SubPanelStates[i].Reason = "no results from iTAC.MES.Suite";
}
}
else
{
// copy values from itac back to asm return struct
virtualInkspotHandlerBoardRequest.BoardRequestResult.RequestResult = itacResult.RequestResult;
virtualInkspotHandlerBoardRequest.BoardRequestResult.Reason = itacResult.Reason;
// virtualInkspotHandlerBoardRequest.BoardRequestResult.Reason = "no results from iTAC.MES.Suite"; // text info
// virtualInkspotHandlerBoardRequest.BoardRequestResult.RequestResult = "Rejected"; // result code
if (itacResult.VIHResult.SubPanelStates != null && itacResult.VIHResult.SubPanelStates.Length == virtualInkspotHandlerBoardRequest.BoardRequestResult.VIHResult.SubPanelStates.Length)
{
// copy all subpanelstates from itacs result to asm return value
for (int i = 0; i < itacResult.VIHResult.SubPanelStates.Length; i++)
{
virtualInkspotHandlerBoardRequest.BoardRequestResult.VIHResult.SubPanelStates[i].Place = itacResult.VIHResult.SubPanelStates[i].Place;
virtualInkspotHandlerBoardRequest.BoardRequestResult.VIHResult.SubPanelStates[i].Reason = itacResult.VIHResult.SubPanelStates[i].Reason;
}
}
}
}
catch (Exception e)
{
// The call failed exceptionally
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "calling BoardRequestResult in eventHandler failed", e);
for (int i = 0; i < virtualInkspotHandlerBoardRequest.BoardRequestResult.VIHResult.SubPanelStates.Length; i++)
{
virtualInkspotHandlerBoardRequest.BoardRequestResult.VIHResult.SubPanelStates[i].Place = false;
virtualInkspotHandlerBoardRequest.BoardRequestResult.VIHResult.SubPanelStates[i].Reason = e.Message;
}
}
}
// called by incoming xml files
public void virtualInkspotData(com.itac.oib.client.customextensions.VirtualInkspotHandlerBoardRequest requestData)
{
try
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "BoardGateKeeperReceiver.VirtualInkspotData from xml-file");
if (_eventHandler != null)
{
com.itac.oib.boardgatekeeper.contracts.data.BoardRequestResult itacResult = _eventHandler.virtualInkspotBoardRequest(requestData);
// TODO: Rückgabe noch auswerten ?
// requestData.setBoardRequestResult(itacResult);
return;
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Warning, "calling BoardGateKeeperReceiver.VirtualInkspotData not performed");
}
}
catch (Exception e)
{
// der letzte Aufruf schlug fehl!!
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "calling BoardRequestResult in eventHandler failed", e);
}
}
}
}

View File

@@ -0,0 +1,106 @@
#region Namespace
using System;
using System.Diagnostics;
using System.Threading;
using Asm.As.Oib.Client.CustomExtensions;
using com.itac.mes.proxy.business;
using com.itac.mes.tools;
using com.itac.oib.client.customextensions;
using Constants = com.itac.mes.tools.Constants;
#endregion
namespace Itac.Oib
{
/// <summary>
/// Receiver class for the Changeover manager events
/// </summary>
public class ChangeoverReceiver : IDisposable, IReceiver
{
#region Fields
public OIBEventHandler _eventHandler { get; set; }
private readonly ChangeoverManager _changeoverManager;
#endregion
#region Constructor
public ChangeoverReceiver(ChangeoverManager changeoverManager)
{
_changeoverManager = changeoverManager;
_changeoverManager.LineChangeover += new Asm.As.Oib.Client.CustomExtensions.LineChangeoverEvent(ChangeoverManagerLineChangeover);
}
#endregion
#region IDisposeable
public void Dispose()
{
if (_changeoverManager != null)
_changeoverManager.Dispose();
}
#endregion
#region Start/Stop
public void Start()
{
}
public void Stop()
{
}
#endregion
#region Handling of events
public class LineChangeoverThread : ThreadTemplate<Asm.As.Oib.Client.CustomExtensions.LineChangeoverEventArgs>
{
public LineChangeoverThread(OIBEventHandler eventHandler, Asm.As.Oib.Client.CustomExtensions.LineChangeoverEventArgs request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = LineChangeoverEventArgsMapper.get(_request);
getEventHandler().lineChangeoverEvent(mesNamespaceConformRequest);
}
}
public void ChangeoverManagerLineChangeover(object sender, Asm.As.Oib.Client.CustomExtensions.LineChangeoverEventArgs args)
{
try
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, string.Format("Changeover completed for line '{0}'", args.Line.Name));
// interessante Infos:
// String conveyorModeString = args.Line.StationInLines[0].StationConveyorSystem.ConveyorMode.ToString();
// com.itac.oib.client.customextensions.LineChangeoverEventArgs lineChangeoverEvent = LineChangeoverEventArgsMapper.get(args);
// if (lineChangeoverEvent == null)
// {
// LogHandler.log(Constants.LOGGER, TraceEventType.Error, "LineChangeover not converted");
// return;
// }
var mmt = new LineChangeoverThread(_eventHandler, args);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, string.Format("LineChangeover could not be pushed to java receiver"), e);
}
}
#endregion
internal com.itac.oib.client.customextensions.LineChangeoverEventArgs getCurrentLineProductionData()
{
com.itac.oib.client.customextensions.LineChangeoverEventArgs lineChangeoverEvent = LineChangeoverEventArgsMapper.get(_changeoverManager.GetCurrentLineProductionData());
if (lineChangeoverEvent == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "LineChangeover not converted");
return null;
}
return lineChangeoverEvent;
}
}
}

View File

@@ -0,0 +1,116 @@
#region Namespace
using System;
using System.Diagnostics;
using System.ServiceModel;
using Asm.As.Oib.Client;
using Asm.As.Oib.SiplaceSetupCenter.Contracts.Data;
using com.itac.mes.proxy.business;
using com.itac.mes.tools;
using Constants = com.itac.mes.tools.Constants;
#endregion
namespace Itac.Oib
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class DekPrinterExternalControlReceiver : IDisposable, IReceiver
{
#region Fields
private readonly OibDekPrinterExtenalControlEvents _oibDekPrinterExternalControlEvents;
public OIBEventHandler _eventHandler { get; set; }
#endregion
#region constructor, event delegate assignment
public DekPrinterExternalControlReceiver(OibDekPrinterExtenalControlEvents oibSetupCenterExternalControlEvents)
{
_oibDekPrinterExternalControlEvents = oibSetupCenterExternalControlEvents;
oibSetupCenterExternalControlEvents.VerifyPrinterMaterial = VerifyPrinterMaterial;
oibSetupCenterExternalControlEvents.VerifyPrinterTool = VerifyPrinterTool;
}
#endregion
#region Start/Stop
public void Start()
{
if (!_oibDekPrinterExternalControlEvents.IsStarted)
{
_oibDekPrinterExternalControlEvents.Start();
}
}
public void Stop()
{
_oibDekPrinterExternalControlEvents.Stop();
}
#endregion
public OIBEventHandler getEventHandler(Object request)
{
if (_eventHandler == null)
{
if (request == null) { throw new Exception("missing event handler to transport unknown message"); }
throw new Exception("missing event handler to transport message of type " + request.GetType().Name);
}
return _eventHandler;
}
#region IDekPrinterCenterExternalControl Members
private void startCall(string method)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, String.Format("DekPrinterExternalControl.{0} called", method));
}
public VerifyPrinterToolResponse VerifyPrinterTool(VerifyPrinterToolRequest request)
{
startCall("VerifyPrinterTool");
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.VerifyPrinterToolRequestMapper.get(request);
VerifyPrinterToolResponse oibResult = null;
try
{
var mesNamespaceConformResult = getEventHandler(request).verifyPrinterTool(mesNamespaceConformRequest);
oibResult = com.itac.oib.siplacesetupcenter.contracts.data.VerifyPrinterToolResponseMapper.get(mesNamespaceConformResult);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "failed to process VerifyPrinterToolRequest", e);
}
return oibResult;
}
public VerifyPrinterMaterialResponse VerifyPrinterMaterial(VerifyPrinterMaterialRequest request)
{
startCall("VerifyPrinterMaterial");
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.VerifyPrinterMaterialRequestMapper.get(request);
VerifyPrinterMaterialResponse oibResult = null;
try
{
var mesNamespaceConformResult = getEventHandler(request).verifyPrinterMaterial(mesNamespaceConformRequest);
oibResult = com.itac.oib.siplacesetupcenter.contracts.data.VerifyPrinterMaterialResponseMapper.get(mesNamespaceConformResult);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "failed to process VerifyPrinterMaterialRequest", e);
}
return oibResult;
}
#endregion
#region IDisposeable
public void Dispose()
{
if (_oibDekPrinterExternalControlEvents != null)
_oibDekPrinterExternalControlEvents.Dispose();
}
#endregion
}
}

View File

@@ -0,0 +1,113 @@
#region Namespace
using System;
using System.Diagnostics;
using System.Threading;
using Asm.As.Oib.Client.CustomExtensions;
using Asm.As.Oib.DisplayService.Contracts.Messages;
using Asm.As.Oib.DisplayService.Proxy.Architecture.Objects;
using com.itac.mes.proxy;
using com.itac.mes.proxy.business;
using com.itac.oib.client.customextensions;
#endregion
namespace Itac.Oib
{
/// <summary>
/// Receiver class for the Changeover manager events
/// </summary>
public class DisplayServiceReceiver : IDisposable, IReceiver
{
#region Fields
public OIBEventHandler _eventHandler { get; set; }
private readonly DisplayServiceClient _displayServiceClient;
#endregion
#region Constructor
public DisplayServiceReceiver(DisplayServiceClient displayServiceClient)
{
_displayServiceClient = displayServiceClient;
_displayServiceClient.ConfirmationReceived += confirmationReceived;
}
#endregion
#region IDisposeable
public void Dispose()
{
if (_displayServiceClient != null)
_displayServiceClient.Dispose();
}
#endregion
#region Start/Stop
public void Start()
{
}
public void Stop()
{
}
#endregion
#region Handling of events
private void confirmationReceived(ConfirmationReceivedRequest confirmationReceivedRequest)
{
throw new NotImplementedException();
}
/*public class LineChangeoverThread : ThreadTemplate<Asm.As.Oib.Client.CustomExtensions.LineChangeoverEventArgs>
{
public LineChangeoverThread(OIBEventHandler eventHandler, Asm.As.Oib.Client.CustomExtensions.LineChangeoverEventArgs request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = LineChangeoverEventArgsMapper.get(_request);
getEventHandler().lineChangeoverEvent(mesNamespaceConformRequest);
}
}
public void ChangeoverManagerLineChangeover(object sender, Asm.As.Oib.Client.CustomExtensions.LineChangeoverEventArgs args)
{
try
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, string.Format("Changeover completed for line '{0}'", args.Line.Name));
// interessante Infos:
// String conveyorModeString = args.Line.StationInLines[0].StationConveyorSystem.ConveyorMode.ToString();
// com.itac.oib.client.customextensions.LineChangeoverEventArgs lineChangeoverEvent = LineChangeoverEventArgsMapper.get(args);
// if (lineChangeoverEvent == null)
// {
// LogHandler.log(Constants.LOGGER, TraceEventType.Error, "LineChangeover not converted");
// return;
// }
var mmt = new LineChangeoverThread(_eventHandler, args);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, string.Format("LineChangeover could not be pushed to java receiver"), e);
}
}
internal com.itac.oib.client.customextensions.LineChangeoverEventArgs getCurrentLineProductionData()
{
com.itac.oib.client.customextensions.LineChangeoverEventArgs lineChangeoverEvent = LineChangeoverEventArgsMapper.get(_displayServiceClient.GetCurrentLineProductionData());
if (lineChangeoverEvent == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "LineChangeover not converted");
return null;
}
return lineChangeoverEvent;
}*/
#endregion
}
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Itac.Oib
{
public interface IReceiver
{
void Start();
void Stop();
}
}

View File

@@ -0,0 +1,187 @@
#region Namespace
using System;
using System.Diagnostics;
using com.itac.mes.proxy.business;
using com.itac.mes.tools;
using www.siplace.com.OIB._2015._10.LineControlServer.Contracts.Data;
using AsmNamespace = www.siplace.com.OIB._2015._10.LineControlServer.Contracts.Data;
using Constants = com.itac.mes.tools.Constants;
using MesNamespace = com.itac.oib.linecontrol.contracts.data;
using OibClient = Asm.As.Oib.Client;
#endregion
namespace Itac.Oib
{
/// <summary>
/// Receiver class for the TraceService events
/// </summary>
public class LineControlMesInterceptorReceiver : IDisposable, IReceiver
{
#region Fields
OIBEventHandler _eventHandler;
readonly OibClient.OibLineControlMesInterceptorEvents _oibLineControlMesInterceptorEvents;
#endregion
#region construtor/destructor
public LineControlMesInterceptorReceiver(OibClient.OibLineControlMesInterceptorEvents oibLineControlMesInterceptorEvents,
OIBEventHandler eventHandler)
{
if (oibLineControlMesInterceptorEvents == null) throw new ArgumentNullException("oibLineControlMesInterceptorEvents");
if (eventHandler == null) throw new ArgumentNullException("eventHandler");
this._oibLineControlMesInterceptorEvents = oibLineControlMesInterceptorEvents;
this._eventHandler = eventHandler;
_oibLineControlMesInterceptorEvents.Ping = Ping;
_oibLineControlMesInterceptorEvents.VerifyPcbForAutoProgramDownload = VerifyPcbForAutoProgramDownload;
_oibLineControlMesInterceptorEvents.VerifyRecipeActivationOnDekPrinter = VerifyRecipeActivationOnDekPrinter;
_oibLineControlMesInterceptorEvents.VerifyRecipeDownload = VerifyRecipeDownload;
_oibLineControlMesInterceptorEvents.VerifyRecipeForAutoProgramDownload = VerifyRecipeForAutoProgramDownload;
_oibLineControlMesInterceptorEvents.VerifyStartAutoProgramDownload = VerifyStartAutoProgramDownload;
}
public void Dispose()
{
if (_oibLineControlMesInterceptorEvents != null) { _oibLineControlMesInterceptorEvents.Dispose(); }
}
#endregion
#region Start/Stop
public void Start()
{
if (!_oibLineControlMesInterceptorEvents.IsStarted)
{
_oibLineControlMesInterceptorEvents.Start();
}
}
public void Stop()
{
_oibLineControlMesInterceptorEvents.Stop();
}
#endregion
#region Handling of events
bool Ping()
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "LineControlMesInterceptorReceiver.Ping");
return _eventHandler != null;
}
private MesVerificationResult VerifyRecipeForAutoProgramDownload(VerifyRecipeForAutoProgramDownloadRequest request)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "LineControlMesInterceptorReceiver VerifyRecipeForAutoProgramDownload called");
// map value from asm namespace to mes namespace
MesNamespace.VerifyRecipeForAutoProgramDownloadRequest report = MesNamespace.VerifyRecipeForAutoProgramDownloadRequestMapper.get(request);
// create return value
AsmNamespace.MesVerificationResult asmResult = null;
try
{
MesNamespace.MesVerificationResult mesResult = _eventHandler.verifyRecipeForAutoProgramDownload(report);
asmResult = MesNamespace.MesVerificationResultMapper.get(mesResult);
}
catch (Exception e)
{
asmResult = getFailureResult(e);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "failed to process LineControlMesInterceptorReceiver.VerifyRecipeForAutoProgramDownload", e);
}
return asmResult;
}
private MesVerificationResult VerifyStartAutoProgramDownload(VerifyRecipeForAutoProgramDownloadRequest request)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "LineControlMesInterceptorReceiver VerifyStartAutoProgramDownload called");
// map value from asm namespace to mes namespace
MesNamespace.VerifyRecipeForAutoProgramDownloadRequest report = MesNamespace.VerifyRecipeForAutoProgramDownloadRequestMapper.get(request);
AsmNamespace.MesVerificationResult asmResult = null;
try
{
MesNamespace.MesVerificationResult mesResult = _eventHandler.verifyStartAutoProgramDownload(report);
asmResult = MesNamespace.MesVerificationResultMapper.get(mesResult);
}
catch (Exception e)
{
asmResult = getFailureResult(e);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "failed to process LineControlMesInterceptorReceiver.VerifyStartAutoProgramDownload", e);
}
return asmResult;
}
private MesVerificationResult VerifyRecipeDownload(VerifyRecipeDownloadRequest request)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "LineControlMesInterceptorReceiver VerifyRecipeDownload called");
// map value from asm namespace to mes namespace
MesNamespace.VerifyRecipeDownloadRequest report = MesNamespace.VerifyRecipeDownloadRequestMapper.get(request);
AsmNamespace.MesVerificationResult asmResult = null;
try
{
MesNamespace.MesVerificationResult mesResult = _eventHandler.verifyRecipeDownload(report);
asmResult = MesNamespace.MesVerificationResultMapper.get(mesResult);
}
catch (Exception e)
{
asmResult = getFailureResult(e);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "failed to process LineControlMesInterceptorReceiver.VerifyRecipeDownload", e);
}
return asmResult;
}
private MesVerificationResult VerifyRecipeActivationOnDekPrinter(VerifyRecipeActivationOnDekPrinterRequest request)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "LineControlMesInterceptorReceiver VerifyRecipeActivationOnDekPrinterRequest called");
// map value from asm namespace to mes namespace
MesNamespace.VerifyRecipeActivationOnDekPrinterRequest report = MesNamespace.VerifyRecipeActivationOnDekPrinterRequestMapper.get(request);
AsmNamespace.MesVerificationResult asmResult = null;
try
{
MesNamespace.MesVerificationResult mesResult = _eventHandler.verifyRecipeActivationOnDekPrinter(report);
asmResult = MesNamespace.MesVerificationResultMapper.get(mesResult);
}
catch (Exception e)
{
asmResult = getFailureResult(e);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "failed to process LineControlMesInterceptorReceiver.VerifyRecipeActivationOnDekPrinterRequest", e);
}
return asmResult;
}
private MesVerificationResult VerifyPcbForAutoProgramDownload(VerifyPcbForAutoProgramDownloadRequest request)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "LineControlMesInterceptorReceiver VerifyPcbForAutoProgramDownloadRequest called");
// map value from asm namespace to mes namespace
MesNamespace.VerifyPcbForAutoProgramDownloadRequest report = MesNamespace.VerifyPcbForAutoProgramDownloadRequestMapper.get(request);
AsmNamespace.MesVerificationResult asmResult = null;
try
{
MesNamespace.MesVerificationResult mesResult = _eventHandler.verifyPcbForAutoProgramDownload(report);
asmResult = MesNamespace.MesVerificationResultMapper.get(mesResult);
}
catch (Exception e)
{
asmResult = getFailureResult(e);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "failed to process LineControlMesInterceptorReceiver.VerifyPcbForAutoProgramDownloadRequest", e);
}
return asmResult;
}
private AsmNamespace.MesVerificationResult getFailureResult(Exception e)
{
MesVerificationResult result = new MesVerificationResult();
result.VerificationResult = 2; // 0=OK, 1=Rejected, 2=Error
result.Reason = e.Message;
return result;
}
#endregion
}
}

View File

@@ -0,0 +1,220 @@
#region Namespace
using System;
using System.Diagnostics;
using System.Threading;
using com.itac.mes.proxy;
using com.itac.mes.proxy.business;
using Constants = com.itac.mes.tools.Constants;
using OibMonBizObj = Asm.As.Oib.Monitoring.Proxy.Business.EventArgs;
using OibClient = Asm.As.Oib.Client;
using System.Configuration;
using com.itac.oib.monitoring.contracts.data;
using Asm.As.Oib.Monitoring.Proxy.Business.Objects;
using com.itac.mes.tools;
#endregion
namespace Itac.Oib
{
public class MonitoringReceiver : IDisposable, IReceiver
{
#region Fields
public OIBEventHandler _eventHandler { get; set; }
private readonly String _lineFullPath;
private readonly OibClient.OibMonitoringEvents _oibMonitoringEvents;
private TimeSpan boardProcessedMaxAge = new TimeSpan(0, 0, 0);
private TimeSpan stationEventMaxAge = new TimeSpan(0, 0, 0);
#endregion
#region Constructor
public MonitoringReceiver(OibClient.OibMonitoringEvents oibMonitoringEvents, string lineFullPath)
{
_oibMonitoringEvents = oibMonitoringEvents;
_lineFullPath = lineFullPath;
oibMonitoringEvents.BoardProcessed += BoardProcessedEventReceived;
oibMonitoringEvents.StationEvent += StationEventReceived;
try
{
String sMaxAge = (String)new AppSettingsReader().GetValue("BoardProcessedDataMaxAge", typeof(String));
boardProcessedMaxAge = TimeSpan.Parse(sMaxAge);
}
catch (FormatException)
{
// default Wert 1 Stunde
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "configured Value for 'BoardProcessedDataMaxAge' is invalid, use default value");
boardProcessedMaxAge = new TimeSpan(24, 0, 0);
}
catch (Exception)
{
boardProcessedMaxAge = new TimeSpan(0, 0, 0);
}
if (boardProcessedMaxAge.Ticks > 0)
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "maximum age for BoardProcessedMessages = " + boardProcessedMaxAge.ToString());
else
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "no maximum age for BoardProcessedMessages");
try
{
String sMaxAge = (String)new AppSettingsReader().GetValue("StationEventMaxAge", typeof(String));
stationEventMaxAge = TimeSpan.Parse(sMaxAge);
}
catch (FormatException)
{
// default Wert 1 Stunde
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "configured Value for 'StationEventMaxAge' is invalid, use default value");
stationEventMaxAge = new TimeSpan(24, 0, 0);
}
catch (Exception)
{
stationEventMaxAge = new TimeSpan(0, 0, 0);
}
if (stationEventMaxAge.Ticks > 0)
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "maximum age for StationEventMaxAge = " + stationEventMaxAge.ToString());
else
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "no maximum age for StationEventMaxAge");
}
#endregion
#region Start/Stopp
public void Start()
{
_oibMonitoringEvents.Start();
}
public void Stop()
{
_oibMonitoringEvents.Stop();
}
#endregion
#region Handling of events
#region Board Processed
public void BoardProcessedEventReceived(object sender, OibMonBizObj.BoardProcessedEventArgs args)
{
try
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "BoardProcessedEventArgs");
if (boardProcessedMaxAge.Ticks > 0)
{
Boolean skip = false;
DateTime oldestDate = new DateTime(DateTime.Now.Ticks - boardProcessedMaxAge.Ticks).ToUniversalTime();
foreach (Asm.As.Oib.Monitoring.Proxy.Business.Objects.ProcessedBoard processedBoard in args.BoardProcessedData.ProcessedBoards)
{
if (processedBoard.StationTime != null && processedBoard.StationTime.ToUniversalTime().Ticks < oldestDate.Ticks)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "found old BoardProcessedEvent from " + processedBoard.StationTime.ToUniversalTime().ToString() +
", oldest message to be processed is " + oldestDate.ToString());
skip = true;
}
}
if (skip)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ignore BoardProcessedEvent because one of its " +
"stationEvents is older than configured time " + boardProcessedMaxAge.ToString());
return;
}
}
var mmt = new BoardProcessedThread(_eventHandler, args.BoardProcessedData);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "BoardProcessedEventArgs failed", e);
}
}
private class BoardProcessedThread : ThreadTemplate<Asm.As.Oib.Monitoring.Proxy.Business.Objects.BoardProcessedData>
{
public BoardProcessedThread(OIBEventHandler eventHandler, Asm.As.Oib.Monitoring.Proxy.Business.Objects.BoardProcessedData request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.monitoring.contracts.data.BoardProcessedDataMapper.get(_request);
getEventHandler().boardProcessedEventReceived(mesNamespaceConformRequest);
}
}
#endregion
#region Station Event
public void StationEventReceived(object sender, OibMonBizObj.StationEventArgs args)
{
if (args == null || args.StationEventComposite == null) { return; }
try
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "StationEventReceived");
// should check event time
if (stationEventMaxAge.TotalSeconds > 0)
{
DateTime oldestDate = new DateTime(DateTime.UtcNow.Ticks - stationEventMaxAge.Ticks);
if (DateTime .Compare( args.StationEventComposite.StationTime, oldestDate) <0)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "ignore StationEvent because its time '" +
args.StationEventComposite.StationTime.ToUniversalTime() + "' is older than configured time " + stationEventMaxAge.ToString());
return;
}
}
var mmt = new StationEventThread(_eventHandler, args.StationEventComposite);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "StationEventArgs failed", e);
}
}
public class StationEventThread : ThreadTemplate<Asm.As.Oib.Monitoring.Proxy.Business.Objects.StationEventComposite>
{
public StationEventThread(OIBEventHandler eventHandler, Asm.As.Oib.Monitoring.Proxy.Business.Objects.StationEventComposite request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.monitoring.contracts.data.StationEventCompositeMapper.get(_request);
getEventHandler().stationEventReceived(mesNamespaceConformRequest);
}
}
#endregion
void MonitoringSubscriptionHealthStatus(object sender, OibClient.OibServiceStatusEventArgs e)
{
try
{
if (!e.SubscriptionCheckResult.Succeeded)
LogHandler.log(Constants.LOGGER, TraceEventType.Error, string.Format("OIB Monitoring Queue for line '{0}' cound not be checked.", _lineFullPath));
else
LogHandler.log(Constants.LOGGER, TraceEventType.Information, string.Format("OIB Monitoring Queue for line '{0}' is in state '{1}' containing '{2}' messages.", _lineFullPath, e.SubscriptionCheckResult.QueueStatus, e.SubscriptionCheckResult.MessagesInQueue));
}
catch (Exception ex)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, string.Format("OIB Monitoring Queue for line '{0}' checked failed: '{1}'.", _lineFullPath, ex.Message));
}
}
#endregion
#region IDisposeable
public void Dispose()
{
if (_oibMonitoringEvents != null)
_oibMonitoringEvents.Dispose();
}
#endregion
}
}

View File

@@ -0,0 +1,33 @@
using System;
using com.itac.mes.proxy.business;
namespace Itac.Oib
{
public class ThreadTemplate<T>
{
protected readonly OIBEventHandler _eventHandler;
protected readonly T _request;
public ThreadTemplate(OIBEventHandler eventHandler, T request)
{
_eventHandler = eventHandler;
_request = request;
}
/// <summary>
/// get the event handler. By calling a funcion at the eventHandler the object is serialized and transported to java receiver.
/// </summary>
/// <returns>The event handler instance</returns>
/// <exception>An exception is thrown when the handler was not set to this instance of thread template</exception>
public OIBEventHandler getEventHandler()
{
if (_eventHandler == null)
{
if (_request == null) { throw new Exception("missing event handler to transport unknown message"); }
throw new Exception("missing event handler to transport message of type " + _request.GetType().Name);
}
return _eventHandler;
}
}
}

View File

@@ -0,0 +1,236 @@
#region Namespace
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.ServiceModel;
using Asm.As.Oib.SiplaceSetupCenter.Contracts.Data;
using com.itac.mes.proxy.business;
using com.itac.mes.tools;
using Constants = com.itac.mes.tools.Constants;
using OibClient = Asm.As.Oib.Client;
#endregion
namespace Itac.Oib
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class SetupCenterExternalControlReceiver : IDisposable, IReceiver
{
#region Fields
private readonly OibClient.OibSetupCenterExternalControlEvents _oibSetupCenterExternalControlEvents;
public OIBEventHandler _eventHandler { get; set; }
#endregion
#region Constructor
public SetupCenterExternalControlReceiver(OibClient.OibSetupCenterExternalControlEvents oibSetupCenterExternalControlEvents)
{
_oibSetupCenterExternalControlEvents = oibSetupCenterExternalControlEvents;
oibSetupCenterExternalControlEvents.GetNewPackagingUnitData = GetNewPackagingUnitData;
oibSetupCenterExternalControlEvents.GetPackagingUnitControlStatus = GetPackagingUnitControlStatus;
}
#endregion
#region Start/Stop
public void Start()
{
if (!_oibSetupCenterExternalControlEvents.IsStarted)
{
_oibSetupCenterExternalControlEvents.Start();
}
}
public void Stop()
{
_oibSetupCenterExternalControlEvents.Stop();
}
#endregion
#region ISiplaceSetupCenterExternalControl Members
public ExternalControlResult[] GetPackagingUnitControlStatus(PackagingUnitLocation[] packagingUnitLocations)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "ExternalControl GetPackagingUnitControlStatus called");
com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitLocation[] report = com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitLocationMapper.getArray(packagingUnitLocations);
Asm.As.Oib.SiplaceSetupCenter.Contracts.Data.ExternalControlResult[] oibResult = null;
try
{
com.itac.oib.siplacesetupcenter.contracts.data.ExternalControlResult[] itacResult = _eventHandler.getPackagingUnitControlStatus(report);
oibResult = com.itac.oib.siplacesetupcenter.contracts.data.ExternalControlResultMapper.get(itacResult);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "failed to process GetPackagingUnitControlStatus", e);
}
asmHandler(ref packagingUnitLocations, ref oibResult);
return oibResult;
}
public void UpdateEmptyFields(List<PackagingUnitLocation> packagingUnitLocations, List<ExternalControlResult> result)
{
if (packagingUnitLocations == null || packagingUnitLocations.Count == 0)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "SetupCenterExternalControl.updateEmptyFields: packagingUnitLocations empty or null");
return;
}
if (result == null || result.Count == 0)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "SetupCenterExternalControl.updateEmptyFields: result empty or null");
return;
}
if (packagingUnitLocations.Count != result.Count)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "SetupCenterExternalControl.updateEmptyFields: packagingUnitLocations and result different size");
return;
}
// über alle Items iterieren
for (int i = 0; i < packagingUnitLocations.Count; i++)
{
UpdateEmptyFields(packagingUnitLocations[i], result[i]);
}
}
public void UpdateEmptyFields(PackagingUnitLocation packagingUnitLocation, ExternalControlResult result)
{
if (packagingUnitLocation == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "SetupCenterExternalControl.updateEmptyFields: packagingUnitLocation is null");
return;
}
if (result == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "SetupCenterExternalControl.updateEmptyFields: result is null");
return;
}
// per reflection über alle Felder iterieren, dabei per Name vorgehen
// deepCopy(packagingUnitLocation, result);
// Console.WriteLine("");
if (packagingUnitLocation.PackagingUnit.BatchPackagingUnit != null && result.PackagingUnit.BatchPackagingUnit == null)
{
result.PackagingUnit.BatchPackagingUnit = packagingUnitLocation.PackagingUnit.BatchPackagingUnit;
}
}
// muss noch weiter getestet werden...
public void DeepCopy(object sourceObject, object destObject)
{
Type sourceType = sourceObject.GetType();
Type destType = destObject.GetType();
MemberInfo[] sourceMbrInfoArray = sourceType.GetMembers();
MemberInfo[] destMbrInfoArray = destType.GetMembers();
foreach (MemberInfo sourceMbrInfo in sourceMbrInfoArray)
{
if (sourceMbrInfo.MemberType == MemberTypes.Property)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "" + sourceMbrInfo + " is a " + sourceMbrInfo.MemberType);
// alle einfachen TypeNameConverter direkt prüfen (int, String, bool)
// komplexe Typen ???
PropertyInfo sourcePropInfo = sourceType.GetProperty(sourceMbrInfo.Name);
// gibt es das Property auch im Zielobjekt
foreach (MemberInfo destMbrInfo in destMbrInfoArray)
{
// identischer Name, identischerr Typ
if (destMbrInfo.MemberType == sourceMbrInfo.MemberType && destMbrInfo.Name == sourceMbrInfo.Name)
{
PropertyInfo destPropInfo = destType.GetProperty(destMbrInfo.Name);
object sourceValue = sourcePropInfo.GetValue(sourceObject, null);
object destValue = destPropInfo.GetValue(destObject, null);
if (sourcePropInfo.PropertyType == typeof(String) || sourcePropInfo.PropertyType == typeof(int)
|| sourcePropInfo.PropertyType == typeof(Int32) || sourcePropInfo.PropertyType == typeof(Int64)
|| sourcePropInfo.PropertyType == typeof(long) || sourcePropInfo.PropertyType == typeof(bool)
|| sourcePropInfo.PropertyType == typeof(Boolean))
{
if (sourceValue != destValue)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "primitive type copy value");
destPropInfo.SetValue(destObject, sourceValue, null);
}
}
else if (!sourceType.IsArray)
{
// komplexer Typ, kein Array
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, sourceMbrInfo.Name + " is complex type ");
if (sourceValue != null)
{
DeepCopy(sourceValue, destValue);
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, sourceMbrInfo.Name + " is complex type, sourceValue is null");
}
}
}
}
}
}
}
private void asmHandler(ref Asm.As.Oib.SiplaceSetupCenter.Contracts.Data.PackagingUnitLocation[] packagingUnitLocations,
ref Asm.As.Oib.SiplaceSetupCenter.Contracts.Data.ExternalControlResult[] result)
{
//
// special ASM Handling:
// simply return MSD Level and MSD Open Date as received in request
foreach (Asm.As.Oib.SiplaceSetupCenter.Contracts.Data.PackagingUnitLocation item in packagingUnitLocations)
{
// find this container in result and copy the values
foreach (Asm.As.Oib.SiplaceSetupCenter.Contracts.Data.ExternalControlResult resultItem in result)
{
if (item.PackagingUnit.UID.Equals(resultItem.PackagingUnit.UID))
{
resultItem.PackagingUnit.MsdLevel = item.PackagingUnit.MsdLevel;
resultItem.PackagingUnit.MsdOpenDate = item.PackagingUnit.MsdOpenDate;
}
}
}
}
public ExternalControlResult[] GetNewPackagingUnitData(PackagingUnitLocation[] packagingUnitLocations)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "SetupCenterExternalControl.GetPackagingUnitControlStatus");
try
{
// List<ExternalControlResult> result = _eventHandler.GetPackagingUnitControlStatus(packagingUnitLocations);
// hier müssen eigentliche alle Felder aus den quelldaten, die nicht in den Zieldaten enthalten sind per
// Reflection übernommen werden, damit wir nie mehr irgend welche Werte verlieren
// UpdateEmptyFields(packagingUnitLocations, result);
// return result;
}
catch (Exception)
{
_eventHandler = null;
// Fehler, keine weitere info vorhanden, da die Applikation nicht läuft
}
return new ExternalControlResult[0];
}
#endregion
#region IDisposeable
public void Dispose()
{
if (_oibSetupCenterExternalControlEvents != null)
_oibSetupCenterExternalControlEvents.Dispose();
}
#endregion
}
}

View File

@@ -0,0 +1,516 @@
#region Namespace
using System;
using System.Diagnostics;
using System.Threading;
using Asm.As.Oib.SiplaceSetupCenter.Contracts.Data;
using com.itac.mes.proxy.business;
using com.itac.mes.tools;
using Constants = com.itac.mes.tools.Constants;
using OibClient = Asm.As.Oib.Client;
#endregion
namespace Itac.Oib
{
public class SetupCenterReceiver : IDisposable, IReceiver
{
#region Fields
public OIBEventHandler _eventHandler { get; set; }
private readonly String _lineFullPath;
private readonly OibClient.OibSetupCenterEvents _oibSetupCenterEvents;
private bool _isSetupStation;
#endregion
#region Constructor
public SetupCenterReceiver(OibClient.OibSetupCenterEvents oibSetupCenterEvents, string lineFullPath, bool isSetupStation)
{
_oibSetupCenterEvents = oibSetupCenterEvents;
_lineFullPath = lineFullPath;
_isSetupStation = isSetupStation;
oibSetupCenterEvents.FeederPlaced += SetupCenterFeederPlaced;
oibSetupCenterEvents.FeederRemoved += SetupCenterFeederRemoved;
oibSetupCenterEvents.NewSetupActive += SetupCenterNewSetupActive;
oibSetupCenterEvents.PackagingQuantityChanged += SetupCenterPackagingQuantityChanged;
oibSetupCenterEvents.SetupChanged += SetupCenterSetupChanged;
oibSetupCenterEvents.PackagingUnitConsumed += SetupCenterPackagingUnitConsumed;
oibSetupCenterEvents.MaterialMoved += SetupCenterMaterialMoved;
oibSetupCenterEvents.PrinterToolVerified += SetupCenterPrinterToolVerified;
oibSetupCenterEvents.PrinterToolUnverified += SetupCenterPrinterToolUnVerified;
oibSetupCenterEvents.PrinterCapabilitiesChanged += SetupCenterPrinterCapabilitiesChanged;
oibSetupCenterEvents.PrinterConsumablesUpdated += SetupCenterPrinterConsumablesChanged;
oibSetupCenterEvents.PrinterCoverClosed += SetupCenterPrintercoverClosed;
oibSetupCenterEvents.PrinterCoverOpened += SetupCenterPrinterCoverOpened;
oibSetupCenterEvents.PrinterMaterialUnverified += SetupCenterPrinterMaterialUnverified;
oibSetupCenterEvents.PrinterMaterialVerified += SetupCenterPrinterMaterialVerified;
oibSetupCenterEvents.PrinterRecipeVerified += SetupCenterPrinterRecipeVerified;
}
#endregion
#region Start/Stop
public void Start()
{
if (!_oibSetupCenterEvents.IsStarted)
{
_oibSetupCenterEvents.Start();
}
}
public void Stop()
{
_oibSetupCenterEvents.Stop();
}
#endregion
#region Handling of events
private void startSetupcenterEvent(Object args)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, String.Format("SetupCenterReceiver.{0}", args.GetType().Name));
}
private void setupcenterEventFailed(Object args, Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, String.Format("calling SetupCenterNotifyReceiver.{0} failed", args.GetType().Name), e);
}
void SetupCenterPackagingQuantityChanged(object sender, OibClient.PackagingQuantityChangedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PackagingQuantityChangedThread(_eventHandler, args.PackagingQuantityChangedReport);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
void SetupCenterFeederPlaced(object sender, OibClient.FeederPlacedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new FeederPlacedThread(_eventHandler, args.FeederPlacedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
void SetupCenterFeederRemoved(object sender, OibClient.FeederRemovedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new FeederRemovedThread(_eventHandler, args.FeederRemovedReport);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
void SetupCenterNewSetupActive(object sender, OibClient.NewSetupActiveEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new NewSetupActiveThread(_eventHandler, args.NewSetupActiveReport);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
void SetupCenterSetupChanged(object sender, OibClient.SetupChangedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new SetupChangedThread(_eventHandler, args.SetupChangedReport);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
void SetupCenterPackagingUnitConsumed(object sender, OibClient.PackagingUnitConsumedEventArgs args)
{
if (_isSetupStation)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "ignore PackagingUnitConsumed because in SetupStation mode");
return;
}
startSetupcenterEvent(args);
try
{
var mmt = new PackagingUnitConsumedThread(_eventHandler, args.PackagingUnitConsumedReport);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
public void SetupCenterMaterialMoved(object sender, OibClient.MaterialMovedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new MaterialMovedThread(_eventHandler, args.MaterialMovedReport);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
#region PrinterFunctions Receiver
public void SetupCenterPrinterToolVerified(object sender, OibClient.PrinterToolVerifiedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PrinterToolVerifiedThread(_eventHandler, args.PrinterToolVerifiedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
public void SetupCenterPrinterRecipeVerified(object sender, OibClient.PrinterRecipeVerifiedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PrinterRecipeVerifiedThread(_eventHandler, args.PrinterRecipeVerifiedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
public void SetupCenterPrinterMaterialVerified(object sender, OibClient.PrinterMaterialVerifiedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PrinterMaterialVerifiedThread(_eventHandler, args.PrinterMaterialVerifiedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
public void SetupCenterPrinterMaterialUnverified(object sender, OibClient.PrinterMaterialUnverifiedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PrinterMaterialUnverifiedThread(_eventHandler, args.PrinterMaterialUnverifiedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
public void SetupCenterPrinterCoverOpened(object sender, OibClient.PrinterCoverOpenedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PrinterCoverOpenedThread(_eventHandler, args.PrinterCoverOpenedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
public void SetupCenterPrintercoverClosed(object sender, OibClient.PrinterCoverClosedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PrinterCoverClosedThread(_eventHandler, args.PrinterCoverClosedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
public void SetupCenterPrinterConsumablesChanged(object sender, OibClient.PrinterConsumablesUpdatedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PrinterConsumablesChangedThread(_eventHandler, args.PrinterConsumablesUpdatedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
public void SetupCenterPrinterCapabilitiesChanged(object sender, OibClient.PrinterCapabilitiesChangedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PrinterCapabilitiesChangedThread(_eventHandler, args.PrinterCapabilitiesChangedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
public void SetupCenterPrinterToolUnVerified(object sender, OibClient.PrinterToolUnverifiedEventArgs args)
{
startSetupcenterEvent(args);
try
{
var mmt = new PrinterToolUnVerifiedThread(_eventHandler, args.PrinterToolUnverifiedReportRequest);
var thread = new Thread(mmt.ThreadFunction);
thread.Start();
}
catch (Exception e)
{
setupcenterEventFailed(args, e);
}
}
#endregion
// Calls delegieren an die eigentliche Implementierung
public class FeederPlacedThread : ThreadTemplate<FeederPlacedReport>
{
public FeederPlacedThread(OIBEventHandler eventHandler, FeederPlacedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.FeederPlacedReportMapper.get(_request);
getEventHandler().feederPlaced(mesNamespaceConformRequest);
}
}
public class FeederRemovedThread : ThreadTemplate<FeederRemovedReport>
{
public FeederRemovedThread(OIBEventHandler eventHandler, FeederRemovedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.FeederRemovedReportMapper.get(_request);
getEventHandler().feederRemoved(mesNamespaceConformRequest);
}
}
public class NewSetupActiveThread : ThreadTemplate<NewSetupActiveReport>
{
public NewSetupActiveThread(OIBEventHandler eventHandler, NewSetupActiveReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.NewSetupActiveReportMapper.get(_request);
getEventHandler().newSetupActive(mesNamespaceConformRequest);
}
}
public class PackagingQuantityChangedThread : ThreadTemplate<PackagingQuantityChangedReport>
{
public PackagingQuantityChangedThread(OIBEventHandler eventHandler, PackagingQuantityChangedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PackagingQuantityChangedReportMapper.get(_request);
getEventHandler().packagingQuantityChanged(mesNamespaceConformRequest);
}
}
public class SetupChangedThread : ThreadTemplate<SetupChangedReport>
{
public SetupChangedThread(OIBEventHandler eventHandler, SetupChangedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.SetupChangedReportMapper.get(_request);
getEventHandler().setupChanged(mesNamespaceConformRequest);
}
}
public class PackagingUnitConsumedThread : ThreadTemplate<PackagingUnitConsumedReport>
{
public PackagingUnitConsumedThread(OIBEventHandler eventHandler, PackagingUnitConsumedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitConsumedReportMapper.get(_request);
getEventHandler().packagingUnitConsumed(mesNamespaceConformRequest);
}
}
// Calls delegieren an die eigentliche Implementierung
public class MaterialMovedThread : ThreadTemplate<MaterialMovedReport>
{
public MaterialMovedThread(OIBEventHandler eventHandler, MaterialMovedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.MaterialMovedReportMapper.get(_request);
getEventHandler().materialMoved(mesNamespaceConformRequest);
}
}
public class PrinterToolVerifiedThread : ThreadTemplate<PrinterToolVerifiedReport>
{
public PrinterToolVerifiedThread(OIBEventHandler eventHandler, PrinterToolVerifiedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PrinterToolVerifiedReportMapper.get(_request);
getEventHandler().printerToolVerified(mesNamespaceConformRequest);
}
}
public class PrinterMaterialVerifiedThread : ThreadTemplate<PrinterMaterialVerifiedReport>
{
public PrinterMaterialVerifiedThread(OIBEventHandler eventHandler, PrinterMaterialVerifiedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PrinterMaterialVerifiedReportMapper.get(_request);
getEventHandler().printerMaterialVerified(mesNamespaceConformRequest);
}
}
public class PrinterMaterialUnverifiedThread : ThreadTemplate<PrinterMaterialUnverifiedReport>
{
public PrinterMaterialUnverifiedThread(OIBEventHandler eventHandler, PrinterMaterialUnverifiedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PrinterMaterialUnverifiedReportMapper.get(_request);
getEventHandler().printerMaterialUnverified(mesNamespaceConformRequest);
}
}
public class PrinterCoverOpenedThread : ThreadTemplate<PrinterCoverOpenedReport>
{
public PrinterCoverOpenedThread(OIBEventHandler eventHandler, PrinterCoverOpenedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PrinterCoverOpenedReportMapper.get(_request);
getEventHandler().printerCoverOpened(mesNamespaceConformRequest);
}
}
public class PrinterCoverClosedThread : ThreadTemplate<PrinterCoverClosedReport>
{
public PrinterCoverClosedThread(OIBEventHandler eventHandler, PrinterCoverClosedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PrinterCoverClosedReportMapper.get(_request);
getEventHandler().printerCoverClosed(mesNamespaceConformRequest);
}
}
public class PrinterConsumablesChangedThread : ThreadTemplate<PrinterConsumablesUpdatedReport>
{
public PrinterConsumablesChangedThread(OIBEventHandler eventHandler, PrinterConsumablesUpdatedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PrinterConsumablesUpdatedReportMapper.get(_request);
getEventHandler().printerConsumablesUpdated(mesNamespaceConformRequest);
}
}
public class PrinterCapabilitiesChangedThread : ThreadTemplate<PrinterCapabilitiesChangedReport>
{
public PrinterCapabilitiesChangedThread(OIBEventHandler eventHandler, PrinterCapabilitiesChangedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PrinterCapabilitiesChangedReportMapper.get(_request);
getEventHandler().printerCapabilitiesChanged(mesNamespaceConformRequest);
}
}
public class PrinterToolUnVerifiedThread : ThreadTemplate<PrinterToolUnverifiedReport>
{
public PrinterToolUnVerifiedThread(OIBEventHandler eventHandler, PrinterToolUnverifiedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PrinterToolUnverifiedReportMapper.get(_request);
getEventHandler().printerToolUnverified(mesNamespaceConformRequest);
}
}
public class PrinterRecipeVerifiedThread : ThreadTemplate<PrinterRecipeVerifiedReport>
{
public PrinterRecipeVerifiedThread(OIBEventHandler eventHandler, PrinterRecipeVerifiedReport request) : base(eventHandler, request) { }
public void ThreadFunction()
{
var mesNamespaceConformRequest = com.itac.oib.siplacesetupcenter.contracts.data.PrinterRecipeVerifiedReportMapper.get(_request);
getEventHandler().printerRecipeVerified(mesNamespaceConformRequest);
}
}
#endregion
#region IDisposeable
public void Dispose()
{
if (_oibSetupCenterEvents != null)
_oibSetupCenterEvents.Dispose();
}
#endregion
}
}

View File

@@ -0,0 +1,89 @@
#region Namespace
using System;
using System.Diagnostics;
using com.itac.mes.proxy.business;
using com.itac.mes.tools;
using com.itac.oib.linecontrol.data;
using Constants = com.itac.mes.tools.Constants;
using OibClient = Asm.As.Oib.Client;
#endregion
namespace Itac.Oib
{
public class SpiReceiver : IDisposable, IReceiver
{
#region Fields
private readonly OIBEventHandler _eventHandler;
private readonly OibClient.OibSpiEvents _oibSpiEvents;
#endregion
#region Constructor
public SpiReceiver(OibClient.OibSpiEvents oibSpiEvents, OIBEventHandler eventHandler)
{
_eventHandler = eventHandler;
_oibSpiEvents = oibSpiEvents;
oibSpiEvents.RecipeSecifiedForStation += OibSpiEventsRecipeSecifiedForStation;
}
#endregion
#region Start/Stopp
public void Start()
{
_oibSpiEvents.StartDownloadEvents();
}
public void Stop()
{
_oibSpiEvents.StopDownloadEvents();
}
#endregion
#region Handling of events
public void OibSpiEventsRecipeSecifiedForStation(object sender, OibClient.RecipeSecifiedForStationEventArgs args)
{
try
{
var downloadData = new DownloadData();
downloadData.strServiceComputer = "";
downloadData.downloadTime = args.DownloadTime;
downloadData.lineName = args.ProductionScheduleElement.Recipe.Setup.Line.FullPath;
downloadData.stationName = args.StationIdentity.FullPath;
downloadData.conveyorLanes = args.IsRightLane ? "Right" : "Left";
downloadData.jobName = args.ProductionScheduleElement.OrderID;
downloadData.recipeName = args.ProductionScheduleElement.Recipe.FullPath;
downloadData.productionScheduleName = args.ProductionScheduleDisplayName;
downloadData.productionScheduleElementId = args.ProductionScheduleElement.ID;
downloadData.placementInfo = com.itac.oib.siplacepro.service.SiplacePro.GetPlacementForRecipe(args.ProductionScheduleElement.Recipe);
_eventHandler.downloadEvent(downloadData);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "download Event received");
}
catch (Exception ex)
{
Trace.WriteLine("Error processing SPI property changed event: " + ex.Message);
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "Error processing SPI property changed event: ", ex);
}
}
#endregion
#region IDisposeable
public void Dispose()
{
if (_oibSpiEvents != null)
_oibSpiEvents.Dispose();
}
#endregion
}
}

View File

@@ -0,0 +1,128 @@
#region Namespace
using System;
using System.Diagnostics;
using Asm.As.Oib.Client.CustomExtensions;
using com.itac.mes.tools;
using Constants = com.itac.mes.tools.Constants;
using com.itac.mes.proxy.business;
using com.itac.oib.traceability.contracts.data;
using OibClient = Asm.As.Oib.Client;
using SiplaceNS = www.siplace.com.OIB._2012._03.Traceability.Contracts.Data;
#endregion
namespace Itac.Oib
{
/// <summary>
/// Receiver class for the TraceService events
/// </summary>
public class TraceabilityReceiver : IDisposable, IReceiver
{
#region Fields
OIBEventHandler _eventHandler;
readonly OibClient.OibTraceabilityEvents _oibTraceabilityEvents;
readonly OperatorNotificationManager _operatorNotificationManager;
#endregion
#region Constructor
public TraceabilityReceiver(OibClient.OibTraceabilityEvents oibTraceEvents, OIBEventHandler eventHandler, OperatorNotificationManager operatorNotificationManager)
{
if (oibTraceEvents == null) throw new ArgumentNullException("oibTraceEvents");
if (eventHandler == null) throw new ArgumentNullException("eventHandler");
if (operatorNotificationManager == null) throw new ArgumentNullException("operatorNotificationManager");
_oibTraceabilityEvents = oibTraceEvents;
_eventHandler = eventHandler;
_operatorNotificationManager = operatorNotificationManager;
oibTraceEvents.TraceabilityData = TraceDataReceived;
}
#endregion
#region Start/Stop
public void Start()
{
_oibTraceabilityEvents.Start();
}
public void Stop()
{
_oibTraceabilityEvents.Stop();
}
#endregion
#region Handling of events
public SiplaceNS.BoardProducedResponse TraceDataReceived(SiplaceNS.TraceabilityData traceabilityData)
{
SiplaceNS.BoardProducedResponse response = new SiplaceNS.BoardProducedResponse();
try
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "ITraceabilityOibService.NewTraceabilityData");
if (_eventHandler != null)
{
TraceabilityData itacTraceData = TraceabilityDataMapper.get(traceabilityData);
BoardProducedResponse result = _eventHandler.boardProduced(itacTraceData);
if (result.BoardValidationResult == 2)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "received the RC_TRCDATA_REJECTED return code");
try
{
_operatorNotificationManager.TraceDataRejected("Die letzte Station wurde gestoppt, da iTac die Tracedaten als fehlerhaft erkannt hat.");
}
catch (Exception ex)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "calling OperatorNotificationManager failed", ex);
}
}
else if (result.BoardValidationReason.StartsWith("RC_TRCDATA_REJECTED:"))
{
string message = result.BoardValidationReason.Replace("RC_TRCDATA_REJECTED:", "");
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "received the RC_TRCDATA_REJECTED return code with additional l message text " + message);
try
{
_operatorNotificationManager.TraceDataRejected(message);
}
catch (Exception ex)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "calling OperatorNotificationManager failed", ex);
}
}
response.BoardValidationResult = 2;
return response;
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Warning, "calling ITraceabilityOibService.NewTraceabilityData not performed");
}
}
catch (Exception e)
{
// der letzte Aufruf schlug fehl!!
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "calling NewTraceabilityData in eventHandler failed", e);
}
response.BoardValidationResult = 1;
return response;
}
#endregion
#region IDisposeable
public void Dispose()
{
if (_oibTraceabilityEvents != null)
_oibTraceabilityEvents.Dispose();
}
#endregion
}
}

View File

@@ -0,0 +1,37 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("iTAC.OIB.Adapter OIB ${asm.oib.version}: MES=${mes.suite.version} INTF=${mes.interface.version}/${timestamp}")]
[assembly: AssemblyDescription("iTAC.OIB.Adapter OIB ${asm.oib.version}: MES=${mes.suite.version} INTF=${mes.interface.version}/${timestamp}")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("iTAC Software AG")]
[assembly: AssemblyProduct("iTAC.OIB.Adapter")]
[assembly: AssemblyCopyright("Copyright © 2018 iTAC Software AG")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("cf1ddacb-ccbc-464c-a946-23b526e766ca")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("5.1.0.*")]
[assembly: AssemblyFileVersion("5.1.0.0")]

View File

@@ -0,0 +1,274 @@
Version 1.1.0.8
---------------
Import and export of messages as xml file
Version 1.1.0.9
---------------
importing invalid xml file; avoid iTAC.OIB.Adapter crash
Version 1.2.0.0
---------------
Configuration changed
filtering for line names implemented
support for PreSetupStation added
Version 1.2.0.1
---------------
Avoid crash if OIB core is down for maintainance. automatically re-establish connection
logging improved
Version 1.2.0.2
---------------
exception handling in setupCenterNotifyReceiver optimized.
field test version
Version 1.2.0.3
---------------
xml file writing for PackagingUnitLocation and ExternalControlResult, Configuration change necessary.
<!-- the following two are for synchronous call on scanning packaging units -->
<add key="PackagingUnitLocation" value="true"/>
<add key="ExternalControlResult" value="true"/>
Version 1.3.0.0
---------------
new libs for OIB 2.5 and SC 4.2
more Exception handling, general exception handler for uncaught exceptions
new function GetNewPackagingUnit (SC requests a packaging unit from MES)
PackagingUnitConsumedReport contains additional information about locations and remaining packaging units
Version 1.3.0.1
---------------
Adapter can read DownloadData from xml file and send it to Client
added consumedComponents information in TraceabilityData
Version 1.3.0.2
---------------
always create new input and output streams to java connector (requires java equivalent)
Version 1.3.0.3
---------------
A few more Packaging Unit fields: brightness class, ..
Version 1.3.0.4
---------------
Missing monitoring endpoint does not kill process
Version 1.3.0.5
---------------
Assembly Version still remains 1.3.0.4 from now to prevent oib configuration change
additionally startup information about FileVersion, which is now 1.3.0.5
compatible with Data Interface Version 6.10.02.374
Version 1.3.0.6
---------------
New Communication structure, DataInterface tells iTAC.OIB.Adapter on startup a remote port
Every data set opens a new connection
line control receiver configured only with port (changed adapter-configuration)
compatible with Data Interface Version 6.10.02.384
Version 1.3.0.7
---------------
catch Exception on logging(was not thread safe)
printing lineControl and setupCenter endpoints on startup
Version 1.3.0.8
---------------
LineName trim()
Events from Monitoring Queue and SetupCenter Queue sent by a thread and return immediately, preventing timeouts
Version 1.3.0.9
---------------
Exception inserting values in Hashmap fixed
possibly NullPointer prevented on MaterialMovedEvent
Version 1.3.0.10
---------------
return own address as IPv4 instead of undefined
config file modified timeout-times (now 2 minutes)
Version 1.3.0.11
---------------
Capability of reading PackagingUnitConsumedReport from file (internal feature)
Capability of reading MaterialMovedReport from file (internal feature)
management of connections to DataInterface now thread safe
Version 1.3.0.12
---------------
logging events NewSetupActive and SetupChangedReport (20120424)
config changed; new setting for NewSetupActive logging (20120424)
requesting DataInterface connection synchronized (20120425)
Version 1.3.0.13
---------------
changed log level for XML-Message-Logging from INFO to DEBUG (20120523)
changed time stamp format in logging, 3 digits for fractions of seconds (20120523)
logging configuration changed, adjustable log level for console logger (20120523)
new Parameter for Logging Xml into Console(20120523)
XML-Serialization performance improved (20120523)
Version 1.3.0.14
----------------
Capability of reading StationEventcomposite from file (internal feature 20120525)
Logging StationEventComposite corrected (20123105)
// from here we have two version for OIB 2.5 and 3.0
Version 2.5.0.15 / Version 3.0.0.15
-----------------------------------
internal structural changes
Version 2.5.0.16 / Version 3.0.0.16
-----------------------------------
preparing data structure (ComponentLocation) corrected (missing location info).
SiplacePro logging modified.
Version 2.5.0.17 / Version 3.0.0.17
-----------------------------------
skips all older BoardProcessedData messages, requires new Configuration value (20120815)
<!-- maximum age for boardProcessedMessages to be processed, in 'hours:minutes:seconds' -->
<add key="BoardProcessedDataMaxAge" value="00:30:00"/>
Version 3.0.1.18
-----------------------------------
new mechanism for line changeover eventBased Mode (20121017)
skips all older Stationevents messages, optional new Configuration value (20121017)
<!-- maximum age for StationEventMessages to be processed, in 'hours:minutes:seconds' -->
<add key="StationEventMaxAge" value="00:30:00"/>
ignored if value is not configured or invalid
Version 3.0.1.19
-----------------------------------
correction in SetupCenterReceiver (20121023)
Version 3.0.1.20
-----------------------------------
check receive time in MonitoringReceiver with UTC time (StationEvent and BoardProcessed) (20121106)
Version 3.0.1.21
-----------------------------------
use stationFullPath instead of stationTypeFullPath in downloadEvent (20121127)
// latest version usable with OIB 3.0.1.x
// from here minimum required OIB Version is 3.1.0.101
Version 3.1.0.22
-----------------------------------
Initial support of OIB 3.1; OIB Client 3.0.x is no longer supported by this Adapter. (20130307)
Version 3.1.0.23
-----------------------------------
Adapter starts even if DisplayService is not available, but in this case without Traceability function. (20130821)
Version 3.1.0.24
-----------------------------------
new ASM DLL V2.1.0.1 including BoardGateKeeper (20130919)
TraceReceiver will not be created/started if configured port is 0
Display Service Receiver will not be started if configured port is 0
Version 3.1.0.25
-----------------------------------
new ASM DLL V2.1.0.2 including modified BoardGateKeeper (20131011)
Adapter starts even if DisplayService is not available/reachable (20131011)
BoardGateKeeper will not be started if configured port is 0
sligthly changed format of xml output (bool values lower case, different date format)
Version 3.1.0.26
-----------------------------------
new ASM DLL V2.1.0.3 including modified BoardGateKeeper (20131018)
sligthly changed format of xml output (bool values lower case, different date format)
read xml files for VirtualInkspotData
Version 3.1.0.26
-----------------------------------
new ASM DLL V2.1.0.11 Virtual Inkspot Handling tested (20131025)
new configuration values "OnVIHDataRejected.ShowMessage" and "OnVIHDataRejected.StationStop" (20131025)
Version 3.1.0.27
-----------------------------------
new ASM DLL V2.1.0.14 implemented (20131120)
provide a new placementRecipeName to the line, new function startPlacementRecipe (20131022)
Version 3.1.0.28
-----------------------------------
deny board when communication break whilst VirtualInkspotRequest is active(20131204)
accept BoardProcessedData messages as xml files (20131206)
Version 3.1.0.29
-----------------------------------
get ASM OIB Product Versions (20131217)
Version 3.1.0.30
-----------------------------------
new ASM DLL V2.1.0.16 (20140113)
// from here:
// minimum required OIB Version 3.2.0.135
Version 3.2.0.31
-----------------------------------
new ASM DLL V2.2.0.1 (20140114)
use ASM OIB V3.2 (20140114)
Version 3.2.0.32
-----------------------------------
use recipeFullPath in LineChangeOverEvents instead of recipeName (20140120)
correct namespace for startJobResult (20140124)
setupCenterQueue subscription corrected (find correct stations of line) (20140120)
Version 3.2.0.33
-----------------------------------
logging on connection breakdown (20140827)
new ASM DLL V2.2.1.4 (20140909)
use ASM OIB V3.2 HF3 (3.2.0.152) (20140909)
Version 3.2.0.34
-----------------------------------
new ASM DLL V2.2.1.6, DLL backward compatible with older adapter versions (20141021)
provide additional info to displayService on rejected Tracebilitydata (20141021)
Version 3.2.0.35
-----------------------------------
ignore download events from any except the configured line (20141118)
Version 3.2.0.36
-----------------------------------
skip StationEventComposite messages without stateTransitions (20150706)
Version 3.2.0.37
-----------------------------------
accept Component to be null even if designator is set in BoardData/improved logging (20150909)
Version 3.2.0.38
-----------------------------------
new internal API Version (AsmApi.dll) / ASM Release 80 (20151209)
Version 3.2.0.39
-----------------------------------
return timestamp values as UTC (like 2016-10-07T12:33:05.0000000Z instead of 2016-10-07T12:33:05.0000000) (20162110)
Version 3.2.0.40
-----------------------------------
new asm client lib 2.3.0.1 (20170215)
Version 3.2.0.41
-----------------------------------
new asm client lib 2.3.0.2
new optional config parameter to configure inkspot fiducial handling
added all optional parameters to configuration file (20170706)
use date 01.01.0001 for any date from iTAC <= 01.01.1970 in PackagingUnitControl (20180201)
Version 3.2.0.42
-----------------------------------
new asm client lib 2.3.0.3 (20180809)
Umstellung auf OIB 5.3.0.60
--Version 5x

View File

@@ -0,0 +1,169 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<appSettings>
<!-- The name or the IP address of the OIB Core Host -->
<add key="OIBCoreHostName" value="192.168.5.51" />
<!-- this iTAC.OIB.Adapter should work for this line. -->
<!-- the line Name is appended to the endpoint urls to distinguish the endpoints in oib -->
<!--add key="LineName" value="Line1\Line1sync"/>
<add key="LineName" value="Line4\Line 4.2"/-->
<add key="LineName" value="Line1\Line1sync"/>
<add key ="isSetupStation" value="false"/>
<!-- set to true for iTAC failure analysis only -->
<add key ="offlineMode" value="false"/>
<!-- The listen port is the port the adapter will listen for Java connections -->
<add key="ListenPort" value="33020"/>
<!-- every iTAC.OIB.Adapter endpoint has a separate URL and port. together with the service name results a uniqe URL -->
<!-- the endpoint-url may contain special characters!!! -->
<!-- e.g. http://OibAdapterPc:33334/Itac.Oib.SetupCenterExternalControl/Line1 -->
<add key="SiplaceProEventPort" value="9500"/>
<add key="DisplayServiceEventPort" value="9600"/>
<!-- default port 9600 -->
<add key="SetupCenterNotifyPort" value="33333"/>
<add key="SetupCenterExternalControlPort" value="33334"/>
<add key="TraceServicePort" value="33335"/>
<add key="MonitoringReceiverPort" value="33336"/>
<add key="LineControlReceiverPort" value="33338"/>
<add key="BoardGateKeeperEventPort" value="33339"/>
<add key="DekPrinterExternalControlPort" value="33337"/>
<add key="LinecontrolMesInterceptorPort" value="33332"/>
<add key="ConfigurationManagerCallbackPort" value="33340"/>
<!-- define wether messages should be logged or not. -->
<add key="xmlExport" value="true"/>
<add key="xmlLogging" value="true"/>
<!-- define, which messages should be logged -->
<add key="TraceabilityData" value="true"/>
<add key="DownloadData" value="false"/>
<add key="StationEventComposite" value="false"/>
<add key="MaterialMovedReport" value="true"/>
<add key="SetupChangedReport" value="false"/>
<add key="FeederPlacedReport" value="false"/>
<add key="TablePlacedReport" value="false"/>
<add key="TableRemovedReport" value="false"/>
<add key="BoardProcessedData" value="false"/>
<add key="CheckInData" value="true"/>
<add key="FeederRemovedReport" value="false"/>
<add key="PackagingUnitConsumedReport" value="true"/>
<add key="PackagingUnitCreatedReport" value="false"/>
<add key="LockStateChangedReport" value="false"/>
<add key="LineChangeoverEvent" value="true"/>
<!-- the following two are for synchronous call on scanning packaging units -->
<add key="PackagingUnitLocation" value="true"/>
<add key="ExternalControlResult" value="true"/>
<add key="BoardRequestData" value="true"/>
<!-- maximum age for boardProcessedMessages to be processed, in 'hours:minutes:seconds' -->
<add key="BoardProcessedDataMaxAge" value="00:30:00"/>
<add key="StationEventMaxAge" value="02:05:00"/>
<!-- This setting allows to stop the line if the trace data is rejected by iTac MES Suite -->
<!-- In this case the input conveyor of the last station is stopped -->
<add key="Asm.As.Oib.Client.Extensions.StopLineOnTraceDataRejected" value="true"/>
<add key="Asm.As.Oib.Client.Extensions.OnVIHDataRejected.ShowMessage" value="true"/>
<add key="Asm.As.Oib.Client.Extensions.OnVIHDataRejected.StationStop" value="true"/>
<!-- timing values for event based mode -->
<add key="Asm.As.Oib.Client.Extensions.ChangeoverIncompleteWarningSeconds" value="120"/>
<add key="Asm.As.Oib.Client.Extensions.ChangeoverIncompleteRepeatWarningSeconds" value="120"/>
<!-- from 2.3.0.2: Virtual Inkspot handling definition
True: VirtualInkspotHandler will only request iTAC if a BarcodeFiducial is configured for the board in SiplacePro. ("Customer-Case")
False: VirtualInkspotHandler will request iTAC always.
Default: true -->
<add key="Asm.As.Oib.Client.Extensions.VirtualInkspotHandlerConsidersBarcodeFiducial" value="true"/>
<!--These are values a user can override if neccessary (for info see MSDN for binding parameters), if not provided the defaults are used-->
<!-- <add key="Siemens.Siplace.OIB.SiplacePro.Proxies.ReliableChannel.MaxNumberOfRetryAttempts" value="1" />-->
<!-- <add key="Siemens.Siplace.OIB.SiplacePro.Proxies.ReliableChannel.RetryFrequency" value="2000" />-->
<!-- This is the interval in ms when the proxy checks the connection to the Service,-->
<!-- it must be greater or equal to 1000ms; if this is not present, a default value of 1 minute is used -->
<!-- <add key="Siemens.Siplace.OIB.SiplacePro.Proxies.ReliableChannel.CheckAliveFrequency" value="60000" />-->
</appSettings>
<log4net>
<appender name="LogFileAppenderFull" type="log4net.Appender.RollingFileAppender">
<file value=".\Log\itac.oib.proxy.full.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<header value="" />
<footer value="" />
<conversionPattern value="%date{dd.MM.yyyy HH:mm:ss,f} %8.10c %-5p %m%n" />
</layout>
</appender>
<appender name="LogFileAppenderError" type="log4net.Appender.RollingFileAppender">
<file value=".\Log\itac.oib.proxy.error.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="3" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="WARN" />
<levelMax value="FATAL" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<header value="" />
<footer value="" />
<conversionPattern value="%date{dd.MM.yyyy HH:mm:ss,f} %8.10c %-5p %m%n" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ColoredConsoleAppender" >
<mapping>
<level value="ERROR" />
<backColor value="White" />
<foreColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="INFO" />
<foreColor value="Yellow" />
<backColor value="White" />
</mapping>
<mapping>
<level value="DEBUG" />
<foreColor value="Blue" />
<backColor value="White" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<header value="[Header]\r\n" />
<footer value="[Footer]\r\n" />
<conversionPattern value="%date{dd.MM.yyyy HH:mm:ss,f} %8.10c %-5p %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="DEBUG" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppenderFull" />
<appender-ref ref="LogFileAppenderError" />
<appender-ref ref="ConsoleAppender" />
</root>
<!-- Print only messages of level or above from ASM -->
<logger name="ASM-OIB">
<level value="WARN" />
</logger>
</log4net>
</configuration>

View File

@@ -0,0 +1,20 @@
using com.itac.oib;
using com.itac.oib.boardgatekeeper.service;
using com.itac.oib.displayservice.service;
using com.itac.oib.linecontrol.service;
using com.itac.oib.monitoring.service;
using com.itac.oib.siplacesetupcenter.service;
using com.itac.oib.traceability.service;
namespace com.itac.mes.domain
{
/// <summary>
/// Defines all events, that will sent from siplace machine
/// </summary>
public interface OIBEvents : ISiplaceSetupCenterNotify, ITraceability, ISetupCenterExternalControl, IMonitoringReceiver, IDisplayServiceCallback, ILineControlReceiver, IAdapterNotify, IChangeoverManager, IBoardGateKeeper, IDekPrinterExternalControl, ILineControlMesInterceptor
{
}
}

View File

@@ -0,0 +1,14 @@
using com.itac.oib;
using com.itac.oib.displayservice.service;
using com.itac.oib.linecontrol.service;
using com.itac.oib.siplacepro.service;
using com.itac.oib.siplacesetupcenter.service;
namespace com.itac.mes.domain
{
public interface OIBService : ISiplaceSetupCenter, IAdapterControl, ILineControl, ISiplacePro, IDisplayService
{
}
}

View File

@@ -0,0 +1,705 @@
#region Namespace
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Asm.As.Oib.Client;
using Asm.As.Oib.SiplacePro.Proxy.Architecture.Objects;
using com.itac.mes.domain;
using com.itac.mes.tools;
using com.itac.oib;
using com.itac.oib.displayservice.contracts.data;
using com.itac.oib.linecontrol.contracts.data;
using com.itac.oib.siplacepro.contracts.data;
using com.itac.oib.siplacepro.service;
using com.itac.oib.siplacesetupcenter.contracts.data;
using com.itac.oib.traceability.contracts.data;
using Itac.Oib;
using Constants = com.itac.mes.tools.Constants;
using LcTypes = Asm.As.Oib.SiplacePro.LineControl.Contracts;
using OibSpiTyp = Asm.As.Oib.SiplacePro.Proxy.Types;
#endregion
namespace com.itac.mes.proxy.business
{
public class OIBServiceImpl : OIBService, IDisposable
{
#region Fields
private IAdapterControl _adapterControl;
private readonly MessageWriter _messageWriter;
public ChangeoverReceiver ChangeoverReceiver { get; set; }
#endregion
public OIBServiceImpl(IAdapterControl adapterControl, MessageWriter messageWriter)
{
_adapterControl = adapterControl;
_messageWriter = messageWriter;
}
public OibSetupCenterAccess OibSetupCenterAccess { get; set; }
public OibLineControlAccess OibLineControlAccess { get; set; }
public SiplacePro SiplacePro { set; get; }
public OibDisplayServiceAccess DisplayServiceAccess { get; set; }
public string configuredLineFullPath { get; set; }
public string firstMachineInLine { get; set; }
public string lastMachineInLine { get; set; }
public void Shutdown()
{
}
internal void SetAdapterControl(IAdapterControl adapterControl)
{
_adapterControl = adapterControl;
}
#region ISiplaceSetupCenter Member
public void set(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitLocation[] packagingUnitLocations)
{
try
{
OibSetupCenterAccess.Set(PackagingUnitLocationMapper.get(packagingUnitLocations));
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Class OIBServiceImpl, Call ISiplaceSetupCenter.Set failed: ", e);
}
}
public void refill(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitLocation[] packagingUnitLocations)
{
try
{
OibSetupCenterAccess.Refill(PackagingUnitLocationMapper.get(packagingUnitLocations));
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Class OIBServiceImpl, Call ISiplaceSetupCenter.Refill failed: ", e);
}
}
public void tearDown(string strSetup, com.itac.oib.siplacesetupcenter.contracts.data.ComponentLocation[] componentLocations)
{
try
{
OibSetupCenterAccess.TearDown(strSetup, ComponentLocationMapper.get(componentLocations));
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Class OIBServiceImpl, Call ISiplaceSetupCenter.TearDown failed: ", e);
}
}
public com.itac.oib.siplacesetupcenter.contracts.data.MachineSetup getReducedActualSetup(string machineId)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SetupCenter.GetReducedActualSetup(machineId=" + machineId + ")");
try
{
Asm.As.Oib.SiplaceSetupCenter.Contracts.Data.MachineSetup oibMachineSetup = OibSetupCenterAccess.GetReducedActualSetup(machineId);
if (oibMachineSetup == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to SetupCenter.GetReducedActualSetup returned null");
return null;
}
MachineSetup machineSetup = MachineSetupMapper.get(oibMachineSetup);
Evaluate(machineSetup);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to SetupCenter.GetReducedActualSetup returned");
return machineSetup;
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to SetupCenter.GetReducedActualSetup failed", e);
return null;
}
}
public PackagingUnitResult[] update(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnit[] packagingUnits)
{
try
{
return PackagingUnitResultMapper.getArray(OibSetupCenterAccess.Get(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitMapper.get(packagingUnits)));
}
catch (Exception) { return null; }
}
public PackagingUnitResult[] get(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnit[] packagingUnits)
{
try
{
return PackagingUnitResultMapper.getArray(OibSetupCenterAccess.Get(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitMapper.get(packagingUnits)));
}
catch (Exception) { return null; }
}
public com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitResult[] create(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnit[] packagingUnits)
{
try { return PackagingUnitResultMapper.getArray(OibSetupCenterAccess.Get(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitMapper.get(packagingUnits))); }
catch (Exception) { return null; }
}
public PackagingUnitResult[] delete(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnit[] packagingUnits)
{
return PackagingUnitResultMapper.getArray(OibSetupCenterAccess.Get(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitMapper.get(packagingUnits)));
}
public void activate(ComponentLocation[] componentLocations)
{
try
{
OibSetupCenterAccess.Activate(ComponentLocationMapper.get(componentLocations));
}
catch (Exception) { }
}
public void deactivate(com.itac.oib.siplacesetupcenter.contracts.data.ComponentLocation[] componentLocations, string reason)
{
try
{
OibSetupCenterAccess.Deactivate(ComponentLocationMapper.get(componentLocations), reason);
}
catch (Exception) { }
}
public void lockUids(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnit[] puIDs, string reason)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SetupCenter.Lock(reason=" + reason + ")");
try
{
OibSetupCenterAccess.Lock(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitMapper.get(puIDs), reason);
Evaluate(puIDs);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to SetupCenter.Lock returned");
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to SetupCenter.Lock failed", e);
}
}
public void unlockUids(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnit[] puIDs)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SetupCenter.Unlock");
try
{
OibSetupCenterAccess.Unlock(com.itac.oib.siplacesetupcenter.contracts.data.PackagingUnitMapper.get(puIDs));
Evaluate(puIDs);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to SetupCenter.Unlock returned");
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to SetupCenter.Unlock failed", e);
}
}
public Configuration getConfiguration()
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SetupCenter.GetConfiguration");
try
{
var configuration = ConfigurationMapper.get(OibSetupCenterAccess.GetConfiguration());
Evaluate(configuration);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to SetupCenter.GetConfiguration returned");
return configuration;
}
catch
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to SetupCenter.GetConfiguration failed");
return null;
}
}
public bool isConnected()
{
try
{
return OibSetupCenterAccess.IsConnected();
}
catch { return false; }
}
public void setMessageLevel(int messageLevel)
{
try
{
OibSetupCenterAccess.SetMessageLevel(messageLevel);
}
catch { }
}
public string getDatabaseName()
{
try
{
return OibSetupCenterAccess.GetDatabaseName();
}
catch { return null; }
}
#endregion
#region ILineControl Member
public string getDatabaseId()
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.getDatabaseId");
try
{
String result = OibLineControlAccess.LineControlSession.DatabaseId;
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to LineControl.getDatabaseId returned " + result);
return result;
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.getDatabaseId failed, return false ", e);
return null;
}
}
public string getAdapterTimeZone()
{
try
{
return OibLineControlAccess.LineControlSession.GetAdapterTimeZone();
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.getAdapterTimeZone failed, return empty string ", e);
return "";
}
}
/// <summary>
/// full path required (including folders)
/// </summary>
/// <param name="lineName"></param>
/// <returns></returns>
public bool stopLine(string lineName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.StopLine(" + lineName + ")");
try
{
bool b = OibLineControlAccess.LineControlSession.StopLine(lineName);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to LineControl.StopLine returned " + b);
return b;
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.StopLine failed, return false ", e);
return false;
}
}
public bool stopLineConveyor(string lineName, int nLanes)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.StopLineConveyor(" + lineName + "," + nLanes + ")");
try
{
var oibLanes = (LcTypes.ConveyorLanes)Enum.ToObject(typeof(LcTypes.ConveyorLanes), nLanes);
bool b = OibLineControlAccess.LineControlSession.StopLineConveyor(lineName, oibLanes);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to LineControl.StopLineConveyor returned " + b);
return b;
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.StopLineConveyor failed, return false", e);
return false;
}
}
public bool continueLine(string lineName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.ContinueLine(" + lineName + ")");
try
{
bool b = OibLineControlAccess.LineControlSession.ContinueLine(lineName);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to LineControl.ContinueLine returned " + b);
return b;
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.ContinueLine failed, return false", e);
return false;
}
}
public bool continueLineConveyor(string lineName, int nLanes)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.ContinueLineConveyor(" + lineName + "," + nLanes + ")");
try
{
var oibLanes = (LcTypes.ConveyorLanes)Enum.ToObject(typeof(LcTypes.ConveyorLanes), nLanes);
bool b = OibLineControlAccess.LineControlSession.ContinueLineConveyor(lineName, oibLanes);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to LineControl.ContinueLineConveyor returned " + b);
return b;
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.ContinueLineConveyor failed, return false", e);
return false;
}
}
public bool blockStationInputConveyor(string station, bool bLock, string strBlockingApplicationName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.BlockStationInputConveyor(" + station + "," + bLock + ", " + strBlockingApplicationName + ")");
try
{
bool b = OibLineControlAccess.LineControlSession.BlockStationInputConveyor(station, bLock, strBlockingApplicationName);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to LineControl.BlockStationInputConveyor returned " + b);
return b;
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.BlockStationInputConveyor failed, return false", e);
return false;
}
}
public bool unBlockStationInputConveyor(string station, string strUnblockingApplicationName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.UnBlockStationInputConveyor(" + station + ", " + strUnblockingApplicationName + ")");
try
{
bool b = OibLineControlAccess.LineControlSession.UnBlockStationInputConveyor(station, strUnblockingApplicationName);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to LineControl.UnBlockStationInputConveyor returned " + b);
return b;
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.UnBlockStationInputConveyor failed, return false", e);
return false;
}
}
public string getActiveProductionSchedule(string lineName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.GetActiveProductionSchedule(" + lineName + ")");
String result = null;
try
{
result = OibLineControlAccess.LineControlSession.GetActiveProductionSchedule(lineName);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to LineControl.GetActiveProductionSchedule(" + lineName + ") returned " + result);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.GetActiveProductionSchedule failed", e);
}
return result;
}
public LineControlLineStatus getLineStatus(string lineName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.GetLineStatus(" + lineName + ")");
LineControlLineStatus result = null;
try
{
result = LineControlLineStatusMapper.get(OibLineControlAccess.LineControlSession.GetLineStatus(lineName));
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to LineControl.GetLineStatus(" + lineName + ") returned ");
Evaluate(result);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, ".NET call to LineControl.GetLineStatus failed", e);
}
return result;
}
public StartJobResult startPlacementRecipe(string productionSchedule, string jobName, int conveyor)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to LineControl.startPlacementRecipe(schedule=" + productionSchedule + ", job=" + jobName + ", conveyor=" + conveyor + ")");
StartJobResult startJobResult = new StartJobResult();
try
{
// evtl. ist productionSchedule leer, dann den aktuellen Schedule der Linie nehmen
LcTypes.ConveyorLanes lcLane = (LcTypes.ConveyorLanes)conveyor;
// Get the SIPLACE Pro session for the SPI adapter on the local host
Session session = SiplacePro.oibSpiAccess.Session;
// Get the line the production schedule will be for.
Object line = session.GetObject(configuredLineFullPath, OibSpiTyp.ObjectServerType.Line);
if (line == null)
{
startJobResult.errorText = string.Format("Line '{0}' does not exist in SIPLACE Pro.", configuredLineFullPath);
startJobResult.result = false;
return startJobResult;
}
if (productionSchedule.Equals("") || productionSchedule.Equals("*"))
{
// automatic resolving of current production schedule
productionSchedule = OibLineControlAccess.LineControlSession.GetActiveProductionSchedule(configuredLineFullPath);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "automatic resolved ProductionSchedule is " + productionSchedule);
}
Asm.As.Oib.SiplacePro.Proxy.Business.Objects.ProductionSchedule prodSched = session.GetObject(productionSchedule, OibSpiTyp.ObjectServerType.ProductionSchedule) as Asm.As.Oib.SiplacePro.Proxy.Business.Objects.ProductionSchedule;
if (prodSched == null)
{
startJobResult.errorText = string.Format("ProductionSchedule '{0}' not found in SIPLACE Pro.", productionSchedule);
startJobResult.result = false;
return startJobResult;
}
bool found = false;
Asm.As.Oib.SiplacePro.Proxy.Business.Objects.ProductionScheduleElement productionScheduleElement = null;
foreach (Asm.As.Oib.SiplacePro.Proxy.Business.Objects.ProductionScheduleElement prodSchedElem in prodSched.ProductionScheduleElements.Values)
{
if (prodSchedElem.Recipe.Name.Equals(jobName) || prodSchedElem.Recipe.FullPath.Equals(jobName))
{
found = true;
productionScheduleElement = prodSchedElem;
break;
}
}
if (!found)
{
startJobResult.errorText = string.Format("Job {0} not found in ProductionSchedule '{1}'.", jobName, productionSchedule);
startJobResult.result = false;
return startJobResult;
}
Asm.As.Oib.SiplacePro.LineControl.Contracts.Data.DownloadResult result = OibLineControlAccess.LineControlSession.DownloadIC(
prodSched.FullPath, //Name of the production schedule
prodSched.ProductionScheduleElements.IndexOf(productionScheduleElement), //Zero based index of the ProductionScheduleElement
"", // ProductionScheduleElement ID, if this is empty, Index will be used
lcLane,//
LcTypes.IntegrityCheckMode.AllowHeadstepRecalcuation,
LcTypes.IntegrityCheckModeForRepartitioning.AvoidRepartitioning,
LcTypes.DownloadProcessingOptions.AutoWidthAdjust | LcTypes.DownloadProcessingOptions.OverwriteFeederSettings)
as Asm.As.Oib.SiplacePro.LineControl.Contracts.Data.DownloadResult;
startJobResult.result = result.Succeeded;
startJobResult.errorText = result.DetailedResults.ToString();
}
catch (Exception e)
{
startJobResult.errorText = e.Message;
startJobResult.result = false;
return startJobResult;
}
Evaluate(startJobResult);
return startJobResult;
}
#endregion
#region IAdapterControl Member
public void startSetupCenterNotifyReceiver()
{
if (_adapterControl != null) { _adapterControl.startSetupCenterNotifyReceiver(); }
}
public void stopSetupCenterNotifyReceiver()
{
if (_adapterControl != null) { _adapterControl.stopSetupCenterNotifyReceiver(); }
}
public void startMonitoringReceiver()
{
_adapterControl.startMonitoringReceiver();
}
public void stopMonitoringReceiver()
{
_adapterControl.stopMonitoringReceiver();
}
public bool ping()
{
return _adapterControl.ping();
}
public bool isSetupStation()
{
return _adapterControl.isSetupStation();
}
public void setInterfaceHost(int port, string ipAddress, string canonicalHostName, string hostName)
{
_adapterControl.setInterfaceHost(port, ipAddress, canonicalHostName, hostName);
}
public void setChannelName(string channelName)
{
_adapterControl.setChannelName(channelName);
}
public void startTraceReceiver()
{
_adapterControl.startTraceReceiver();
}
public void stopTraceReceiver()
{
_adapterControl.stopTraceReceiver();
}
public void startBoardGateKeeper()
{
_adapterControl.startBoardGateKeeper();
}
public void stopBoardGateKeeper()
{
_adapterControl.stopBoardGateKeeper();
}
public void startDekReceiver()
{
_adapterControl.startDekReceiver();
}
public void stopDekReceiver()
{
_adapterControl.stopDekReceiver();
}
#endregion
#region ISiplacePro Member
public BoardCheckInRequest completeCheckinData(BoardCheckInRequest checkinData)
{
return SiplacePro.completeCheckinData(checkinData);
}
public BoardElement[] getPlacementForBoard(String boardFullName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SiplacePro.getPlacementForBoard(" + boardFullName + ")");
BoardElement[] placeInfo = null;
try
{
placeInfo = SiplacePro.getPlacementForBoard(boardFullName);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call to SiplacePro.getPlacementForBoard(" + boardFullName + ") returned ");
Evaluate(placeInfo);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "java call to SiplacePro.getPlacementForBoard failed", e);
}
return placeInfo;
}
// beim starten des interface ermittelt sich das Interface darueber einmalig den Status und die Rüstng der Linie, und
// kann damit die Rüstung neu aufbauen
oib.client.customextensions.LineChangeoverEventArgs ISiplacePro.getCurrentLineProductionData()
{
if (ChangeoverReceiver == null) { return null; }
return ChangeoverReceiver.getCurrentLineProductionData();
}
#endregion
#region Logging Utils
private void Evaluate(Object arg)
{
if (_messageWriter != null)
{
_messageWriter.output(arg);
}
}
#endregion
#region IDisposable
public void Dispose()
{
if (OibLineControlAccess != null)
OibLineControlAccess.Dispose();
if (OibSetupCenterAccess != null)
OibSetupCenterAccess.Dispose();
if (OibLineControlAccess != null)
OibLineControlAccess.Dispose();
if (OibLineControlAccess != null)
OibLineControlAccess.Dispose();
}
#endregion
public void sendMessageByLinePathAllStations(string linePath, string messageText, string extendedDescription, AcknowledgementType acknowledgementType,
bool callbackRequest, SeverityLevel severityLevel)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SendMessageByLinePathAllStations");
// wenn default-Wert (*) dann den konfigurierten Wert für die Linie benutzen
if (linePath == null || linePath.Length == 0 || linePath.Equals("*"))
{
linePath = configuredLineFullPath;
}
try
{
Asm.As.Oib.DisplayService.Proxy.Architecture.Objects.DisplayServiceClient displaySession = DisplayServiceAccess.DisplayServiceSession;
Asm.As.Oib.DisplayService.Contracts.Data.Types.AcknowledgementType ackType = AcknowledgementTypeMapper.get(acknowledgementType);
Asm.As.Oib.DisplayService.Contracts.Data.Types.SeverityLevel severity = SeverityLevelMapper.get(severityLevel);
Asm.As.Oib.DisplayService.Contracts.Messages.SendMessageResponse sendMessageResponse = displaySession.
SendMessageByLinePathAllStations(linePath, messageText, extendedDescription, ackType, callbackRequest, 0, severity, null, null);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SendMessageByStationPath finished");
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "java call to SendMessageByStationPath finished", e);
}
}
public void sendMessageByLinePathFirstStation(string linePath, string messageText, string extendedDescription, AcknowledgementType acknowledgementType,
bool callbackRequest, SeverityLevel severityLevel)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SendMessageByLinePathFirstStation");
if (linePath.Equals("*"))
{
linePath = configuredLineFullPath;
}
try
{
Asm.As.Oib.DisplayService.Proxy.Architecture.Objects.DisplayServiceClient displaySession = DisplayServiceAccess.DisplayServiceSession;
Asm.As.Oib.DisplayService.Contracts.Data.Types.AcknowledgementType ackType = AcknowledgementTypeMapper.get(acknowledgementType);
Asm.As.Oib.DisplayService.Contracts.Data.Types.SeverityLevel severity = SeverityLevelMapper.get(severityLevel);
Asm.As.Oib.DisplayService.Contracts.Messages.SendMessageResponse sendMessageResponse = displaySession.
SendMessageByLinePathFirstStation(linePath, messageText, extendedDescription, ackType, callbackRequest, 0, severity, null, null);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SendMessageByLinePathFirstStation finished");
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "java call to SendMessageByLinePathFirstStation finished", e);
}
}
public void sendMessageByStationPath(string stationPath, string messageText, string extendedDescription, AcknowledgementType acknowledgementType,
bool callbackRequest, SeverityLevel severityLevel, Answer[] answerList)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SendMessageByStationPath");
if (stationPath.Equals("*"))
{
stationPath = firstMachineInLine;
}
else if (stationPath.Equals("#"))
{
stationPath = lastMachineInLine;
}
try
{
Asm.As.Oib.DisplayService.Proxy.Architecture.Objects.DisplayServiceClient displaySession = DisplayServiceAccess.DisplayServiceSession;
Asm.As.Oib.DisplayService.Contracts.Data.Types.AcknowledgementType ackType = AcknowledgementTypeMapper.get(acknowledgementType);
Asm.As.Oib.DisplayService.Contracts.Data.Types.SeverityLevel severity = SeverityLevelMapper.get(severityLevel);
List<Asm.As.Oib.DisplayService.Contracts.Data.Answer> asmAnswerList = new List<Asm.As.Oib.DisplayService.Contracts.Data.Answer>();
Asm.As.Oib.DisplayService.Contracts.Messages.SendMessageResponse sendMessageResponse = displaySession.
SendMessageByStationPath(stationPath, messageText, extendedDescription, ackType, callbackRequest, 0, severity, asmAnswerList, null);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "java call to SendMessageByStationPath finished with failure");
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "java call to SendMessageByStationPath finished", e);
}
}
}
}

View File

@@ -0,0 +1,266 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Threading;
using com.itac.artes.ihap;
using com.itac.mes.domain;
using com.itac.mes.tools;
using com.itac.oib;
using com.itac.oib.boardgatekeeper.service;
using com.itac.oib.linecontrol.service;
using com.itac.oib.monitoring.service;
using com.itac.oib.siplacesetupcenter.service;
using com.itac.oib.traceability.service;
// Handler der das callen von Methoden des DataInterface aus dem iTAC.OIB.Adapter übernimmt
namespace com.itac.mes.proxy.sockets
{
public delegate void PropertyChangeListener(object sender, string channelName, string message);
public class IhapEventChannel : RealProxy
{
private static int CONNECTION_CHECK_MILLIES = 500;
private TcpClient _client;
private IhapOutputStream _ios;
private IhapInputStream _iis;
private bool _isShutdown;
public string channelName { get; set; }
private long lastCall = DateTime.Now.Ticks;
private Object lockObject = new Object();
private Thread aliveThread;
public event PropertyChangeListener connectionStateChangeListener;
public IhapEventChannel(TcpClient client, String channelName)
: base(typeof(OIBEvents))
{
lock (typeof(IhapHandler))
{
}
this.channelName = channelName;
this._client = client;
_ios = new IhapOutputStream(_client.GetStream());
_iis = new IhapInputStream(_client.GetStream());
aliveThread = new Thread(new ThreadStart(aliveThreadRun));
}
public void shutdown()
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "closing channel" + channelName);
_isShutdown = true;
try
{
_client.Close();
}
catch (Exception)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Warning, "closing channel" + channelName + " failed");
}
}
public long getLastCall()
{
return lastCall;
}
public bool isConnected()
{
return _client.Client.Connected;
}
public bool isShutdownInProgress()
{
return _isShutdown;
}
public override IMessage Invoke(IMessage message)
{
lastCall = new DateTime().Ticks;
IMethodCallMessage methodMsg = (IMethodCallMessage)message;
try
{
MethodInfo methodInfo = typeof(OIBEvents).GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
Type[] interfaces = typeof(OIBEvents).GetInterfaces();
foreach (Type t in interfaces)
{
methodInfo = t.GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
if (methodInfo != null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, String.Format("found method {0} in interface {1}", methodInfo.Name, t.Name));
break;
}
}
if (methodInfo == null)
{
throw new Exception("IHapEventChannel: methode '" + methodMsg.MethodName + "' not found in any of the interfaces");
}
object[] args = methodMsg.Args;
if (methodMsg.MethodName.Equals("Equals"))
{
return new ReturnMessage(args[0].Equals(this), args, 0, methodMsg.LogicalCallContext, methodMsg);
}
else if (methodMsg.MethodName.Equals("GetHashCode"))
{
return new ReturnMessage(this.GetHashCode(), args, 0, methodMsg.LogicalCallContext, methodMsg);
}
else if (methodMsg.MethodName.Equals("shutdown"))
{
shutdown();
stopAliveThread();
connectionClosed();
return new ReturnMessage(null, args, 0, methodMsg.LogicalCallContext, methodMsg);
}
else if (methodMsg.MethodName.Equals("startup"))
{
aliveThread.Start();
return new ReturnMessage(null, args, 0, methodMsg.LogicalCallContext, methodMsg);
}
Object retValue = sendCall(methodInfo, args);
return new ReturnMessage(retValue, args, 0, methodMsg.LogicalCallContext, methodMsg);
}
catch (TargetInvocationException ite)
{
return new ReturnMessage(ite.GetBaseException(), methodMsg);
}
catch (Exception ite)
{
return new ReturnMessage(ite.GetBaseException(), methodMsg);
}
}
private Object sendCall(MethodInfo method, Object[] args)
{
lock (lockObject)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "Send event '" + method.Name + "' to socket " + _client.Client.RemoteEndPoint + " on " + channelName);
Object result = null;
try
{
_ios.writeBoolean(false);
_ios.call(method, args);
_ios.Flush();
IhapReply reply = _iis.readReply();
if (reply is IhapSuccessReply)
{
result = ((IhapSuccessReply)reply).getReturnValue();
}
else
{
IhapFaultReply fault = (IhapFaultReply)reply;
switch (fault.getFaultCode())
{
case FaultCode.NoSuchMethodException:
throw new NotImplementedException(fault.getMessage());
case FaultCode.ProtocolException:
throw new IhapProtocolException(fault.getMessage(), null);
default:
throw new IhapProtocolException(fault.getMessage(), null);
//(Exception)fault.getException();
}
}
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "Error while sending event call on " + channelName + ":" + e.Message + "\n" + e.StackTrace);
shutdown();
}
return result;
}
}
protected void connectionClosed()
{
// Hier wird überprüft, ob ein Eintrag in der Aufruf-Liste vorhanden ist.
if (this.connectionStateChangeListener != null)
{
// Hier wird jeder Delegat, der sich für den Event registriert hat, aufgerufen.
this.connectionStateChangeListener(this, channelName, "connectionClosed");
}
}
/**
*
*/
private void stopAliveThread()
{
if (aliveThread.IsAlive && (aliveThread.ThreadState != System.Threading.ThreadState.Running))
{
aliveThread.Interrupt();
}
}
public void aliveThreadRun()
{
while (!_isShutdown && aliveThread.ThreadState == System.Threading.ThreadState.Running)
{
// wenn der letzte Call länger als .. her ist...
try
{
Thread.Sleep(50);
}
catch (Exception)
{
// wenn beim schliessen der Verbindung noch was passiert ist das nicht schlimm
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "interrupted for " + channelName);
}
if (DateTime.Now.Ticks - lastCall > CONNECTION_CHECK_MILLIES)
{
try
{
// versuchen den Server zu pingen
// wenn das fehlschlägt ist die Verbindung kaputt
lock (lockObject)
{ // das erfolgreiche Schreiben eines booleschen Wertes ist aus Kommunikationssicht zu sehen wie der
// erfolgreiche Aufruf einer Methode
if (!_isShutdown && (aliveThread.ThreadState == System.Threading.ThreadState.Running))
{
// nur wenn die Verbindung nicht bereits gestoppt wurde...
_ios.writeBoolean(true);
_ios.Flush();
lastCall = DateTime.Now.Ticks;
}
}
}
catch (Exception)
{
try
{
_isShutdown = true;
_client.Close();
}
catch (IOException e)
{
// wenn beim schliessen der Verbindung noch was passiert ist das nicht schlimm
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "shutdown connection problem for " + channelName, e);
}
finally
{
// die Schreibverbindung ist kaputt, also diese Connection töten...
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "detected broken connection for " + channelName
+ " because Server closed port");
connectionClosed();
}
}
}
}
// wenn beim schliessen der Verbindung noch was passiert ist das nicht schlimm
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "channel shut down finished for " + channelName);
}
}
}

View File

@@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Threading;
using com.itac.artes.ihap;
using com.itac.artes.ihap.serialize;
using com.itac.mes.domain;
using com.itac.mes.proxy.business;
using com.itac.mes.tools;
using com.itac.oib;
using com.itac.oib.boardgatekeeper.service;
using com.itac.oib.linecontrol.service;
using com.itac.oib.monitoring.service;
using com.itac.oib.siplacesetupcenter.service;
using com.itac.oib.traceability.service;
namespace com.itac.mes.proxy.sockets
{
public delegate void ClientDisconnectedHandler(IhapHandler handler);
public class IhapHandler : RealProxy
{
private static IDictionary<String, MethodInfo> _methodMap;
private static int handlerCounter;
private Object lockObject = new Object();
private int handlerNr;
private TcpClient _client;
private IhapOutputStream _ios;
private IhapInputStream _iis;
private OIBServiceImpl _serviceImpl;
private bool _isShutdown;
private long lastCall = DateTime.Now.Ticks;
public IhapHandler(TcpClient client, OIBServiceImpl oibServiceImpl)
: base(typeof(OIBEvents))
{
lock (typeof(IhapHandler))
{
handlerCounter++;
this.handlerNr = handlerCounter;
}
this._client = client;
this._serviceImpl = oibServiceImpl;
// damit zum testen callbacks aufgerufen werden koennen
initMethodMap();
Thread thread = new Thread(new ThreadStart(Run));
thread.Start();
}
public event ClientDisconnectedHandler ClientDisconnected;
private static void initMethodMap()
{
if (_methodMap != null)
{
return;
}
_methodMap = new Dictionary<String, MethodInfo>();
ProtocolMapping protocolMapping = new ProtocolMapping_v1();
MethodInfo[] methods = typeof(OIBService).GetMethods();
foreach (MethodInfo method in methods)
{
_methodMap.Add(protocolMapping.getOverloadMethodName(method), method);
}
// Alle Methoden aller implmentierten Interface eintragen...
Type[] array = typeof(OIBService).GetInterfaces();
foreach (Type innerType in array)
{
methods = innerType.GetMethods();
foreach (MethodInfo method in methods)
{
_methodMap.Add(protocolMapping.getOverloadMethodName(method), method);
}
}
}
public void shutdown()
{
_isShutdown = true;
try
{
_serviceImpl.Shutdown();
_client.Close();
}
catch (Exception)
{
}
}
public long getLastCall()
{
return lastCall;
}
public bool isConnected()
{
return _client.Client.Connected;
}
public string getName()
{
return "IhapHandler" + handlerNr;
}
public bool isShutdownInProgress()
{
return _isShutdown;
}
public override IMessage Invoke(IMessage message)
{
lastCall = new DateTime().Ticks;
IMethodCallMessage methodMsg = (IMethodCallMessage)message;
try
{
MethodInfo methodInfo = typeof(OIBEvents).GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
// der Reihe nach alle Interface durchgehen, die als Callback implementiert sind
if (methodInfo == null)
{
methodInfo = typeof(ISiplaceSetupCenterNotify).GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
}
if (methodInfo == null)
{
methodInfo = typeof(ITraceability).GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
}
if (methodInfo == null)
{
methodInfo = typeof(ISetupCenterExternalControl).GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
}
if (methodInfo == null)
{
methodInfo = typeof(IMonitoringReceiver).GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
}
if (methodInfo == null)
{
methodInfo = typeof(ILineControlReceiver).GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
}
if (methodInfo == null)
{
methodInfo = typeof(IAdapterNotify).GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
}
if (methodInfo == null)
{
methodInfo = typeof(IBoardGateKeeper).GetMethod(methodMsg.MethodName, (Type[])methodMsg.MethodSignature);
}
if (methodInfo == null)
{
throw new Exception("IHapHandler.cs: methode nicht in den Interfacen gefunden");
}
object[] args = methodMsg.Args;
if (methodMsg.MethodName.Equals("Equals"))
{
return new ReturnMessage(args[0].Equals(this), args, 0, methodMsg.LogicalCallContext, methodMsg);
}
else if (methodMsg.MethodName.Equals("GetHashCode"))
{
return new ReturnMessage(this.GetHashCode(), args, 0, methodMsg.LogicalCallContext, methodMsg);
}
Object retValue = sendCall(methodInfo, args);
return new ReturnMessage(retValue, args, 0, methodMsg.LogicalCallContext, methodMsg);
}
catch (TargetInvocationException ite)
{
return new ReturnMessage(ite.GetBaseException(), methodMsg);
}
catch (Exception ite)
{
return new ReturnMessage(ite.GetBaseException(), methodMsg);
}
}
public void Run()
{
Thread.CurrentThread.Name = "IhapHandler-" + handlerNr;
_ios = new IhapOutputStream(_client.GetStream());
_iis = new IhapInputStream(_client.GetStream());
try
{
while (!_isShutdown && isConnected())
{
receiveCall();
}
}
catch (Exception)
{
shutdown();
}
}
private void receiveCall()
{
lock (lockObject)
{
try
{
Exception fault = null;
Object returnValue = null;
String methodName = null;
try
{
if (!_iis.readBoolean())
{
IhapCall lCall = _iis.readCall();
methodName = lCall.getOverloadMethodName();
if (_methodMap.ContainsKey(methodName))
{
MethodInfo lMethod = _methodMap[methodName];
Object[] args = lCall.getArgs();
returnValue = lMethod.Invoke(_serviceImpl, args);
lastCall = DateTime.Now.Ticks;
}
else
{
throw new NotImplementedException();
}
}
else
{
//ping...
return;
}
}
catch (IhapProtocolException pe)
{
if (pe.Message.EndsWith("end of file"))
{
throw pe;
}
fault = new ArtesRemoteException("Unable to read client request on " + getName(), pe);
_ios.writeFaultReply(FaultCode.ProtocolException, fault);
}
catch (NotImplementedException)
{
fault = new ArtesRemoteException("Unknown method '" + methodName + "'");
_ios.writeFaultReply(FaultCode.NoSuchMethodException, fault);
}
catch (IOException ioe)
{
throw ioe;
}
catch (Exception e)
{
if (e is TargetInvocationException)
{
e = ((TargetInvocationException)e).InnerException;
}
fault = e;
_ios.writeFaultReply(FaultCode.ServiceException, fault);
}
if (fault == null)
{
_ios.writeSuccessReply(returnValue);
}
}
catch (IOException ioe)
{
if (ioe.Message.EndsWith("end of file"))
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Socket " + _client.Client.RemoteEndPoint + " disconnected for " + getName());
ClientDisconnected(this);
shutdown();
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "Error receiving call for " + getName() + ":" + ioe.Message);
ClientDisconnected(this);
}
throw ioe;
}
finally
{
try
{
_ios.Flush();
}
catch (IOException)
{
}
}
}
}
private Object sendCall(MethodInfo method, Object[] args)
{
lock (lockObject)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "Send event '" + method.Name + "' to socket " + _client.Client.RemoteEndPoint + " for " + getName());
Object result = null;
try
{
_ios.writeBoolean(false);
_ios.call(method, args);
_ios.Flush();
IhapReply reply = _iis.readReply();
if (reply is IhapSuccessReply)
{
result = ((IhapSuccessReply)reply).getReturnValue();
}
else
{
IhapFaultReply fault = (IhapFaultReply)reply;
switch (fault.getFaultCode())
{
case FaultCode.NoSuchMethodException:
throw new NotImplementedException(fault.getMessage());
case FaultCode.ProtocolException:
throw new IhapProtocolException(fault.getMessage(), null);
default:
throw new IhapProtocolException(fault.getMessage(), null); // (Exception)fault.getException();
}
}
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "Error while sending event call for " + getName() + " . " + e.Message + "\n" + e.StackTrace);
shutdown();
}
return result;
}
}
public void setAdapterControl(IAdapterControl adapterControl)
{
_serviceImpl.SetAdapterControl(adapterControl);
}
}
}

View File

@@ -0,0 +1,155 @@
#region Namespace
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using com.itac.mes.proxy.business;
using com.itac.oib;
using com.itac.mes.tools;
#endregion
namespace com.itac.mes.proxy.sockets
{
public class SocketAdapter
{
private readonly IList<IhapHandler> _channels = new List<IhapHandler>();
private readonly TcpListener _listener;
private readonly IAdapterControl _adapterControl;
private readonly OIBServiceImpl _serviceImpl;
private bool _isShutdown = false;
// Wenn ein IHapHandler ein Disconnect feststellt wird eine Verbindung entfernt...
public void ClientDisconnected(IhapHandler iHapHandler)
{
// remove handler with disconnected sockets
for (int i = _channels.Count - 1; i >= 0; i--)
{
IhapHandler element = _channels[i];
if (element == iHapHandler)
{
_channels[i].shutdown();
_channels.RemoveAt(i);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Remove socket connection.");
}
}
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "Nr of active connections: " + _channels.Count);
}
public SocketAdapter(int listeningPort, IAdapterControl adapterControl, OIBServiceImpl serviceImpl)
{
_listener = new TcpListener(IPAddress.Any, listeningPort);
_listener.Start();
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Listen on port " + listeningPort);
_adapterControl = adapterControl;
_serviceImpl = serviceImpl;
var thread = new Thread(Run);
thread.Start();
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Startup " + Constants.SERVICE_NAME + " finished.");
//
// neuen Thread aufmachen, der immer wieder nachguckt, wie oft die IHapHandler benutzt werden. und unbenutzte Verbindungen entfernt
var checkAliveThread = new Thread(RunCheckAlive);
checkAliveThread.Start();
}
public void Run()
{
Thread.CurrentThread.Name = "SocketAdapter";
while (!_isShutdown)
{
TcpClient client;
try
{
client = _listener.AcceptTcpClient();
}
catch (SocketException se)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "Accepting new socket connection failed", se);
continue;
}
var handler = new IhapHandler(client, _serviceImpl);
handler.setAdapterControl(_adapterControl);
handler.ClientDisconnected += ClientDisconnected;
_channels.Add(handler);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Incoming socket connection from " + client.Client.RemoteEndPoint);
}
}
public void RunCheckAlive()
{
Thread.CurrentThread.Name = "CheckAliveThread";
while (!_isShutdown)
{
bool removed = false;
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "registered incoming socket connections: " + _channels.Count);
try
{
for (int i = _channels.Count - 1; i >= 0; i--)
{
var channel = _channels[i];
if (!channel.isConnected())
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "remove disconnected incoming socket connection for " + channel.getName());
_channels.Remove(channel);
removed = true;
continue;
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "" + channel.getName() + " channel last used: " + new DateTime(channel.getLastCall()));
if ((channel.getLastCall() + 36001000L) < DateTime.Now.Ticks) // eine Stunde...
{
// Verbindung schliessen, wenn Sie länger als ... nicht benutzt wurde
// channel.shutdown();
}
}
if (removed)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "remaining open incoming socket connections after cleanup: " + _channels.Count);
}
}
catch (Exception )
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "service channel listing interrupted");
}
// LG: Why this??
Thread.Sleep(60000);
}
}
public void Shutdown()
{
_isShutdown = true;
try
{
_listener.Stop();
foreach (var channel in _channels)
{
if (channel.isConnected())
{
channel.shutdown();
}
}
_channels.Clear();
}
catch
{
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Listen port closed.");
}
}
}

View File

@@ -0,0 +1,686 @@
#region Namespace
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
using System.Threading;
using com.itac.mes.proxy.business;
using com.itac.mes.proxy.sockets;
using com.itac.oib;
using com.itac.oib.siplacepro.service;
using Itac.Oib;
using Asm.As.Oib.Client;
using Asm.As.Oib.Client.CustomExtensions;
using System.Security.Principal;
using com.itac.mes.tools;
using com.itac.oib.siplacesetupcenter.contracts.data;
using com.itac.oib.linecontrol.data;
#endregion
namespace com.itac.mes.proxy.winservice
{
public class WindowsService : ServiceBase
{
#region Fields
/// <summary>
/// Der Linienname ergibt sich aus der SetupCenter Konfiguration. Es darf nur eine Linie geben.
/// </summary>
private SocketAdapter _socketAdapter;
private OIBEventHandler _eventHandler;
private OibClient _oibClient;
private static List<KeyValue> versionList;
#endregion
#region Static Methods
private static string GetVersionNr()
{
var asm = Assembly.GetExecutingAssembly();
var asmName = asm.GetName();
object[] attribs = asm.GetCustomAttributes(typeof(AssemblyProductAttribute), true);
string productName = String.Empty;
if (attribs.Length > 0)
{
var asmProduct = attribs[0] as AssemblyProductAttribute;
productName = asmProduct.Product;
}
string aVersion = String.Format("{1}.{2}.{3}.{4}",
productName, asmName.Version.Major, asmName.Version.Minor, asmName.Version.Build, asmName.Version.Revision);
string vers = String.Format("{0} - Version: {1}", productName, aVersion);
return (vers);
}
private static string GetFileVersionNr()
{
var asm = Assembly.GetExecutingAssembly();
object[] attribs = asm.GetCustomAttributes(typeof(AssemblyProductAttribute), true);
string productName = String.Empty;
var assembly = Assembly.GetExecutingAssembly();
if (attribs.Length > 0)
{
var asmProduct = attribs[0] as AssemblyProductAttribute;
productName = asmProduct.Product;
}
var fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
// string version = fvi.ProductVersion;
versionList.Add(new KeyValue() { key = productName, value = fvi.ProductVersion });
string version = String.Format("{0} - FileVersion: {1}", productName, fvi.ProductVersion);
String[] xVersion = fvi.Comments.Split();
String[] mesVersion = xVersion[3].Split('=');
versionList.Add(new KeyValue() { key = mesVersion[0], value = mesVersion[1] });
String[] intfVersion = xVersion[4].Split('=');
versionList.Add(new KeyValue() { key = intfVersion[0], value = intfVersion[1] });
return (version);
}
#endregion
/// <summary>
/// Public Constructor for WindowsService.
/// - Put all of your Initialization code here.
/// </summary>
public WindowsService()
{
ServiceName = Constants.SERVICE_NAME;
EventLog.Log = Constants.LOGGER;
// These Flags set whether or not to handle that specific
// type of event. Set to true if you need it, false otherwise.
CanHandlePowerEvent = true;
CanHandleSessionChangeEvent = true;
CanPauseAndContinue = true;
CanShutdown = true;
CanStop = true;
}
/// <summary>
/// The Main Thread: This is where your Service is Run.
/// </summary>
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
if (e.IsTerminating)
{
object o = e.ExceptionObject;
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "### general exception handling ###");
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, o.ToString());
}
};
var service = new WindowsService();
#if (SERVICE)
ServiceBase.Run(service);
#else
service.OnStart(null);
Console.ReadLine();
service.OnStop();
#endif
}
/// <summary>
/// OnStart(): Put startup code here
/// - Start threads, get inital data, etc.
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
InitService();
base.OnStart(args);
}
/// <summary>
/// OnStop(): Put your stop code here
/// - Stop threads, set final data, etc.
/// </summary>
protected override void OnStop()
{
ShutdownService();
base.OnStop();
}
/// <summary>
/// OnShutdown(): Called when the System is shutting down
/// - Put code here when you need special handling
/// of code that deals with a system shutdown, such
/// as saving special data before shutdown.
/// </summary>
protected override void OnShutdown()
{
ShutdownService();
base.OnShutdown();
}
/// <summary>
/// Dieser Adapter übernimmt die Steuerung der Subscriptions und der Endpoints
/// </summary>
private readonly AdapterControl _adapterControl = new AdapterControl();
private StatisticWorker statisticWorker;
private Thread statisticThread;
private void InitService()
{
// Ausgabe hilfe für xml-Messages
var messageWriter = new MessageWriter();
var config = new AppSettingsReader();
//<add key="xmlExport" value="true"/>
bool xmlExport = (bool)config.GetValue("xmlExport", typeof(bool));
bool xmlLogging = (bool)config.GetValue("xmlLogging", typeof(bool));
messageWriter.init(xmlExport, xmlLogging);
_eventHandler = new OIBEventHandler(_adapterControl, messageWriter);
try
{
#if (SERVICE)
TraceListener eventLogTraceListener = new EventLogTraceListener(Constants.SERVICE_NAME);
eventLogTraceListener.Filter = new EventTypeFilter(SourceLevels.Information);
LogHandler.addListener(eventLogTraceListener);
#endif
// this is the port the oib adapter listens for incoming connections from the data interface application
var listenPort = (int)config.GetValue("ListenPort", typeof(int));
// store all configuration values in the configuration instance
Asm.As.Oib.Client.Configuration.OibClientConfiguration oibClientconfiguration = new Asm.As.Oib.Client.Configuration.OibClientConfiguration();
// PRE: _oibClient = new OibClient("iTac", "OibAdapter", oibCoreComuputerName, configuredLineFullPath);
oibClientconfiguration.ApplicationName = "OibAdapter";
oibClientconfiguration.CompanyName = "iTac";
oibClientconfiguration.FactoryElementPath = "Enterprise"; // this is probably not necessary to set
oibClientconfiguration.EventNotificationProtocol = new Asm.As.Oib.Client.Configuration.EventNotificationProtocol();
oibClientconfiguration.OibClientMode = Asm.As.Oib.Client.Configuration.OibClientMode.Line;
oibClientconfiguration.TcpPortSharingEnabled = true;
oibClientconfiguration.UnsubscribeCoreEventsOnShutdown = true;
oibClientconfiguration.CoreComputerName = (String)config.GetValue("OIBCoreHostName", typeof(String));
oibClientconfiguration.LineControlMesInterceptorCallbackPort = (int)config.GetValue("LinecontrolMesInterceptorPort", typeof(int)); // new from OIB5.3
oibClientconfiguration.OibSpiCallbackPort = (int)config.GetValue("SiplaceProEventPort", typeof(int));
oibClientconfiguration.DisplayServiceCallbackPort = (int)config.GetValue("DisplayServiceEventPort", typeof(int));
oibClientconfiguration.SetupCenterEventsCallbackPort = (int)config.GetValue("SetupCenterNotifyPort", typeof(int));
oibClientconfiguration.SetupCenterExternalControlCallbackPort = (int)config.GetValue("SetupCenterExternalControlPort", typeof(int));
oibClientconfiguration.TraceabilitySynchronousCallbackPort = (int)config.GetValue("TraceServicePort", typeof(int));
oibClientconfiguration.MonitoringEventsCallbackPort = (int)config.GetValue("MonitoringReceiverPort", typeof(int));
oibClientconfiguration.BoardGateKeeperCallbackPort = (int)config.GetValue("BoardGateKeeperEventPort", typeof(int));
oibClientconfiguration.DekPrinterExternalControlCallbackPort = (int)config.GetValue("DekPrinterExternalControlPort", typeof(int)); // new from OIB5.3
oibClientconfiguration.ConfigurationManagerCallbackPort = (int)config.GetValue("ConfigurationManagerCallbackPort", typeof(int)); // new from OIB5.3
oibClientconfiguration.LineFullPath = (String)config.GetValue("LineName", typeof(String));
var isSetupStation = (bool)config.GetValue("isSetupStation", typeof(bool));
var isOfflineMode = (bool)config.GetValue("offlineMode", typeof(bool));
// check that the process is started as administrator or end process with message
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
{
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, getHeadertext("iTAC.OIB.Adapter Startup Problem"));
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "");
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "Insufficient privileges!");
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "This process needs to be started with administrative privileges.");
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "Right click on the executable file and select \"Run As Administrator\"");
return;
}
_eventHandler.LineName = oibClientconfiguration.LineFullPath;
versionList = new List<KeyValue>();
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("iTAC.OIB.Adapter"));
String version = GetVersionNr();
LogHandler.log(Constants.LOGGER, TraceEventType.Information, version);
String fileVersion = GetFileVersionNr();
LogHandler.log(Constants.LOGGER, TraceEventType.Information, fileVersion);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "listening for incoming connections on port " + listenPort);
_adapterControl._isSetupStation = isSetupStation;
if (isSetupStation)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "running in SetupStation Mode");
}
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in loadedAssemblies)
{
if (assembly.FullName.StartsWith("AsmApi"))
{
AssemblyProductAttribute adAttr = (AssemblyProductAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyProductAttribute));
versionList.Add(new KeyValue() { key = "AsmApi", value = adAttr.Product });
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "AsmApi Version: " + adAttr.Product);
}
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("OIB Startup"));
_oibClient = new OibClient(oibClientconfiguration);
String firstMachineInLine = "";
String lastMachineInLine = "";
_adapterControl.OibClient = _oibClient;
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("Setup Center Access"));
var serviceImpl = new OIBServiceImpl(_adapterControl, messageWriter);
serviceImpl.OibSetupCenterAccess = _oibClient.GetOibSetupCenterAccess();
Asm.As.Oib.SiplaceSetupCenter.Contracts.Data.Configuration setupCenterConfig = serviceImpl.OibSetupCenterAccess.GetConfiguration();
_eventHandler.serviceImpl = serviceImpl;
#region Check Setup Center Version and that the confiured line is also configured in setup center.
var stationFullPaths = new List<string>();
try
{
// setupCenterConfig = serviceImpl.GetConfiguration();
String scVersion = setupCenterConfig.ProductVersion;
if (scVersion == null)
{
// Der iTAC.OIB.Adapter muss eine SetupCenter Verbindung haben
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "iTAC OIB.Adapter can not work without SetupCenter connection");
Environment.Exit(-3);
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "SetupCenter connected, version = " + scVersion);
versionList.Add(new KeyValue() { key = "SetupCenter", value = scVersion });
// nur eine Linie erlaubt ...
if (!isSetupStation)
{
bool isLineConfiguredInSetupCenter = false;
foreach (var line in setupCenterConfig.LineConfigurations)
{
if (line.LinePath == oibClientconfiguration.LineFullPath)
{
isLineConfiguredInSetupCenter = true;
firstMachineInLine = line.MachineConfigurations[0].MachineLocator.MachineName;
lastMachineInLine = line.MachineConfigurations[line.MachineConfigurations.Count - 1].MachineLocator.MachineName;
BoardGateKeeperReceiver.DefaultMachineFullPath = firstMachineInLine;
foreach (var station in line.MachineConfigurations)
{
stationFullPaths.Add(station.MachineLocator.MachineName);
}
foreach (var station in line.PrinterConfigurations)
{
stationFullPaths.Add(station.PrinterPath);
}
}
}
if (!isLineConfiguredInSetupCenter)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, string.Format("Line '{0}' is not configured in Setup Center. Adapter stops.", oibClientconfiguration.LineFullPath));
Environment.Exit(-4);
}
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "use fix url extension '/SetupStation'");
// HOW TO HANDLE THE SETUP_STATION
// _lineFullPath = "SetupStation";
}
}
catch (Exception ex)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "SetupCenter NOT connected, unable to get version information", ex);
Environment.Exit(-4);
}
serviceImpl.configuredLineFullPath = oibClientconfiguration.LineFullPath;
serviceImpl.firstMachineInLine = firstMachineInLine;
serviceImpl.lastMachineInLine = lastMachineInLine;
#endregion
OperatorNotificationManager operatorNotificationManager = null;
OibDisplayServiceAccess oibDisplayServiceAccess = null;
SetupCenterExternalControlReceiver externalcontrolReceiver = null;
if (!isOfflineMode)
{
/// listener auf externalcontrol bauen
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("SetupCenterExternalControl"));
var oibSetupCenterExternalControlEvents = _oibClient.GetOibSetupCenterExternalControlEvents();
externalcontrolReceiver = new SetupCenterExternalControlReceiver(oibSetupCenterExternalControlEvents);
externalcontrolReceiver._eventHandler = _eventHandler;
_adapterControl.SetupCenterExternalControlReceiver = externalcontrolReceiver;
if (oibClientconfiguration.DisplayServiceCallbackPort > 0)
{
oibDisplayServiceAccess = initDisplayService(serviceImpl);
}
}
TraceabilityReceiver traceOibReceiver = null;
SiplacePro siplacePro = null;
if (!isSetupStation)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("Setup Center Events"));
var oibSetupCenterEvents = _oibClient.GetOibSetupCenterEvents(stationFullPaths);
if (!isOfflineMode)
{
_adapterControl.SetupCenterReceiver = new SetupCenterReceiver(oibSetupCenterEvents, oibClientconfiguration.LineFullPath, isSetupStation);
_adapterControl.SetupCenterReceiver._eventHandler = _eventHandler;
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("SIPLACE Pro"));
OibSpiAccess oibSpiAccess = null;
if (!isOfflineMode)
{
oibSpiAccess = _oibClient.GetOibSpiAccess();
var spiVersion = oibSpiAccess.Session.SPIVersion;
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("Monitoring Events"));
if (!isOfflineMode)
{
var oibMonitoringEvents = _oibClient.GetOibMonitoringEvents();
_adapterControl.MonitoringReceiver = new MonitoringReceiver(oibMonitoringEvents, oibClientconfiguration.LineFullPath);
_adapterControl.MonitoringReceiver._eventHandler = _eventHandler;
}
try
{
HashSet<string> versionKeySet = new HashSet<string>();
versionKeySet.Add("ConfigurationManager");
versionKeySet.Add("ServiceLocator");
versionKeySet.Add("DisplayService");
versionKeySet.Add("SIPLACE.SetupCenter.MaterialControl");
versionKeySet.Add("SIPLACE.Pro.LineControl");
versionKeySet.Add("SIPLACE.Monitoring");
versionKeySet.Add("SIPLACE.Pro.SPI");
/* var serviceLocator = _oibClient.Get.GetServiceRegistration();
var allServices = serviceLocator.GetAllServices();
for (int i = 0; i < allServices.Length; i++)
{
var sd = allServices[i];
if (versionKeySet.Contains(sd.ServiceName) && sd.Configuration != null)
{
versionList.Add(new KeyValue() { key = sd.ServiceName, value = sd.ServiceVersion });
}
}
*/
_adapterControl.productVersions = versionList;
}
catch (Exception)
{
throw;
}
if (!isOfflineMode)
{
siplacePro = new SiplacePro();
siplacePro._eventHandler = _eventHandler;
siplacePro.oibSpiAccess = oibSpiAccess;
siplacePro.RegisterCallback();
serviceImpl.SiplacePro = siplacePro;
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("Siplace Pro"));
versionList.Add(new KeyValue() { key = "SiplacePro", value = siplacePro.oibSpiAccess.Session.ProductVersion });
var oibSpiEvents = _oibClient.GetOibSpiEvents(oibSpiAccess);
oibSpiEvents.StartDownloadEvents();
var spiReceiver = new SpiReceiver(oibSpiEvents, _eventHandler);
_adapterControl.SpiReceiver = spiReceiver;
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("Line Control"));
serviceImpl.OibLineControlAccess = _oibClient.GetOibLineControlAccess();
// LogHandler.log(Constants.LOGGER, TraceEventType.Information, "connect to Line Control: " + serviceImpl.OibLineControlAccess.OibServiceComputerName);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "connect to Line Control: " + serviceImpl.OibLineControlAccess.DisplayName);
try
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Line Control Database Id: " + serviceImpl.OibLineControlAccess.LineControlSession.DatabaseId);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "Line Control Database Id not detected", e);
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Line Control: " + serviceImpl.OibLineControlAccess.LineControlSession.ProductVersion);
versionList.Add(new KeyValue() { key = "LineControl", value = serviceImpl.OibLineControlAccess.LineControlSession.ProductVersion });
Asm.As.Oib.Client.CustomExtensions.Configuration.OperatorNotificationManagerConfiguration operatorNotificationManagerConfiguration = new Asm.As.Oib.Client.CustomExtensions.Configuration.OperatorNotificationManagerConfiguration();
operatorNotificationManagerConfiguration.ShowMessageOnVihDataRejected = true;
operatorNotificationManagerConfiguration.StopLineOnTraceDataRejected = true;
operatorNotificationManagerConfiguration.StopStationOnVihDataRejected = true;
// NO specific configuration right now
operatorNotificationManager = new OperatorNotificationManager(_oibClient, oibSpiAccess, serviceImpl.OibLineControlAccess, oibDisplayServiceAccess, operatorNotificationManagerConfiguration);
traceOibReceiver = initTraceability(oibClientconfiguration.TraceabilitySynchronousCallbackPort, oibSpiAccess, serviceImpl.OibLineControlAccess, oibDisplayServiceAccess, operatorNotificationManager);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("Changeover Manager"));
Asm.As.Oib.Client.CustomExtensions.Configuration.OibChangeoverManagerConfiguration changeoverManagerConfiguration = new Asm.As.Oib.Client.CustomExtensions.Configuration.OibChangeoverManagerConfiguration();
// ab client 2.1.0.14 diesen Constructor nutzen
changeoverManagerConfiguration.LineFullPath = oibClientconfiguration.LineFullPath;
changeoverManagerConfiguration.ChangeoverIncompleteRepeatWarningSeconds = 120;
changeoverManagerConfiguration.ChangeoverIncompleteWarningSeconds = 120;
var changeoverManager = new ChangeoverManager(oibSpiAccess, oibSpiEvents, serviceImpl.OibSetupCenterAccess, oibSetupCenterEvents, serviceImpl.OibLineControlAccess, operatorNotificationManager, changeoverManagerConfiguration);
var changeoverReceiver = new ChangeoverReceiver(changeoverManager);
changeoverReceiver._eventHandler = _eventHandler;
_adapterControl.ChangeoverReceiver = changeoverReceiver;
serviceImpl.ChangeoverReceiver = changeoverReceiver;
initBoardGateKeeper(oibClientconfiguration.BoardGateKeeperCallbackPort, _eventHandler, _adapterControl, oibSpiAccess, oibSpiEvents, operatorNotificationManager, oibClientconfiguration.LineFullPath);
OibDekPrinterExtenalControlEvents dekReceiver = _oibClient.GetOibDekPrinterExtenalControlEvents();
var dekExternalControlReceiver = new DekPrinterExternalControlReceiver(dekReceiver);
_adapterControl.DekPrinterExternalControlReceiver = dekExternalControlReceiver;
OibLineControlMesInterceptorEvents mesLineControlInterceptorEvents = _oibClient.GetOibLineControlMesInterceptorEvents();
var lineControlMesInterceptorReceiver = new LineControlMesInterceptorReceiver(mesLineControlInterceptorEvents, _eventHandler);
_adapterControl.MesLineControlMesInterceptorReceiver = lineControlMesInterceptorReceiver;
// starting health checks when a port number is given
if (_oibClient.Configuration.ConfigurationManagerCallbackPort > 0)
{
_oibClient.GetOibHealthCheckCallbacks().Start();
}
}
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("iHap Connection"));
_socketAdapter = new SocketAdapter(listenPort, _adapterControl, serviceImpl);
String currentPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "current path = " + currentPath);
bool exists = System.IO.Directory.Exists(@"./xml");
if (exists)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "directory ./xml exists, start scanning");
DirectoryMonitor dirMonitor = new DirectoryMonitor();
dirMonitor.addType(typeof(com.itac.oib.siplacesetupcenter.contracts.data.MaterialMovedReport));
dirMonitor.addType(typeof(com.itac.oib.monitoring.contracts.data.StationEventComposite));
dirMonitor.addType(typeof(com.itac.oib.monitoring.contracts.data.BoardProcessedData));
dirMonitor.addType(typeof(FeederPlacedEvent));
dirMonitor.addType(typeof(PackagingUnitLocation));
dirMonitor.addType(typeof(TraceabilityData));
dirMonitor.addType(typeof(DownloadData));
dirMonitor.addType(typeof(PackagingUnitConsumedReport));
dirMonitor.addType(typeof(LineChangeoverEventArgs));
dirMonitor.addType(typeof(VirtualInkspotHandlerBoardRequest));
dirMonitor.deserializedObjectEvent += dispatchFileObject;
}
var proxyVersions = _oibClient.GetOibProxyVersions();
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("OIB Proxy Versions"));
foreach (var keyValuePair in proxyVersions)
{
if (!keyValuePair.Key.Equals("AsmApi"))
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, string.Format("{0,-50} {1,10}", keyValuePair.Key, keyValuePair.Value));
}
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("Statistic Thread"));
try
{
statisticWorker = new StatisticWorker();
statisticWorker.setVersionList(versionList);
statisticThread = new Thread(statisticWorker.DoWork);
statisticThread.Start();
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Statistic thread started! ");
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "Statistic thread NOT started!", e);
}
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("Initialization completed"));
if (!isOfflineMode)
{
_adapterControl.startMonitoringReceiver();
_adapterControl.startSetupCenterNotifyReceiver();
_adapterControl.startTraceReceiver();
_adapterControl.startBoardGateKeeper();
}
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "Initialization failed! " + e.Message, e);
}
}
private void dispatchFileObject(object sender, object deserializedObject)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "deserialized obejct");
/* if (traceOibReceiver != null)
{
dirMonitor.setTraceReceiver(traceOibReceiver);
}
if (_adapterControl.MonitoringReceiver != null)
{
dirMonitor.setMonitoringReceiver(_adapterControl.MonitoringReceiver);
}
dirMonitor.setSetupCenterReceiver(_adapterControl.SetupCenterReceiver);
dirMonitor.setSetupCenterExternalControl(externalcontrolReceiver);
if (siplacePro != null)
{
dirMonitor.setSiplacePro(serviceImpl.SiplacePro);
}
dirMonitor.changeoverReceiver = _adapterControl.ChangeoverReceiver;
dirMonitor.boardGateKeeperReceiver = _adapterControl.BoardGateKeeperReceiver;*/
}
private OibDisplayServiceAccess initDisplayService(OIBServiceImpl serviceImpl)
{
OibDisplayServiceAccess oibDisplayServiceAccess = null;
try
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("DisplayService"));
oibDisplayServiceAccess = _oibClient.GetOibDisplayServiceAccess();
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Warning, "DisplayService not initialized correctly, continue without DisplayService", e);
}
finally
{
serviceImpl.DisplayServiceAccess = oibDisplayServiceAccess;
}
return oibDisplayServiceAccess;
}
private TraceabilityReceiver initTraceability(int traceServicePort, OibSpiAccess oibSpiAccess, OibLineControlAccess oibLineControlAccess, OibDisplayServiceAccess oibDisplayServiceAccess, OperatorNotificationManager operatorNotificationManager)
{
TraceabilityReceiver traceOibReceiver = null;
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("Traceability"));
if (traceServicePort > 0)
{
try
{
var oibTraceabilityEvents = _oibClient.GetOibTraceabilityEvents();
traceOibReceiver = new TraceabilityReceiver(oibTraceabilityEvents, _eventHandler, operatorNotificationManager);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "Traceability initialization failure", e);
}
finally
{
_adapterControl.TraceReceiver = traceOibReceiver;
}
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "Traceability switched off by configuration (port is set to 0)");
}
return traceOibReceiver;
}
private void initBoardGateKeeper(int boardGateKeeperEventPort, OIBEventHandler _eventHandler, AdapterControl _adapterControl, OibSpiAccess oibSpiAccess, OibSpiEvents oibSpiEvents, OperatorNotificationManager operatorNotificationManager, String configuredLineFullPath)
{
BoardGateKeeperReceiver boardGateKeeperOibReceiver = null;
LogHandler.log(Constants.LOGGER, TraceEventType.Information, getHeadertext("BoardGateKeeper"));
if (boardGateKeeperEventPort > 0)
{
try
{
var oibBoardGateKeeperEvents = _oibClient.GetOibBoardGateKeeperEvents();
boardGateKeeperOibReceiver = new BoardGateKeeperReceiver(oibBoardGateKeeperEvents, _eventHandler);
Asm.As.Oib.Client.CustomExtensions.Configuration.VirtualInkspotHandlerConfiguration virtualInkspotHandlerConfiguration = new Asm.As.Oib.Client.CustomExtensions.Configuration.VirtualInkspotHandlerConfiguration();
virtualInkspotHandlerConfiguration.LineFullPath = configuredLineFullPath;
VirtualInkspotHandlerWrapper vx = new VirtualInkspotHandlerWrapper(oibSpiAccess, oibSpiEvents, oibBoardGateKeeperEvents, operatorNotificationManager, virtualInkspotHandlerConfiguration);
vx.VirtualInkspotData = boardGateKeeperOibReceiver.virtualInkspotData;
//
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "BoardGateKeeper initialization failure", e);
}
finally
{
_adapterControl.BoardGateKeeperReceiver = boardGateKeeperOibReceiver;
}
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "BoardGateKeeper switched off by configuration (port is set to 0)");
}
}
private string getHeadertext(string v)
{
String separator = "--------------------------------------------------------------------";
if (separator.Length < v.Length)
{
return separator.Substring(0, 10) + " " + v;
}
else
{
return separator.Substring(0, 10) + " " + v + " " + separator.Substring(0, separator.Length - v.Length);
}
}
private void ShutdownService()
{
statisticWorker.RequestStop();
statisticThread.Join();
_socketAdapter.Shutdown();
if (_oibClient != null)
_oibClient.Dispose();
if (_adapterControl != null)
_adapterControl.Dispose();
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using com.itac.mes.tools;
namespace com.itac.mes.proxy.winservice
{
[RunInstaller(true)]
public class WindowsServiceInstaller : ServiceInstaller
{
/// <summary>
/// Public Constructor for WindowsServiceInstaller.
/// - Put all of your Initialization code here.
/// </summary>
public WindowsServiceInstaller()
{
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
//# Service Account Information
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
serviceProcessInstaller.Username = null;
serviceProcessInstaller.Password = null;
//# Service Information
serviceInstaller.DisplayName = Constants.SERVICE_NAME;
serviceInstaller.StartType = ServiceStartMode.Automatic;
//# This must be identical to the WindowsService.ServiceBase name
//# set in the constructor of WindowsService.cs
serviceInstaller.ServiceName = Constants.SERVICE_NAME;
this.Installers.Add(serviceProcessInstaller);
this.Installers.Add(serviceInstaller);
}
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
ServiceController controller = new ServiceController(Constants.SERVICE_NAME);
try
{
controller.Start();
}
catch (Exception e)
{
if (!EventLog.SourceExists(Constants.SERVICE_NAME))
{
EventLog.CreateEventSource(Constants.SERVICE_NAME, Constants.LOGGER);
}
EventLog.WriteEntry(Constants.SERVICE_NAME, "@The service could not be started. Error: " + e.Message, EventLogEntryType.Error);
}
}
}
}

View File

@@ -0,0 +1,16 @@
namespace com.itac.oib.client
{
// property: assembly: ASM.AS.OIB.Client, Version: 3.0.0.0
public class OibClientService {
// canRead:True, canWrite:False
private string displayName;
public void setDisplayName(string displayName) {
this.displayName = displayName;
}
// field DisplayName without setMethod
}
}

View File

@@ -0,0 +1,27 @@
using com.itac.oib.linecontrol.service;
using System;
namespace com.itac.oib.client
{
// property: assembly: ASM.AS.OIB.Client, Version: 3.0.0.0
public class OibLineControlAccess : OibService {
// property: assembly: ASM.AS.OIB.SIPLACEPro.LineControl.Proxy, Version: 5.1.0.84
// canRead:True, canWrite:False
private OibLineControlAccess lineControlSession;
// property: assembly: mscorlib, Version: 4.0.0.0
// canRead:True, canWrite:False
private Nullable<bool> isServiceAlive;
public void setLineControlSession(OibLineControlAccess lineControlSession) {
this.lineControlSession = lineControlSession;
}
// field LineControlSession without setMethod
public void setIsServiceAlive(Nullable<bool> isServiceAlive) {
this.isServiceAlive = isServiceAlive;
}
// field IsServiceAlive without setMethod
}
}

View File

@@ -0,0 +1,16 @@
namespace com.itac.oib.client
{
// property: assembly: ASM.AS.OIB.Client, Version: 3.0.0.0
public class OibService : OibClientService {
// canRead:True, canWrite:False
private string serviceName;
public void setServiceName(string serviceName) {
this.serviceName = serviceName;
}
// field ServiceName without setMethod
}
}

View File

@@ -0,0 +1,180 @@
#region Namespace
using System;
using System.Diagnostics;
using Asm.As.Oib.Client;
using com.itac.mes.proxy.business;
using com.itac.oib.client.customextensions;
using com.itac.mes.tools;
using Constants = com.itac.mes.tools.Constants;
using com.itac.oib.siplacepro.contracts.data;
using com.itac.oib.traceability.contracts.data;
using OibSpiArchObj = Asm.As.Oib.SiplacePro.Proxy.Architecture.Objects;
using OibSpiBizObj = Asm.As.Oib.SiplacePro.Proxy.Business.Objects;
using OibSpiTypes = Asm.As.Oib.SiplacePro.Proxy.Types;
using System.Collections.Generic;
#endregion
namespace com.itac.oib.siplacepro.service
{
/// <summary>
/// Diese Klasse enthält eine Referenz auf eine Siplace pro Session, über die auf die SiplacePro Schnittstelle zugegriffen werden kann.
/// </summary>
public class SiplacePro : ISiplacePro
{
#region Fields
// Eventhandler zur übergabe des Events an Java Server.
public OIBEventHandler _eventHandler { set; get; }
public OibSpiAccess oibSpiAccess { get; set; }
#endregion
#region ISiplacePro Member
public void RegisterCallback()
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "subscribe SiplacePro events");
try
{
if (oibSpiAccess.Session != null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "SiplacePro Adapter Version: " + oibSpiAccess.Session.OibSiplaceProAdapterVersion);
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "SiplacePro Proxy Version: " + oibSpiAccess.Session.OibSiplaceProProxyVersion);
oibSpiAccess.Session.ServiceUnreachable += SpiSessionOnServiceUnreachable;
oibSpiAccess.Session.ServiceReconnect += SpiSessionOnServiceReconnect;
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "SiplacePro events subscribed ");
}
}
catch (Exception ex)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "Got exception during setting up Subcription mode: ", ex);
}
}
#endregion
#region SPI Event Handling
private void SpiSessionOnServiceReconnect(string endpoint, string comment)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "*** SERVICE RECONNECT ***");
if (_eventHandler != null)
_eventHandler.onServiceReconnect();
}
private void SpiSessionOnServiceUnreachable(string endpoint, string comment)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "*** SERVICE UNREACHABLE ***");
if (_eventHandler != null)
_eventHandler.onServiceDisconnect();
}
#endregion
#region ISiplacePro Member
public BoardElement[] getPlacementForBoard(String boardFullName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET get Board");
// PlacementInfo placementInfo = new PlacementInfo();
OibSpiBizObj.Board board = oibSpiAccess.Session.GetObject(boardFullName, OibSpiTypes.ObjectServerType.Board) as OibSpiBizObj.Board;
List<com.itac.oib.siplacepro.contracts.data.BoardElement> itacBoardElementList = new List<com.itac.oib.siplacepro.contracts.data.BoardElement>();
com.itac.oib.siplacepro.contracts.data.BoardElement itacBoardElement = new com.itac.oib.siplacepro.contracts.data.BoardElement();
com.itac.oib.siplacepro.contracts.data.Board itacBoard = BoardMapper.get(board);
itacBoardElement.Board = itacBoard;
//board = BoardElementHelper.DoBoard(board);
// itacBoard.producedSide = board.BoardSideProduced.ToString();
itacBoardElementList.Add(itacBoardElement);
return itacBoardElementList.ToArray();
}
// diese Methode im Download Event ausführen und Ergebnis zurückliefern
internal static BoardElement[] GetPlacementForRecipe(OibSpiBizObj.Recipe recipe)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET get Recipe");
BoardElement[] placementInfo = new BoardElement[0];
// var itacBoardElementList = new List<BoardElement>();
try
{
foreach (var boardelement in recipe.BoardElements)
{
// itacBoardElementList.Add(BoardElementHelper.DoBoardElement(boardelement));
}
// placementInfo.boardElements = itacBoardElementList.ToArray();
}
catch (Exception ex)
{
// bei allen Exceptions Ausgabe machen und null liefern!!!
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "converting board information failed, can't continue properly", ex);
return null;
}
return placementInfo;
}
#endregion
#region ISiplacePro Member
public BoardCheckInRequest completeCheckinData(BoardCheckInRequest checkinData)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "complete CheckInData");
if (checkinData == null) { return null; }
// Line und Recipe ermitteln, die fehlenden Werte in die übergebene Struktur eintragen und zurückliefern
var result = checkinData;
LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call getRecipe");
// var recipe = oibSpiAccess.Session.GetObject(checkinData.getRecipeName(), OibSpiTypes.ObjectServerType.Recipe) as OibSpiBizObj.Recipe;
// result.setRecipeName(monitoring.contracts.data.RecipeMapper.get(recipe));
// LogHandler.log(Constants.LOGGER, TraceEventType.Information, ".NET call getLine");
// var line = oibSpiAccess.Session.GetObject(checkinData.getLineName(), OibSpiTypes.ObjectServerType.Line) as OibSpiBizObj.Line;
// result.setLineName( LineMapper.get(line));
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "complete CheckInData finished");
return checkinData;
}
private static OibSpiArchObj.Identity GetStationIdentity(OibSpiBizObj.DownloadData downloadData, OibSpiBizObj.ProductionDataManager pdm)
{
foreach (var dd in pdm.LineControlData.DownloadData)
{
if (dd.Value.OID == downloadData.OID)
{
return dd.Key;
}
}
return null;
}
#endregion
internal void Download(Asm.As.Oib.SiplacePro.Contracts.Data.Business.Objects.DownloadData downloadData)
{
if (_eventHandler != null)
{
// TODO richtiges download nehmen _eventHandler.DownloadEvent(downloadData);
}
}
public LineChangeoverEventArgs getCurrentLineProductionData()
{
throw new NotImplementedException();
}
#region ISiplacePro Member
#endregion
}
}

View File

@@ -0,0 +1,420 @@
#region Namespace
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Asm.As.Oib.Client;
using com.itac.mes.domain;
using com.itac.mes.proxy.sockets;
using com.itac.mes.tools;
using Itac.Oib;
#endregion
namespace com.itac.oib
{
// remote-Methoden zum steuern der einzelnen Teile der Anwendung
public class AdapterControl : IAdapterControl, IDisposable
{
#region Fields
// Zugriff auf die folgenden Maps muss synchronisiert erfolgen
static readonly object _locker = new object();
// In dieser Map sind alle offenen Verbindungen zum DataInterface enthalten
private Dictionary<String, IhapEventChannel> openClientChannels = new Dictionary<String, IhapEventChannel>();
// pro Verbindung wird gez?hlt wie viele Connections es schon gab...
private Dictionary<String, Int32> channelNameCounter = new Dictionary<String, Int32>();
// Verbindungsparameter zum DataInterface. Diese werden nach dem Start des DataInterface an den Adapter ?bertragen
private int _port = 0;
private string _ipAddress = "";
private string _hostName = "";
private string _canonicalHostName = "";
// die folgenden Werte werden beim Initialisieren des iTAC.OIB.Adapter gesetzt
private int _own_itac_oib_adapter_port = 0;
private string _own_ip_address = "";
private string _own_host_name = "";
private string _own_canonical_host_name = "";
#endregion
// die eigentlichen OIB-Event-Receiver
public SetupCenterReceiver SetupCenterReceiver { set; get; }
public SetupCenterExternalControlReceiver SetupCenterExternalControlReceiver { set; get; }
public MonitoringReceiver MonitoringReceiver { set; get; }
public TraceabilityReceiver TraceReceiver { set; get; }
public SpiReceiver SpiReceiver { get; set; }
public ChangeoverReceiver ChangeoverReceiver { get; set; }
public OibClient OibClient { get; set; }
public BoardGateKeeperReceiver BoardGateKeeperReceiver { set; get; }
public bool _isSetupStation;
public List<com.itac.mes.tools.KeyValue> productVersions { get; set; }
public DekPrinterExternalControlReceiver DekPrinterExternalControlReceiver { get; set; }
public LineControlMesInterceptorReceiver MesLineControlMesInterceptorReceiver { get; set; }
public AdapterControl()
{
var config = new AppSettingsReader();
try
{
// Der Port an dem der Adapter auf eingehende Verbindungen des iTAC DataInterface lauscht
_own_itac_oib_adapter_port = (int)config.GetValue("ListenPort", typeof(int));
_own_host_name = Environment.MachineName;
var hostInfo = Dns.GetHostEntry(_own_host_name);
_own_canonical_host_name = hostInfo.HostName;
var addresslist = Dns.GetHostAddresses(_own_host_name);
// die eigene IP-Adresse raussuchen
var theaddress = addresslist[0];
// jetzt versuchen eine gueltige V4 Adresse zu finden, diese bevorzugen
foreach (var IPA in addresslist)
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
theaddress = IPA;
break;
}
}
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, theaddress.ToString());
_own_ip_address = theaddress.ToString();
}
catch (Exception)
{
}
}
// eine neue socket zum DataInterface als Client aufmachen. ?ber diese Verbindung werden alle Events zum
// Datainterface ?bertragen
// Returned nie einen Null-Wert
public IhapEventChannel GetDataInterfaceConnection(string channelName)
{
// sind die n?tigen Parameter gesetzt (_ipAddress, _hostname), damit eine Verbindung aufgebaut werden kann?
if (_ipAddress.Equals("") || _hostName.Equals("") || _canonicalHostName.Equals(""))
{
//Fehlerausgabe
LogHandler.log(Constants.LOGGER, TraceEventType.Critical, "ADAPTER: communication parameter unknown:\n" +
"DataInterface IP Address = " + _ipAddress + "\n" +
"DataInterface Host Name = " + _hostName + "\n" +
"DataInterface Canonical Host Name = " + _canonicalHostName + "\n");
// Ende
throw new Exception("iTAC.OIB.Adapter is not configured properly");
}
// F?r jeden Kanal eine neue eigene Verbindung aufmachen. Pro Verbindung eine laufende Nummer z?hlen...
var channelNameWithNumber = "";
// gab es f?r diesen channelName bereits eine Connection
var counter = 0;
lock (_locker)
{
if (channelNameCounter.ContainsKey(channelName))
{
counter = channelNameCounter[channelName];
counter++;
if (counter > 100000) { counter = 1; }
channelNameCounter.Remove(channelName);
channelNameCounter.Add(channelName, counter);
}
else
{
channelNameCounter.Add(channelName, counter);
}
channelNameWithNumber = channelName + "#" + counter;
}
// Neue Verbindung zum DataInterface aufmachen
var tcpClient = new TcpClient(_canonicalHostName, _port);
// eine neue TCp-Client-Verbindung
var iHapEventChannel = new IhapEventChannel(tcpClient, channelNameWithNumber);
if (iHapEventChannel == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "ADAPTER: iHapEventChannel not created");
throw new Exception("ADAPTER: iHapEventChannel not created");
}
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: before adding " + channelNameWithNumber);
lock (_locker)
{
if (openClientChannels.ContainsKey(channelNameWithNumber))
{
openClientChannels.Remove(channelNameWithNumber);
}
openClientChannels.Add(channelNameWithNumber, iHapEventChannel);
}
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: " + channelNameWithNumber + " added");
iHapEventChannel.channelName = channelNameWithNumber;
// Listener installieren, um zu reagieren, wenn das Data-Interface die Verbindung abgebrochen hat
iHapEventChannel.connectionStateChangeListener += new PropertyChangeListener(iHapEventChannel_connectionStateChangeListener);
var oibEvents = (OIBEvents)iHapEventChannel.GetTransparentProxy();
if (oibEvents == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Error, "ADAPTER: iHapEventChannel.transparentProxy not created");
throw new Exception("ADAPTER: iHapEventChannel.transparentProxy not created");
}
oibEvents.setChannelName(channelNameWithNumber);
oibEvents.startup();
return iHapEventChannel;
}
#region IAdapterControl Member
/// <summary>
/// subscriptions starten
/// </summary>
public void startMonitoringReceiver()
{
genericStart("Monitoring Receiver", MonitoringReceiver);
}
/// <summary>
/// subscriptions anhalten und austragen
/// </summary>
public void stopMonitoringReceiver()
{
genericStop("Monitoring Receiver", MonitoringReceiver);
}
public void startSetupCenterNotifyReceiver()
{
genericStart("SetupCenterReceiver", SetupCenterReceiver);
genericStart("SetupCenterExternalControlReceiver", SetupCenterExternalControlReceiver);
genericStart("DekPrinterExternalControlReceiver", DekPrinterExternalControlReceiver);
genericStart("MesLineControlMesInterceptorReceiver", MesLineControlMesInterceptorReceiver);
}
public void stopSetupCenterNotifyReceiver()
{
genericStop("SetupCenterReceiver", SetupCenterReceiver);
genericStop("SetupCenterExternalControlReceiver", SetupCenterExternalControlReceiver);
genericStop("DekPrinterExternalControlReceiver", DekPrinterExternalControlReceiver);
genericStop("MesLineControlMesInterceptorReceiver", MesLineControlMesInterceptorReceiver);
}
/// <summary>
/// subscriptions starten
/// </summary>
public void startTraceReceiver()
{
genericStart("TraceReceiver", TraceReceiver);
}
/// <summary>
/// subscriptions anhalten und austragen
/// </summary>
public void stopTraceReceiver()
{
genericStop("TraceReceiver", TraceReceiver);
}
/// <summary>
/// subscriptions starten
/// </summary>
public void startBoardGateKeeper()
{
genericStart("BoardGateKeeperReceiver", BoardGateKeeperReceiver);
}
/// <summary>
/// subscriptions anhalten und austragen
/// </summary>
public void stopBoardGateKeeper()
{
genericStop("BoardGateKeeperReceiver", BoardGateKeeperReceiver);
}
public void startDekReceiver()
{
genericStart("DekPrinterExternalControlReceiver", DekPrinterExternalControlReceiver);
genericStart("MesLineControlMesInterceptorReceiver", MesLineControlMesInterceptorReceiver);
}
public void stopDekReceiver()
{
genericStop("DekPrinterExternalControlReceiver", DekPrinterExternalControlReceiver);
genericStop("MesLineControlMesInterceptorReceiver", MesLineControlMesInterceptorReceiver);
}
public bool ping()
{
LogHandler.log(Constants.LOGGER, TraceEventType.Information, "ADAPTER: ping");
return true;
}
public bool isSetupStation()
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: isSetupStation()");
return _isSetupStation;
}
public void setInterfaceHost(int port, string ipAddress, string canonicalHostName, string hostName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: setInterfaceHost() called");
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: set DataInterface port: " + port);
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: set DataInterface ipAddress: " + ipAddress);
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: set DataInterface canonical hostname : " + canonicalHostName);
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: set DataInterface hostname : " + hostName);
// setzen der Parameter ist immer moeglich, wenn die Parameter noch nicht gesetzt wurden.
if (_port != 0 && !_hostName.Equals(""))
{
// eine Änderung des Hostnamen ist nicht erlaubt, so lange der AdapterProzess besteht.
if (!_hostName.Equals(hostName) || !_ipAddress.Equals(ipAddress) || !_canonicalHostName.Equals(canonicalHostName))
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: current port: " + _port + ": new port :" + port);
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: current ipAddress: " + _ipAddress + ": new ipAddress :" + ipAddress);
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: current canonical hostname : " + _canonicalHostName + ": new canonical hostname : " + canonicalHostName);
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: current hostname : " + _hostName + ": new hostname:" + hostName);
LogHandler.log(Constants.LOGGER, TraceEventType.Warning, "ADAPTER: changing DataInterface communication parameter not allowed and not changed");
return;
}
}
_port = port;
_ipAddress = ipAddress;
_hostName = hostName;
_canonicalHostName = canonicalHostName;
try
{
IhapEventChannel interfaceControlChannel = GetDataInterfaceConnection("interfaceControlChannel");
// die Methode "DataInterfaceShutdown" wird aufgerufen, wenn das Interface diese Clientverbindung abbricht
// hierf?r wird ein zus?tzlicher Handler installiert
// interfaceControlChannel.connectionStateChangeListener += new PropertyChangeListener(DataInterfaceShutdown);
//interfaceControlChannel.connectionStateChangeListener += new PropertyChangeListener(iHapEventChannel_connectionStateChangeListener);
var channel = (OIBEvents)interfaceControlChannel.GetTransparentProxy();
channel.RegisterAdapter(_own_itac_oib_adapter_port, _own_ip_address, _own_canonical_host_name, _own_host_name);
var versions = OibClient.GetOibProxyVersions();
var versionList = new List<KeyValue>();
foreach (var version in productVersions)
{
versionList.Add(version);
}
foreach (var version in versions)
{
if (version.Key.Equals("AsmApi")) { continue; }
versionList.Add(new KeyValue() { key = version.Key, value = version.Value });
}
channel.setVersionInfo(versionList.ToArray());
closeHandler(channel);
}
catch (Exception e)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: setInterfaceHost() call failed", e);
}
}
public void setChannelName(string channelName)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: setting channel name(" + channelName + ")");
}
#endregion
// die Verbindung zum DataInterface aktiv abbauen
internal void closeChannel(IhapEventChannel eventChannel)
{
lock (_locker)
{
openClientChannels.Remove(eventChannel.channelName);
eventChannel.shutdown();
}
}
// die eingehende Verbindung aktiv schliessen
internal void closeHandler(OIBEvents eventHandler)
{
eventHandler.shutdown();
}
// Listener f?r ausgehende Verbindungen; wird aufgerufen, wenn f?r eine ausgehende Verbindung das schreiben fehlschl?gt (also durch das
// DataInterface die Verbindung abgebrochen wurde
internal void iHapEventChannel_connectionStateChangeListener(Object source, string channelName, string message)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: " + channelName + " " + message);
closeChannel((IhapEventChannel)source);
if (openClientChannels.Count > 0)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "shutdown " + openClientChannels.Count + " remaining open connections from iTAC.OIB.Adpater to DataInterface");
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "no remaining open connections from iTAC.OIB.Adpater to DataInterface");
}
}
// Wenn ein IHapHandler ein Disconnect feststellt wird eine Verbindung entfernt...
public void DataInterfaceShutdown(object sender, string channelName, string message)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, channelName + " disconnected");
_port = 0;
_ipAddress = "";
_canonicalHostName = "";
_hostName = "";
// alle client-Verbindungen muessen abgebaut werden...
if (openClientChannels.Count > 0)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "shutdown " + openClientChannels.Count + " remaining open connections from iTAC.OIB.Adpater to DataInterface");
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "no remaining open connections from iTAC.OIB.Adpater to DataInterface");
}
// ge?ffnete Eventing Queues stoppen
stopMonitoringReceiver();
stopSetupCenterNotifyReceiver();
}
protected void genericStop(String serviceName, IReceiver service)
{
if (service == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: " + serviceName + " will not be stopped because it was not initialized");
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: Stop " + serviceName + "");
service.Stop();
}
}
public void genericStart(String serviceName, IReceiver service)
{
if (service == null)
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: " + serviceName + " will not be started because it was not initialized");
}
else
{
LogHandler.log(Constants.LOGGER, TraceEventType.Verbose, "ADAPTER: Start " + serviceName + "");
service.Start();
}
}
public void Dispose()
{
if (SetupCenterReceiver != null)
SetupCenterReceiver.Dispose();
if (SetupCenterExternalControlReceiver != null)
SetupCenterExternalControlReceiver.Dispose();
if (MonitoringReceiver != null)
MonitoringReceiver.Dispose();
if (TraceReceiver != null)
TraceReceiver.Dispose();
if (SpiReceiver != null)
SpiReceiver.Dispose();
if (BoardGateKeeperReceiver != null)
BoardGateKeeperReceiver.Dispose();
}
}
}

View File

@@ -0,0 +1,74 @@
namespace com.itac.oib
{
// remote-Methoden zum testen der Anwendung...
public interface IAdapterControl
{
//bool addEventFilter(string filterExpr);
//void clearFilter();
void startSetupCenterNotifyReceiver();
void stopSetupCenterNotifyReceiver();
/// <summary>
/// subscriptions starten
/// </summary>
void startMonitoringReceiver();
/// <summary>
/// subscriptions anhalten und austragen
/// </summary>
void stopMonitoringReceiver();
/// <summary>
/// subscriptions starten
/// </summary>
void startTraceReceiver();
/// <summary>
/// subscriptions anhalten und austragen
/// </summary>
void stopTraceReceiver();
/// <summary>
/// subscriptions starten
/// </summary>
void startBoardGateKeeper();
/// <summary>
/// subscriptions anhalten und austragen
/// </summary>
void stopBoardGateKeeper();
/// <summary>
/// subscriptions starten
/// </summary>
void startDekReceiver();
/// <summary>
/// subscriptions anhalten und austragen
/// </summary>
void stopDekReceiver();
bool ping();
/// <summary>
/// liefert true, wenn dieser Adapter für eine SetupStation (Vorrüstplatz) konfiguriert ist.
/// In diesem Fall muss die Client Applikation beim start keine Board Daten lesen
/// </summary>
/// <returns></returns>
bool isSetupStation();
/// <summary>
/// dem Adapter die Interface-Konfiguration mitteilen
/// </summary>
/// @param ipAddress
/// die Adresse, auf der das Interface zu erreichen ist
/// @param hostName
/// der host, auf dem das Interface zu erreichen ist
void setInterfaceHost(int port, string ipAddress, string canonicalHostName, string hostName);
void setChannelName(string channelName);
}
}

View File

@@ -0,0 +1,26 @@
namespace com.itac.oib
{
//public class KeyValue
//{
// public string key { get; set; }
// public string value { get; set; }
//}
// Meldungen, die der Adapter an das DataInterface senden kann
public interface IAdapterNotify
{
// Diese Nachricht wird immer dann vom iTAC.OIB.Adapter zum DataInterface gesendet, wenn eine MessageQueue durch den Adapter neu gestartet wurde.
void MessageQueueRestartet(string queueEndpoint);
void SendQueueInfo(QueueInfo queueInfo);
// wenn der iTAC.OIB.Adapter vom DataInterface angesprochen wird und eine neue Konfiguration erhält
// (Endpunkt/Port, wo das Interface zu finden ist) schickt der Adapter eine Meldung an das Interface wo er selbst zu finden ist.
void RegisterAdapter(int port, string ipAddress, string canonicalHostName, string hostName);
void shutdown();
void setChannelName(string channelName);
void startup();
void setVersionInfo(com.itac.mes.tools.KeyValue[] keyValueArray);
}
}

View File

@@ -0,0 +1,10 @@
namespace com.itac.oib
{
public class QueueInfo
{
public int OutStandingMessages { get; set; }
public string Status { get; set; }
public string QueueName { get; set; }
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB