This commit is contained in:
luosheng
2023-07-12 06:42:28 +08:00
parent 25555cad18
commit db591e0367
188 changed files with 56088 additions and 9 deletions

View File

@@ -20,7 +20,7 @@
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<IncludeSymbols>True</IncludeSymbols>
<IncludeSource>True</IncludeSource>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<Platforms>AnyCPU</Platforms>

View File

@@ -101,14 +101,23 @@ namespace Modbus.Net.Opc
{
resultTrans = (byte)0;
}
else if (result.Value.ToString() == "True")
else if (result.Value?.ToString() == "True")
{
resultTrans = (byte)1;
}
else
else if (result.Value != null)
{
resultTrans = result.Value;
}
else
{
logger.LogError($"Opc Machine {ConnectionToken} Read Opc tag {tag} for value null");
return new OpcParamOut
{
Success = false,
Value = Encoding.ASCII.GetBytes("NoData")
};
}
logger.LogInformation($"Opc Machine {ConnectionToken} Read Opc tag {tag} for value {result.Value} {result.Value.GetType().FullName}");
return new OpcParamOut
{
@@ -116,6 +125,7 @@ namespace Modbus.Net.Opc
Value = BigEndianLsbValueHelper.Instance.GetBytes(resultTrans, resultTrans.GetType())
};
}
logger.LogError($"Opc Machine {ConnectionToken} Read Opc tag null");
return new OpcParamOut
{
Success = false,
@@ -156,6 +166,7 @@ namespace Modbus.Net.Opc
catch (Exception e)
{
logger.LogError(e, "Opc client {ConnectionToken} read exception", ConnectionToken);
Disconnect();
return new OpcParamOut
{
Success = false,

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Modbus.Net.Opc
{
@@ -19,7 +20,6 @@ namespace Modbus.Net.Opc
/// <param name="host">Opc DA 服务地址</param>
protected OpcDaConnector(string host) : base(host)
{
Client = new MyDaClient(new Uri(ConnectionToken));
}
/// <summary>
@@ -36,5 +36,12 @@ namespace Modbus.Net.Opc
}
return _instances[host];
}
/// <inheritdoc />
public override Task<bool> ConnectAsync()
{
if (Client == null) Client = new MyDaClient(new Uri(ConnectionToken));
return base.ConnectAsync();
}
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Modbus.Net.Opc
{
@@ -19,7 +20,6 @@ namespace Modbus.Net.Opc
/// <param name="host">Opc UA 服务地址</param>
protected OpcUaConnector(string host) : base(host)
{
Client = new MyUaClient(new Uri(ConnectionToken));
}
/// <summary>
@@ -36,5 +36,12 @@ namespace Modbus.Net.Opc
}
return _instances[host];
}
/// <inheritdoc />
public override Task<bool> ConnectAsync()
{
if (Client == null) Client = new MyUaClient(new Uri(ConnectionToken));
return base.ConnectAsync();
}
}
}

View File

@@ -7,6 +7,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Modbus.Net", "Modbus.Net\Mo
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{64472271-8B95-4036-ACF9-C10941C1DB0A}"
ProjectSection(SolutionItems) = preProject
..\LICENSE = ..\LICENSE
..\README.md = ..\README.md
EndProjectSection
EndProject
@@ -38,64 +39,148 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "h-opc", "..\h-opc\h-opc\h-o
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Modbus.Net.BigEndian3412", "Modbus.Net.BigEndian3412\Modbus.Net.BigEndian3412.csproj", "{D48D4F79-1DA2-4C91-A9EE-FDCAEC09E808}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Technosoftware.OpcRcw", "..\Technosoftware\OpcRcw\Technosoftware.OpcRcw.csproj", "{7689CBF8-1992-467D-AD45-E1464F705220}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Technosoftware.DaAeHdaClient", "..\Technosoftware\DaAeHdaClient\Technosoftware.DaAeHdaClient.csproj", "{116160B2-7D6D-40A2-839C-7997BC0E1A0C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Technosoftware.DaAeHdaClient.Com", "..\Technosoftware\DaAeHdaClient.Com\Technosoftware.DaAeHdaClient.Com.csproj", "{ACAF0A16-FC51-4369-BFA8-484FF20707D7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{124EBEF2-8960-4447-84CF-1D683B1EF7CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{124EBEF2-8960-4447-84CF-1D683B1EF7CC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{124EBEF2-8960-4447-84CF-1D683B1EF7CC}.Debug|x64.ActiveCfg = Debug|Any CPU
{124EBEF2-8960-4447-84CF-1D683B1EF7CC}.Debug|x64.Build.0 = Debug|Any CPU
{124EBEF2-8960-4447-84CF-1D683B1EF7CC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{124EBEF2-8960-4447-84CF-1D683B1EF7CC}.Release|Any CPU.Build.0 = Release|Any CPU
{124EBEF2-8960-4447-84CF-1D683B1EF7CC}.Release|x64.ActiveCfg = Release|Any CPU
{124EBEF2-8960-4447-84CF-1D683B1EF7CC}.Release|x64.Build.0 = Release|Any CPU
{FDCA72BA-6D06-4DE0-B873-C11C4AC853AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FDCA72BA-6D06-4DE0-B873-C11C4AC853AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FDCA72BA-6D06-4DE0-B873-C11C4AC853AD}.Debug|x64.ActiveCfg = Debug|Any CPU
{FDCA72BA-6D06-4DE0-B873-C11C4AC853AD}.Debug|x64.Build.0 = Debug|Any CPU
{FDCA72BA-6D06-4DE0-B873-C11C4AC853AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FDCA72BA-6D06-4DE0-B873-C11C4AC853AD}.Release|Any CPU.Build.0 = Release|Any CPU
{FDCA72BA-6D06-4DE0-B873-C11C4AC853AD}.Release|x64.ActiveCfg = Release|Any CPU
{FDCA72BA-6D06-4DE0-B873-C11C4AC853AD}.Release|x64.Build.0 = Release|Any CPU
{6258F9D9-0DF4-497F-9F3B-6D2F6F752A21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6258F9D9-0DF4-497F-9F3B-6D2F6F752A21}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6258F9D9-0DF4-497F-9F3B-6D2F6F752A21}.Debug|x64.ActiveCfg = Debug|Any CPU
{6258F9D9-0DF4-497F-9F3B-6D2F6F752A21}.Debug|x64.Build.0 = Debug|Any CPU
{6258F9D9-0DF4-497F-9F3B-6D2F6F752A21}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6258F9D9-0DF4-497F-9F3B-6D2F6F752A21}.Release|Any CPU.Build.0 = Release|Any CPU
{6258F9D9-0DF4-497F-9F3B-6D2F6F752A21}.Release|x64.ActiveCfg = Release|Any CPU
{6258F9D9-0DF4-497F-9F3B-6D2F6F752A21}.Release|x64.Build.0 = Release|Any CPU
{3BB01E98-3D45-454A-A1BD-49D7B2C83B74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3BB01E98-3D45-454A-A1BD-49D7B2C83B74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3BB01E98-3D45-454A-A1BD-49D7B2C83B74}.Debug|x64.ActiveCfg = Debug|Any CPU
{3BB01E98-3D45-454A-A1BD-49D7B2C83B74}.Debug|x64.Build.0 = Debug|Any CPU
{3BB01E98-3D45-454A-A1BD-49D7B2C83B74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3BB01E98-3D45-454A-A1BD-49D7B2C83B74}.Release|Any CPU.Build.0 = Release|Any CPU
{3BB01E98-3D45-454A-A1BD-49D7B2C83B74}.Release|x64.ActiveCfg = Release|Any CPU
{3BB01E98-3D45-454A-A1BD-49D7B2C83B74}.Release|x64.Build.0 = Release|Any CPU
{22A35CA8-CDCF-416D-BA84-08C933B4A3DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{22A35CA8-CDCF-416D-BA84-08C933B4A3DE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{22A35CA8-CDCF-416D-BA84-08C933B4A3DE}.Debug|x64.ActiveCfg = Debug|Any CPU
{22A35CA8-CDCF-416D-BA84-08C933B4A3DE}.Debug|x64.Build.0 = Debug|Any CPU
{22A35CA8-CDCF-416D-BA84-08C933B4A3DE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{22A35CA8-CDCF-416D-BA84-08C933B4A3DE}.Release|Any CPU.Build.0 = Release|Any CPU
{22A35CA8-CDCF-416D-BA84-08C933B4A3DE}.Release|x64.ActiveCfg = Release|Any CPU
{22A35CA8-CDCF-416D-BA84-08C933B4A3DE}.Release|x64.Build.0 = Release|Any CPU
{D4AF0E1E-676E-43B6-BAA3-BFC329D68C80}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4AF0E1E-676E-43B6-BAA3-BFC329D68C80}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4AF0E1E-676E-43B6-BAA3-BFC329D68C80}.Debug|x64.ActiveCfg = Debug|Any CPU
{D4AF0E1E-676E-43B6-BAA3-BFC329D68C80}.Debug|x64.Build.0 = Debug|Any CPU
{D4AF0E1E-676E-43B6-BAA3-BFC329D68C80}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4AF0E1E-676E-43B6-BAA3-BFC329D68C80}.Release|Any CPU.Build.0 = Release|Any CPU
{D4AF0E1E-676E-43B6-BAA3-BFC329D68C80}.Release|x64.ActiveCfg = Release|Any CPU
{D4AF0E1E-676E-43B6-BAA3-BFC329D68C80}.Release|x64.Build.0 = Release|Any CPU
{1857DA63-3335-428F-84D8-1FA4F8178643}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1857DA63-3335-428F-84D8-1FA4F8178643}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1857DA63-3335-428F-84D8-1FA4F8178643}.Debug|x64.ActiveCfg = Debug|Any CPU
{1857DA63-3335-428F-84D8-1FA4F8178643}.Debug|x64.Build.0 = Debug|Any CPU
{1857DA63-3335-428F-84D8-1FA4F8178643}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1857DA63-3335-428F-84D8-1FA4F8178643}.Release|Any CPU.Build.0 = Release|Any CPU
{1857DA63-3335-428F-84D8-1FA4F8178643}.Release|x64.ActiveCfg = Release|Any CPU
{1857DA63-3335-428F-84D8-1FA4F8178643}.Release|x64.Build.0 = Release|Any CPU
{C854A379-C5EA-4CAC-9C5F-7291372D1D3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C854A379-C5EA-4CAC-9C5F-7291372D1D3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C854A379-C5EA-4CAC-9C5F-7291372D1D3F}.Debug|x64.ActiveCfg = Debug|Any CPU
{C854A379-C5EA-4CAC-9C5F-7291372D1D3F}.Debug|x64.Build.0 = Debug|Any CPU
{C854A379-C5EA-4CAC-9C5F-7291372D1D3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C854A379-C5EA-4CAC-9C5F-7291372D1D3F}.Release|Any CPU.Build.0 = Release|Any CPU
{C854A379-C5EA-4CAC-9C5F-7291372D1D3F}.Release|x64.ActiveCfg = Release|Any CPU
{C854A379-C5EA-4CAC-9C5F-7291372D1D3F}.Release|x64.Build.0 = Release|Any CPU
{AA3A42D2-0502-41D3-929A-BAB729DF07D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AA3A42D2-0502-41D3-929A-BAB729DF07D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AA3A42D2-0502-41D3-929A-BAB729DF07D6}.Debug|x64.ActiveCfg = Debug|Any CPU
{AA3A42D2-0502-41D3-929A-BAB729DF07D6}.Debug|x64.Build.0 = Debug|Any CPU
{AA3A42D2-0502-41D3-929A-BAB729DF07D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AA3A42D2-0502-41D3-929A-BAB729DF07D6}.Release|Any CPU.Build.0 = Release|Any CPU
{AA3A42D2-0502-41D3-929A-BAB729DF07D6}.Release|x64.ActiveCfg = Release|Any CPU
{AA3A42D2-0502-41D3-929A-BAB729DF07D6}.Release|x64.Build.0 = Release|Any CPU
{414956B8-DBD4-414C-ABD3-565580739646}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{414956B8-DBD4-414C-ABD3-565580739646}.Debug|Any CPU.Build.0 = Debug|Any CPU
{414956B8-DBD4-414C-ABD3-565580739646}.Debug|x64.ActiveCfg = Debug|Any CPU
{414956B8-DBD4-414C-ABD3-565580739646}.Debug|x64.Build.0 = Debug|Any CPU
{414956B8-DBD4-414C-ABD3-565580739646}.Release|Any CPU.ActiveCfg = Release|Any CPU
{414956B8-DBD4-414C-ABD3-565580739646}.Release|Any CPU.Build.0 = Release|Any CPU
{414956B8-DBD4-414C-ABD3-565580739646}.Release|x64.ActiveCfg = Release|Any CPU
{414956B8-DBD4-414C-ABD3-565580739646}.Release|x64.Build.0 = Release|Any CPU
{C4FA55AF-80ED-4467-948F-8EF865C8A5A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C4FA55AF-80ED-4467-948F-8EF865C8A5A5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C4FA55AF-80ED-4467-948F-8EF865C8A5A5}.Debug|x64.ActiveCfg = Debug|Any CPU
{C4FA55AF-80ED-4467-948F-8EF865C8A5A5}.Debug|x64.Build.0 = Debug|Any CPU
{C4FA55AF-80ED-4467-948F-8EF865C8A5A5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C4FA55AF-80ED-4467-948F-8EF865C8A5A5}.Release|Any CPU.Build.0 = Release|Any CPU
{C4FA55AF-80ED-4467-948F-8EF865C8A5A5}.Release|x64.ActiveCfg = Release|Any CPU
{C4FA55AF-80ED-4467-948F-8EF865C8A5A5}.Release|x64.Build.0 = Release|Any CPU
{DC6425E4-1409-488D-A014-4DCC909CF542}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DC6425E4-1409-488D-A014-4DCC909CF542}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC6425E4-1409-488D-A014-4DCC909CF542}.Debug|x64.ActiveCfg = Debug|Any CPU
{DC6425E4-1409-488D-A014-4DCC909CF542}.Debug|x64.Build.0 = Debug|Any CPU
{DC6425E4-1409-488D-A014-4DCC909CF542}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DC6425E4-1409-488D-A014-4DCC909CF542}.Release|Any CPU.Build.0 = Release|Any CPU
{DC6425E4-1409-488D-A014-4DCC909CF542}.Release|x64.ActiveCfg = Release|Any CPU
{DC6425E4-1409-488D-A014-4DCC909CF542}.Release|x64.Build.0 = Release|Any CPU
{D48D4F79-1DA2-4C91-A9EE-FDCAEC09E808}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D48D4F79-1DA2-4C91-A9EE-FDCAEC09E808}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D48D4F79-1DA2-4C91-A9EE-FDCAEC09E808}.Debug|x64.ActiveCfg = Debug|Any CPU
{D48D4F79-1DA2-4C91-A9EE-FDCAEC09E808}.Debug|x64.Build.0 = Debug|Any CPU
{D48D4F79-1DA2-4C91-A9EE-FDCAEC09E808}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D48D4F79-1DA2-4C91-A9EE-FDCAEC09E808}.Release|Any CPU.Build.0 = Release|Any CPU
{D48D4F79-1DA2-4C91-A9EE-FDCAEC09E808}.Release|x64.ActiveCfg = Release|Any CPU
{D48D4F79-1DA2-4C91-A9EE-FDCAEC09E808}.Release|x64.Build.0 = Release|Any CPU
{7689CBF8-1992-467D-AD45-E1464F705220}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7689CBF8-1992-467D-AD45-E1464F705220}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7689CBF8-1992-467D-AD45-E1464F705220}.Debug|x64.ActiveCfg = Debug|x64
{7689CBF8-1992-467D-AD45-E1464F705220}.Debug|x64.Build.0 = Debug|x64
{7689CBF8-1992-467D-AD45-E1464F705220}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7689CBF8-1992-467D-AD45-E1464F705220}.Release|Any CPU.Build.0 = Release|Any CPU
{7689CBF8-1992-467D-AD45-E1464F705220}.Release|x64.ActiveCfg = Release|x64
{7689CBF8-1992-467D-AD45-E1464F705220}.Release|x64.Build.0 = Release|x64
{116160B2-7D6D-40A2-839C-7997BC0E1A0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{116160B2-7D6D-40A2-839C-7997BC0E1A0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{116160B2-7D6D-40A2-839C-7997BC0E1A0C}.Debug|x64.ActiveCfg = Debug|Any CPU
{116160B2-7D6D-40A2-839C-7997BC0E1A0C}.Debug|x64.Build.0 = Debug|Any CPU
{116160B2-7D6D-40A2-839C-7997BC0E1A0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{116160B2-7D6D-40A2-839C-7997BC0E1A0C}.Release|Any CPU.Build.0 = Release|Any CPU
{116160B2-7D6D-40A2-839C-7997BC0E1A0C}.Release|x64.ActiveCfg = Release|Any CPU
{116160B2-7D6D-40A2-839C-7997BC0E1A0C}.Release|x64.Build.0 = Release|Any CPU
{ACAF0A16-FC51-4369-BFA8-484FF20707D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ACAF0A16-FC51-4369-BFA8-484FF20707D7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ACAF0A16-FC51-4369-BFA8-484FF20707D7}.Debug|x64.ActiveCfg = Debug|x64
{ACAF0A16-FC51-4369-BFA8-484FF20707D7}.Debug|x64.Build.0 = Debug|x64
{ACAF0A16-FC51-4369-BFA8-484FF20707D7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ACAF0A16-FC51-4369-BFA8-484FF20707D7}.Release|Any CPU.Build.0 = Release|Any CPU
{ACAF0A16-FC51-4369-BFA8-484FF20707D7}.Release|x64.ActiveCfg = Release|x64
{ACAF0A16-FC51-4369-BFA8-484FF20707D7}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -506,7 +506,7 @@ namespace Modbus.Net
_taskCancel = true;
}
private void ReceiveMessage()
private async Task ReceiveMessage()
{
while (!_taskCancel)
{
@@ -549,9 +549,19 @@ namespace Modbus.Net
CacheBytes.RemoveRange(0, confirmed.Item1.Length);
}
}
else if (confirmed.Item2 == false)
else
{
lock (CacheBytes)
{
CacheBytes.RemoveRange(0, confirmed.Item1.Length);
}
var sendMessage = InvokeReturnMessage(confirmed.Item1);
//主动传输事件
if (sendMessage != null)
{
await SendMsgWithoutConfirm(sendMessage);
}
}
}
}

View File

@@ -0,0 +1,876 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Runtime.InteropServices;
using Technosoftware.DaAeHdaClient.Ae;
using Technosoftware.DaAeHdaClient.Da;
#endregion
#pragma warning disable 0618
namespace Technosoftware.DaAeHdaClient.Com.Ae
{
/// <summary>
/// Defines COM marshalling/unmarshalling functions for AE.
/// </summary>
internal class Interop
{
/// <summary>
/// Converts a standard FILETIME to an OpcRcw.Ae.FILETIME structure.
/// </summary>
internal static OpcRcw.Ae.FILETIME Convert(FILETIME input)
{
var output = new OpcRcw.Ae.FILETIME();
output.dwLowDateTime = input.dwLowDateTime;
output.dwHighDateTime = input.dwHighDateTime;
return output;
}
/// <summary>
/// Converts an OpcRcw.Ae.FILETIME to a standard FILETIME structure.
/// </summary>
internal static FILETIME Convert(OpcRcw.Ae.FILETIME input)
{
var output = new FILETIME();
output.dwLowDateTime = input.dwLowDateTime;
output.dwHighDateTime = input.dwHighDateTime;
return output;
}
/// <summary>
/// Converts the HRESULT to a system type.
/// </summary>
internal static OpcResult GetResultID(int input)
{
// must check for this error because of a code collision with a DA code.
if (input == Result.E_INVALIDBRANCHNAME)
{
return OpcResult.Ae.E_INVALIDBRANCHNAME;
}
return Technosoftware.DaAeHdaClient.Com.Interop.GetResultID(input);
}
/// <summary>
/// Unmarshals and deallocates a OPCEVENTSERVERSTATUS structure.
/// </summary>
internal static OpcServerStatus GetServerStatus(ref IntPtr pInput, bool deallocate)
{
OpcServerStatus output = null;
if (pInput != IntPtr.Zero)
{
var status = (OpcRcw.Ae.OPCEVENTSERVERSTATUS)Marshal.PtrToStructure(pInput, typeof(OpcRcw.Ae.OPCEVENTSERVERSTATUS));
output = new OpcServerStatus();
output.VendorInfo = status.szVendorInfo;
output.ProductVersion = string.Format("{0}.{1}.{2}", status.wMajorVersion, status.wMinorVersion, status.wBuildNumber);
output.MajorVersion = status.wMajorVersion;
output.MinorVersion = status.wMinorVersion;
output.BuildNumber = status.wBuildNumber;
output.ServerState = (OpcServerState)status.dwServerState;
output.StatusInfo = null;
output.StartTime = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(status.ftStartTime));
output.CurrentTime = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(status.ftCurrentTime));
output.LastUpdateTime = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(status.ftLastUpdateTime));
if (deallocate)
{
Marshal.DestroyStructure(pInput, typeof(OpcRcw.Ae.OPCEVENTSERVERSTATUS));
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Converts a NodeType value to the OPCAEBROWSETYPE equivalent.
/// </summary>
internal static OpcRcw.Ae.OPCAEBROWSETYPE GetBrowseType(TsCAeBrowseType input)
{
switch (input)
{
case TsCAeBrowseType.Area: return OpcRcw.Ae.OPCAEBROWSETYPE.OPC_AREA;
case TsCAeBrowseType.Source: return OpcRcw.Ae.OPCAEBROWSETYPE.OPC_SOURCE;
}
return OpcRcw.Ae.OPCAEBROWSETYPE.OPC_AREA;
}
/// <summary>
/// Converts an array of ONEVENTSTRUCT structs to an array of EventNotification objects.
/// </summary>
internal static TsCAeEventNotification[] GetEventNotifications(OpcRcw.Ae.ONEVENTSTRUCT[] input)
{
TsCAeEventNotification[] output = null;
if (input != null && input.Length > 0)
{
output = new TsCAeEventNotification[input.Length];
for (var ii = 0; ii < input.Length; ii++)
{
output[ii] = GetEventNotification(input[ii]);
}
}
return output;
}
/// <summary>
/// Converts a ONEVENTSTRUCT struct to a EventNotification object.
/// </summary>
internal static TsCAeEventNotification GetEventNotification(OpcRcw.Ae.ONEVENTSTRUCT input)
{
var output = new TsCAeEventNotification();
output.SourceID = input.szSource;
output.Time = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(input.ftTime));
output.Severity = input.dwSeverity;
output.Message = input.szMessage;
output.EventType = (TsCAeEventType)input.dwEventType;
output.EventCategory = input.dwEventCategory;
output.ChangeMask = input.wChangeMask;
output.NewState = input.wNewState;
output.Quality = new TsCDaQuality(input.wQuality);
output.ConditionName = input.szConditionName;
output.SubConditionName = input.szSubconditionName;
output.AckRequired = input.bAckRequired != 0;
output.ActiveTime = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(input.ftActiveTime));
output.Cookie = input.dwCookie;
output.ActorID = input.szActorID;
var attributes = Technosoftware.DaAeHdaClient.Com.Interop.GetVARIANTs(ref input.pEventAttributes, input.dwNumEventAttrs, false);
output.SetAttributes(attributes);
return output;
}
/// <summary>
/// Converts an array of OPCCONDITIONSTATE structs to an array of Condition objects.
/// </summary>
internal static TsCAeCondition[] GetConditions(ref IntPtr pInput, int count, bool deallocate)
{
TsCAeCondition[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new TsCAeCondition[count];
var pos = pInput;
for (var ii = 0; ii < count; ii++)
{
var condition = (OpcRcw.Ae.OPCCONDITIONSTATE)Marshal.PtrToStructure(pos, typeof(OpcRcw.Ae.OPCCONDITIONSTATE));
output[ii] = new TsCAeCondition();
output[ii].State = condition.wState;
output[ii].Quality = new TsCDaQuality(condition.wQuality);
output[ii].Comment = condition.szComment;
output[ii].AcknowledgerID = condition.szAcknowledgerID;
output[ii].CondLastActive = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(condition.ftCondLastActive));
output[ii].CondLastInactive = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(condition.ftCondLastInactive));
output[ii].SubCondLastActive = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(condition.ftSubCondLastActive));
output[ii].LastAckTime = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(condition.ftLastAckTime));
output[ii].ActiveSubCondition.Name = condition.szActiveSubCondition;
output[ii].ActiveSubCondition.Definition = condition.szASCDefinition;
output[ii].ActiveSubCondition.Severity = condition.dwASCSeverity;
output[ii].ActiveSubCondition.Description = condition.szASCDescription;
// unmarshal sub-conditions.
var names = Technosoftware.DaAeHdaClient.Com.Interop.GetUnicodeStrings(ref condition.pszSCNames, condition.dwNumSCs, deallocate);
var severities = Technosoftware.DaAeHdaClient.Com.Interop.GetInt32s(ref condition.pdwSCSeverities, condition.dwNumSCs, deallocate);
var definitions = Technosoftware.DaAeHdaClient.Com.Interop.GetUnicodeStrings(ref condition.pszSCDefinitions, condition.dwNumSCs, deallocate);
var descriptions = Technosoftware.DaAeHdaClient.Com.Interop.GetUnicodeStrings(ref condition.pszSCDescriptions, condition.dwNumSCs, deallocate);
output[ii].SubConditions.Clear();
if (condition.dwNumSCs > 0)
{
for (var jj = 0; jj < names.Length; jj++)
{
var subcondition = new TsCAeSubCondition();
subcondition.Name = names[jj];
subcondition.Severity = severities[jj];
subcondition.Definition = definitions[jj];
subcondition.Description = descriptions[jj];
output[ii].SubConditions.Add(subcondition);
}
}
// unmarshal attributes.
var values = Technosoftware.DaAeHdaClient.Com.Interop.GetVARIANTs(ref condition.pEventAttributes, condition.dwNumEventAttrs, deallocate);
var errors = Technosoftware.DaAeHdaClient.Com.Interop.GetInt32s(ref condition.pErrors, condition.dwNumEventAttrs, deallocate);
output[ii].Attributes.Clear();
if (condition.dwNumEventAttrs > 0)
{
for (var jj = 0; jj < values.Length; jj++)
{
var attribute = new TsCAeAttributeValue();
attribute.ID = 0;
attribute.Value = values[jj];
attribute.Result = GetResultID(errors[jj]);
output[ii].Attributes.Add(attribute);
}
}
// deallocate structure.
if (deallocate)
{
Marshal.DestroyStructure(pos, typeof(OpcRcw.Ae.OPCCONDITIONSTATE));
}
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Ae.OPCCONDITIONSTATE)));
}
// deallocate array.
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/*
/// <summary>
/// Converts an array of COM HRESULTs structures to .NET ResultID objects.
/// </summary>
internal static ResultID[] GetResultIDs(ref IntPtr pInput, int count, bool deallocate)
{
ResultID[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new ResultID[count];
int[] errors = OpcCom.Interop.GetInt32s(ref pInput, count, deallocate);
for (int ii = 0; ii < count; ii++)
{
output[ii] = OpcCom.Interop.GetResultID(errors[ii]);
}
}
return output;
}
/// <summary>
/// Converts an array of COM SourceServer structures to .NET SourceServer objects.
/// </summary>
internal static SourceServer[] GetSourceServers(ref IntPtr pInput, int count, bool deallocate)
{
SourceServer[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new SourceServer[count];
IntPtr pos = pInput;
for (int ii = 0; ii < count; ii++)
{
OpcRcw.Dx.SourceServer server = (OpcRcw.Dx.SourceServer)Marshal.PtrToStructure(pos, typeof(OpcRcw.Dx.SourceServer));
output[ii] = new SourceServer();
output[ii].ItemName = server.szItemName;
output[ii].ItemPath = server.szItemPath;
output[ii].Version = server.szVersion;
output[ii].Name = server.szName;
output[ii].Description = server.szDescription;
output[ii].ServerType = server.szServerType;
output[ii].ServerURL = server.szServerURL;
output[ii].DefaultConnected = server.bDefaultSourceServerConnected != 0;
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Dx.SourceServer)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Converts an array of .NET SourceServer objects to COM SourceServer structures.
/// </summary>
internal static OpcRcw.Dx.SourceServer[] GetSourceServers(SourceServer[] input)
{
OpcRcw.Dx.SourceServer[] output = null;
if (input != null && input.Length > 0)
{
output = new OpcRcw.Dx.SourceServer[input.Length];
for (int ii = 0; ii < input.Length; ii++)
{
output[ii] = new OpcRcw.Dx.SourceServer();
output[ii].dwMask = (uint)OpcRcw.Dx.Mask.All;
output[ii].szItemName = input[ii].ItemName;
output[ii].szItemPath = input[ii].ItemPath;
output[ii].szVersion = input[ii].Version;
output[ii].szName = input[ii].Name;
output[ii].szDescription = input[ii].Description;
output[ii].szServerType = input[ii].ServerType;
output[ii].szServerURL = input[ii].ServerURL;
output[ii].bDefaultSourceServerConnected = (input[ii].DefaultConnected)?1:0;
}
}
return output;
}
/// <summary>
/// Converts an array of COM DXGeneralResponse structure to a .NET GeneralResponse object.
/// </summary>
internal static GeneralResponse GetGeneralResponse(OpcRcw.Dx.DXGeneralResponse input, bool deallocate)
{
Opc.Dx.IdentifiedResult[] results = Interop.GetIdentifiedResults(ref input.pIdentifiedResults, input.dwCount, deallocate);
return new GeneralResponse(input.szConfigurationVersion, results);
}
/// <summary>
/// Converts an array of COM IdentifiedResult structures to .NET IdentifiedResult objects.
/// </summary>
internal static Opc.Dx.IdentifiedResult[] GetIdentifiedResults(ref IntPtr pInput, int count, bool deallocate)
{
Opc.Dx.IdentifiedResult[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new Opc.Dx.IdentifiedResult[count];
IntPtr pos = pInput;
for (int ii = 0; ii < count; ii++)
{
OpcRcw.Dx.IdentifiedResult result = (OpcRcw.Dx.IdentifiedResult)Marshal.PtrToStructure(pos, typeof(OpcRcw.Dx.IdentifiedResult));
output[ii] = new Opc.Dx.IdentifiedResult();
output[ii].ItemName = result.szItemName;
output[ii].ItemPath = result.szItemPath;
output[ii].Version = result.szVersion;
output[ii].ResultID = OpcCom.Interop.GetResultID(result.hResultCode);
if (deallocate)
{
Marshal.DestroyStructure(pos, typeof(OpcRcw.Dx.IdentifiedResult));
}
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Dx.IdentifiedResult)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Converts an array of COM DXConnection structures to .NET DXConnection objects.
/// </summary>
internal static DXConnection[] GetDXConnections(ref IntPtr pInput, int count, bool deallocate)
{
DXConnection[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new DXConnection[count];
IntPtr pos = pInput;
for (int ii = 0; ii < count; ii++)
{
OpcRcw.Dx.DXConnection connection = (OpcRcw.Dx.DXConnection)Marshal.PtrToStructure(pos, typeof(OpcRcw.Dx.DXConnection));
output[ii] = GetDXConnection(connection, deallocate);
if (deallocate)
{
Marshal.DestroyStructure(pos, typeof(OpcRcw.Dx.DXConnection));
}
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Dx.DXConnection)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Converts an array of .NET DXConnection objects to COM DXConnection structures.
/// </summary>
internal static OpcRcw.Dx.DXConnection[] GetDXConnections(DXConnection[] input)
{
OpcRcw.Dx.DXConnection[] output = null;
if (input != null && input.Length > 0)
{
output = new OpcRcw.Dx.DXConnection[input.Length];
for (int ii = 0; ii < input.Length; ii++)
{
output[ii] = GetDXConnection(input[ii]);
}
}
return output;
}
/// <summary>
/// Converts a .NET DXConnection object to COM DXConnection structure.
/// </summary>
internal static OpcRcw.Dx.DXConnection GetDXConnection(DXConnection input)
{
OpcRcw.Dx.DXConnection output = new OpcRcw.Dx.DXConnection();
// set output default values.
output.dwMask = 0;
output.szItemPath = null;
output.szItemName = null;
output.szVersion = null;
output.dwBrowsePathCount = 0;
output.pszBrowsePaths = IntPtr.Zero;
output.szName = null;
output.szDescription = null;
output.szKeyword = null;
output.bDefaultSourceItemConnected = 0;
output.bDefaultTargetItemConnected = 0;
output.bDefaultOverridden = 0;
output.vDefaultOverrideValue = null;
output.vSubstituteValue = null;
output.bEnableSubstituteValue = 0;
output.szTargetItemPath = null;
output.szTargetItemName = null;
output.szSourceServerName = null;
output.szSourceItemPath = null;
output.szSourceItemName = null;
output.dwSourceItemQueueSize = 0;
output.dwUpdateRate = 0;
output.fltDeadBand = 0;
output.szVendorData = null;
// item name
if (input.ItemName != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.ItemName;
output.szItemName = input.ItemName;
}
// item path
if (input.ItemPath != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.ItemPath;
output.szItemPath = input.ItemPath;
}
// version
if (input.Version != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.Version;
output.szVersion = input.Version;
}
// browse paths
if (input.BrowsePaths.Count > 0)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.BrowsePaths;
output.dwBrowsePathCount = input.BrowsePaths.Count;
output.pszBrowsePaths = OpcCom.Interop.GetUnicodeStrings(input.BrowsePaths.ToArray());
}
// name
if (input.Name != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.Name;
output.szName = input.Name;
}
// description
if (input.Description != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.Description;
output.szDescription = input.Description;
}
// keyword
if (input.Keyword != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.Keyword;
output.szKeyword = input.Keyword;
}
// default source item connected
if (input.DefaultSourceItemConnectedSpecified)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.DefaultSourceItemConnected;
output.bDefaultSourceItemConnected = (input.DefaultSourceItemConnected)?1:0;
}
// default target item connected
if (input.DefaultTargetItemConnectedSpecified)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.DefaultTargetItemConnected;
output.bDefaultTargetItemConnected = (input.DefaultTargetItemConnected)?1:0;
}
// default overridden
if (input.DefaultOverriddenSpecified)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.DefaultOverridden;
output.bDefaultOverridden = (input.DefaultOverridden)?1:0;
}
// default override value
if (input.DefaultOverrideValue != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.DefaultOverrideValue;
output.vDefaultOverrideValue = input.DefaultOverrideValue;
}
// substitute value
if (input.SubstituteValue != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.SubstituteValue;
output.vSubstituteValue = input.SubstituteValue;
}
// enable substitute value
if (input.EnableSubstituteValueSpecified)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.EnableSubstituteValue;
output.bEnableSubstituteValue = (input.EnableSubstituteValue)?1:0;
}
// target item name
if (input.TargetItemName != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.TargetItemName;
output.szTargetItemName = input.TargetItemName;
}
// target item path
if (input.TargetItemPath != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.TargetItemPath;
output.szTargetItemPath = input.TargetItemPath;
}
// source server name
if (input.SourceServerName != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.SourceServerName;
output.szSourceServerName = input.SourceServerName;
}
// source item name
if (input.SourceItemName != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.SourceItemName;
output.szSourceItemName = input.SourceItemName;
}
// source item path
if (input.SourceItemPath != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.SourceItemPath;
output.szSourceItemPath = input.SourceItemPath;
}
// source item queue size
if (input.SourceItemQueueSizeSpecified)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.SourceItemQueueSize;
output.dwSourceItemQueueSize = input.SourceItemQueueSize;
}
// update rate
if (input.UpdateRateSpecified)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.UpdateRate;
output.dwUpdateRate = input.UpdateRate;
}
// deadband
if (input.DeadbandSpecified)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.DeadBand;
output.fltDeadBand = input.Deadband;
}
// vendor data
if (input.VendorData != null)
{
output.dwMask |= (uint)OpcRcw.Dx.Mask.VendorData;
output.szVendorData = input.VendorData;
}
return output;
}
/// <summary>
/// Converts a COM DXConnection structure to a .NET DXConnection object.
/// </summary>
internal static DXConnection GetDXConnection(OpcRcw.Dx.DXConnection input, bool deallocate)
{
DXConnection output = new DXConnection();
// set output default values.
output.ItemPath = null;
output.ItemName = null;
output.Version = null;
output.BrowsePaths.Clear();
output.Name = null;
output.Description = null;
output.Keyword = null;
output.DefaultSourceItemConnected = false;
output.DefaultSourceItemConnectedSpecified = false;
output.DefaultTargetItemConnected = false;
output.DefaultTargetItemConnectedSpecified = false;
output.DefaultOverridden = false;
output.DefaultOverriddenSpecified = false;
output.DefaultOverrideValue = null;
output.SubstituteValue = null;
output.EnableSubstituteValue = false;
output.EnableSubstituteValueSpecified = false;
output.TargetItemPath = null;
output.TargetItemName = null;
output.SourceServerName = null;
output.SourceItemPath = null;
output.SourceItemName = null;
output.SourceItemQueueSize = 0;
output.SourceItemQueueSizeSpecified = false;
output.UpdateRate = 0;
output.UpdateRateSpecified = false;
output.Deadband = 0;
output.DeadbandSpecified = false;
output.VendorData = null;
// item name
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.ItemName) != 0)
{
output.ItemName = input.szItemName;
}
// item path
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.ItemPath) != 0)
{
output.ItemPath = input.szItemPath;
}
// version
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.Version) != 0)
{
output.Version = input.szVersion;
}
// browse paths
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.BrowsePaths) != 0)
{
string[] browsePaths = OpcCom.Interop.GetUnicodeStrings(ref input.pszBrowsePaths, input.dwBrowsePathCount, deallocate);
if (browsePaths != null)
{
output.BrowsePaths.AddRange(browsePaths);
}
}
// name
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.Name) != 0)
{
output.Name = input.szName;
}
// description
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.Description) != 0)
{
output.Description = input.szDescription;
}
// keyword
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.Keyword) != 0)
{
output.Keyword = input.szKeyword;
}
// default source item connected
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.DefaultSourceItemConnected) != 0)
{
output.DefaultSourceItemConnected = input.bDefaultSourceItemConnected != 0;
output.DefaultSourceItemConnectedSpecified = true;
}
// default target item connected
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.DefaultTargetItemConnected) != 0)
{
output.DefaultTargetItemConnected = input.bDefaultTargetItemConnected != 0;
output.DefaultTargetItemConnectedSpecified = true;
}
// default overridden
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.DefaultOverridden) != 0)
{
output.DefaultOverridden = input.bDefaultOverridden != 0;
output.DefaultOverriddenSpecified = true;
}
// default override value
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.DefaultOverrideValue) != 0)
{
output.DefaultOverrideValue = input.vDefaultOverrideValue;
}
// substitute value
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.SubstituteValue) != 0)
{
output.SubstituteValue = input.vSubstituteValue;
}
// enable substitute value
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.EnableSubstituteValue) != 0)
{
output.EnableSubstituteValue = input.bEnableSubstituteValue != 0;
output.EnableSubstituteValueSpecified = true;
}
// target item name
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.TargetItemName) != 0)
{
output.TargetItemName = input.szTargetItemName;
}
// target item path
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.TargetItemPath) != 0)
{
output.TargetItemPath = input.szTargetItemPath;
}
// source server name
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.SourceServerName) != 0)
{
output.SourceServerName = input.szSourceServerName;
}
// source item name
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.SourceItemName) != 0)
{
output.SourceItemName = input.szSourceItemName;
}
// source item path
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.SourceItemPath) != 0)
{
output.SourceItemPath = input.szSourceItemPath;
}
// source item queue size
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.SourceItemQueueSize) != 0)
{
output.SourceItemQueueSize = input.dwSourceItemQueueSize;
output.SourceItemQueueSizeSpecified = true;
}
// update rate
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.UpdateRate) != 0)
{
output.UpdateRate = input.dwUpdateRate;
output.UpdateRateSpecified = true;
}
// deadband
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.DeadBand) != 0)
{
output.Deadband = input.fltDeadBand;
output.DeadbandSpecified = true;
}
// vendor data
if ((input.dwMask & (uint)OpcRcw.Dx.Mask.VendorData) != 0)
{
output.VendorData = input.szVendorData;
}
return output;
}
/// <summary>
/// Converts an array of .NET ItemIdentifier objects to COM ItemIdentifier structures.
/// </summary>
internal static OpcRcw.Dx.ItemIdentifier[] GetItemIdentifiers(Opc.Dx.ItemIdentifier[] input)
{
OpcRcw.Dx.ItemIdentifier[] output = null;
if (input != null && input.Length > 0)
{
output = new OpcRcw.Dx.ItemIdentifier[input.Length];
for (int ii = 0; ii < input.Length; ii++)
{
output[ii] = new OpcRcw.Dx.ItemIdentifier();
output[ii].szItemName = input[ii].ItemName;
output[ii].szItemPath = input[ii].ItemPath;
output[ii].szVersion = input[ii].Version;
}
}
return output;
}
*/
}
}

View File

@@ -0,0 +1,51 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Com.Ae
{
/// <summary>
/// Defines all well known COM AE HRESULT codes.
/// </summary>
internal struct Result
{
/// <remarks/>
public const int S_ALREADYACKED = +0x00040200; // 0x00040200
/// <remarks/>
public const int S_INVALIDBUFFERTIME = +0x00040201; // 0x00040201
/// <remarks/>
public const int S_INVALIDMAXSIZE = +0x00040202; // 0x00040202
/// <remarks/>
public const int S_INVALIDKEEPALIVETIME = +0x00040203; // 0x00040203
/// <remarks/>
public const int E_INVALIDBRANCHNAME = -0x3FFBFDFD; // 0xC0040203
/// <remarks/>
public const int E_INVALIDTIME = -0x3FFBFDFC; // 0xC0040204
/// <remarks/>
public const int E_BUSY = -0x3FFBFDFB; // 0xC0040205
/// <remarks/>
public const int E_NOINFO = -0x3FFBFDFA; // 0xC0040206
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,610 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Runtime.InteropServices;
using Technosoftware.DaAeHdaClient.Ae;
using Technosoftware.OpcRcw.Ae;
using Technosoftware.DaAeHdaClient.Utilities;
#endregion
namespace Technosoftware.DaAeHdaClient.Com.Ae
{
/// <summary>
/// A .NET wrapper for a COM server that implements the AE subscription interfaces.
/// </summary>
[Serializable]
internal class Subscription : ITsCAeSubscription
{
#region Constructors
/// <summary>
/// Initializes the object with the specified URL and COM server.
/// </summary>
internal Subscription(TsCAeSubscriptionState state, object subscription)
{
subscription_ = subscription;
clientHandle_ = OpcConvert.Clone(state.ClientHandle);
supportsAe11_ = true;
callback_ = new Callback(state.ClientHandle);
// check if the V1.1 interfaces are supported.
try
{
var server = (IOPCEventSubscriptionMgt2)subscription_;
}
catch
{
supportsAe11_ = false;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// The finalizer.
/// </summary>
~Subscription()
{
Dispose(false);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing">If true managed and unmanaged resources can be disposed. If false only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!disposed_)
{
lock (lock_)
{
if (disposing)
{
// Free other state (managed objects).
if (subscription_ != null)
{
// close all connections.
if (connection_ != null)
{
try
{
connection_.Dispose();
}
catch
{
// Ignore. COM Server probably no longer connected
}
connection_ = null;
}
}
}
// Free your own state (unmanaged objects).
// Set large fields to null.
if (subscription_ != null)
{
// release subscription object.
try
{
Technosoftware.DaAeHdaClient.Com.Interop.ReleaseServer(subscription_);
}
catch
{
// Ignore. COM Server probably no longer connected
}
subscription_ = null;
}
}
disposed_ = true;
}
}
#endregion
#region Technosoftware.DaAeHdaClient.ISubscription Members
/// <summary>
/// An event to receive data change updates.
/// </summary>
public event TsCAeDataChangedEventHandler DataChangedEvent
{
add { lock (this) { Advise(); callback_.DataChangedEvent += value; } }
remove { lock (this) { callback_.DataChangedEvent -= value; Unadvise(); } }
}
//======================================================================
// State Management
/// <summary>
/// Returns the current state of the subscription.
/// </summary>
/// <returns>The current state of the subscription.</returns>
public TsCAeSubscriptionState GetState()
{
lock (this)
{
// verify state and arguments.
if (subscription_ == null) throw new NotConnectedException();
// initialize arguments.
int pbActive;
int pdwBufferTime;
int pdwMaxSize;
var pdwKeepAliveTime = 0;
// invoke COM method.
try
{
((IOPCEventSubscriptionMgt)subscription_).GetState(
out pbActive,
out pdwBufferTime,
out pdwMaxSize,
out _);
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt.GetState", e);
}
// get keep alive.
if (supportsAe11_)
{
try
{
((IOPCEventSubscriptionMgt2)subscription_).GetKeepAlive(out pdwKeepAliveTime);
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt2.GetKeepAlive", e);
}
}
// build results
var state = new TsCAeSubscriptionState
{
Active = pbActive != 0,
ClientHandle = clientHandle_,
BufferTime = pdwBufferTime,
MaxSize = pdwMaxSize,
KeepAlive = pdwKeepAliveTime
};
// return results.
return state;
}
}
/// <summary>
/// Changes the state of a subscription.
/// </summary>
/// <param name="masks">A bit mask that indicates which elements of the subscription state are changing.</param>
/// <param name="state">The new subscription state.</param>
/// <returns>The actual subscription state after applying the changes.</returns>
public TsCAeSubscriptionState ModifyState(int masks, TsCAeSubscriptionState state)
{
lock (this)
{
// verify state and arguments.
if (subscription_ == null) throw new NotConnectedException();
// initialize arguments.
var active = (state.Active) ? 1 : 0;
var hActive = GCHandle.Alloc(active, GCHandleType.Pinned);
var hBufferTime = GCHandle.Alloc(state.BufferTime, GCHandleType.Pinned);
var hMaxSize = GCHandle.Alloc(state.MaxSize, GCHandleType.Pinned);
var pbActive = ((masks & (int)TsCAeStateMask.Active) != 0) ? hActive.AddrOfPinnedObject() : IntPtr.Zero;
var pdwBufferTime = ((masks & (int)TsCAeStateMask.BufferTime) != 0) ? hBufferTime.AddrOfPinnedObject() : IntPtr.Zero;
var pdwMaxSize = ((masks & (int)TsCAeStateMask.MaxSize) != 0) ? hMaxSize.AddrOfPinnedObject() : IntPtr.Zero;
var phClientSubscription = 0;
// invoke COM method.
try
{
((IOPCEventSubscriptionMgt)subscription_).SetState(
pbActive,
pdwBufferTime,
pdwMaxSize,
phClientSubscription,
out _,
out _);
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt.SetState", e);
}
finally
{
if (hActive.IsAllocated) hActive.Free();
if (hBufferTime.IsAllocated) hBufferTime.Free();
if (hMaxSize.IsAllocated) hMaxSize.Free();
}
// update keep alive.
if (((masks & (int)TsCAeStateMask.KeepAlive) != 0) && supportsAe11_)
{
try
{
((IOPCEventSubscriptionMgt2)subscription_).SetKeepAlive(
state.KeepAlive,
out _);
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt2.SetKeepAlive", e);
}
}
// return current state.
return GetState();
}
}
//======================================================================
// Filter Management
/// <summary>
/// Returns the current filters for the subscription.
/// </summary>
/// <returns>The current filters for the subscription.</returns>
public TsCAeSubscriptionFilters GetFilters()
{
lock (this)
{
// verify state and arguments.
if (subscription_ == null) throw new NotConnectedException();
// initialize arguments.
int pdwEventType;
int pdwNumCategories;
IntPtr ppidEventCategories;
int pdwLowSeverity;
int pdwHighSeverity;
int pdwNumAreas;
IntPtr ppsAreaList;
int pdwNumSources;
IntPtr ppsSourceList;
// invoke COM method.
try
{
((IOPCEventSubscriptionMgt)subscription_).GetFilter(
out pdwEventType,
out pdwNumCategories,
out ppidEventCategories,
out pdwLowSeverity,
out pdwHighSeverity,
out pdwNumAreas,
out ppsAreaList,
out pdwNumSources,
out ppsSourceList);
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt.GetFilter", e);
}
// marshal results
var categoryIDs = Technosoftware.DaAeHdaClient.Com.Interop.GetInt32s(ref ppidEventCategories, pdwNumCategories, true);
var areaIDs = Technosoftware.DaAeHdaClient.Com.Interop.GetUnicodeStrings(ref ppsAreaList, pdwNumAreas, true);
var sourceIDs = Technosoftware.DaAeHdaClient.Com.Interop.GetUnicodeStrings(ref ppsSourceList, pdwNumSources, true);
// build results.
var filters = new TsCAeSubscriptionFilters
{
EventTypes = pdwEventType, LowSeverity = pdwLowSeverity, HighSeverity = pdwHighSeverity
};
filters.Categories.AddRange(categoryIDs);
filters.Areas.AddRange(areaIDs);
filters.Sources.AddRange(sourceIDs);
// return results.
return filters;
}
}
/// <summary>
/// Sets the current filters for the subscription.
/// </summary>
/// <param name="filters">The new filters to use for the subscription.</param>
public void SetFilters(TsCAeSubscriptionFilters filters)
{
lock (this)
{
// verify state and arguments.
if (subscription_ == null) throw new NotConnectedException();
// invoke COM method.
try
{
((IOPCEventSubscriptionMgt)subscription_).SetFilter(
filters.EventTypes,
filters.Categories.Count,
filters.Categories.ToArray(),
filters.LowSeverity,
filters.HighSeverity,
filters.Areas.Count,
filters.Areas.ToArray(),
filters.Sources.Count,
filters.Sources.ToArray());
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt.SetFilter", e);
}
}
}
//======================================================================
// Attribute Management
/// <summary>
/// Returns the set of attributes to return with event notifications.
/// </summary>
/// <returns>The set of attributes to returned with event notifications.</returns>
public int[] GetReturnedAttributes(int eventCategory)
{
lock (this)
{
// verify state and arguments.
if (subscription_ == null) throw new NotConnectedException();
// initialize arguments.
int pdwCount;
IntPtr ppidAttributeIDs;
// invoke COM method.
try
{
((IOPCEventSubscriptionMgt)subscription_).GetReturnedAttributes(
eventCategory,
out pdwCount,
out ppidAttributeIDs);
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt.GetReturnedAttributes", e);
}
// marshal results
var attributeIDs = Technosoftware.DaAeHdaClient.Com.Interop.GetInt32s(ref ppidAttributeIDs, pdwCount, true);
// return results.
return attributeIDs;
}
}
/// <summary>
/// Selects the set of attributes to return with event notifications.
/// </summary>
/// <param name="eventCategory">The specific event category for which the attributes apply.</param>
/// <param name="attributeIDs">The list of attribute ids to return.</param>
public void SelectReturnedAttributes(int eventCategory, int[] attributeIDs)
{
lock (this)
{
// verify state and arguments.
if (subscription_ == null) throw new NotConnectedException();
// invoke COM method.
try
{
((IOPCEventSubscriptionMgt)subscription_).SelectReturnedAttributes(
eventCategory,
attributeIDs?.Length ?? 0,
attributeIDs ?? Array.Empty<int>());
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt.SelectReturnedAttributes", e);
}
}
}
//======================================================================
// Refresh
/// <summary>
/// Force a refresh for all active conditions and inactive, unacknowledged conditions whose event notifications match the filter of the event subscription.
/// </summary>
public void Refresh()
{
lock (this)
{
// verify state and arguments.
if (subscription_ == null) throw new NotConnectedException();
// invoke COM method.
try
{
((IOPCEventSubscriptionMgt)subscription_).Refresh(0);
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt.Refresh", e);
}
}
}
/// <summary>
/// Cancels an outstanding refresh request.
/// </summary>
public void CancelRefresh()
{
lock (this)
{
// verify state and arguments.
if (subscription_ == null) throw new NotConnectedException();
// invoke COM method.
try
{
((IOPCEventSubscriptionMgt)subscription_).CancelRefresh(0);
}
catch (Exception e)
{
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCEventSubscriptionMgt.CancelRefresh", e);
}
}
}
#endregion
#region IOPCEventSink Members
/// <summary>
/// A class that implements the IOPCEventSink interface.
/// </summary>
private class Callback : IOPCEventSink
{
/// <summary>
/// Initializes the object with the containing subscription object.
/// </summary>
public Callback(object clientHandle)
{
clientHandle_ = clientHandle;
}
/// <summary>
/// Raised when data changed callbacks arrive.
/// </summary>
public event TsCAeDataChangedEventHandler DataChangedEvent
{
add { lock (this) { DataChangedEventHandler += value; } }
remove { lock (this) { DataChangedEventHandler -= value; } }
}
/// <summary>
/// Called when a data changed event is received.
/// </summary>
public void OnEvent(
int hClientSubscription,
int bRefresh,
int bLastRefresh,
int dwCount,
ONEVENTSTRUCT[] pEvents)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions, true);
try
{
lock (this)
{
// do nothing if no connections.
if (DataChangedEventHandler == null) return;
// un marshal item values.
var notifications = Interop.GetEventNotifications(pEvents);
foreach (var notification in notifications)
{
notification.ClientHandle = clientHandle_;
}
if (!LicenseHandler.IsExpired)
{
// invoke the callback.
DataChangedEventHandler?.Invoke(notifications, bRefresh != 0, bLastRefresh != 0);
}
}
}
catch (Exception e)
{
Utils.Trace(e, "Exception '{0}' in event handler.", e.Message);
}
}
#region Private Members
private object clientHandle_;
private event TsCAeDataChangedEventHandler DataChangedEventHandler;
#endregion
}
#endregion
#region Private Methods
/// <summary>
/// Establishes a connection point callback with the COM server.
/// </summary>
private void Advise()
{
if (connection_ == null)
{
connection_ = new ConnectionPoint(subscription_, typeof(IOPCEventSink).GUID);
connection_.Advise(callback_);
}
}
/// <summary>
/// Closes a connection point callback with the COM server.
/// </summary>
private void Unadvise()
{
if (connection_ != null)
{
if (connection_.Unadvise() == 0)
{
connection_.Dispose();
connection_ = null;
}
}
}
#endregion
#region Private Members
private object subscription_;
private object clientHandle_;
private bool supportsAe11_ = true;
private ConnectionPoint connection_;
private Callback callback_;
/// <summary>
/// The synchronization object for subscription access
/// </summary>
private static volatile object lock_ = new object();
private bool disposed_;
#endregion
}
}

View File

@@ -0,0 +1,97 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
/// <summary>
/// Manages the license to enable the different product versions.
/// </summary>
public partial class ApplicationInstance
{
#region Nested Enums
/// <summary>
/// The possible authentication levels.
/// </summary>
[Flags]
public enum AuthenticationLevel : uint
{
/// <summary>
/// Tells DCOM to choose the authentication level using its normal security blanket negotiation algorithm.
/// </summary>
Default = 0,
/// <summary>
/// Performs no authentication.
/// </summary>
None = 1,
/// <summary>
/// Authenticates the credentials of the client only when the client establishes a relationship with the server. Datagram transports always use Packet instead.
/// </summary>
Connect = 2,
/// <summary>
/// Authenticates only at the beginning of each remote procedure call when the server receives the request. Datagram transports use Packet instead.
/// </summary>
Call = 3,
/// <summary>
/// Authenticates that all data received is from the expected client.
/// </summary>
Packet = 4,
/// <summary>
/// Authenticates and verifies that none of the data transferred between client and server has been modified.
/// </summary>
Integrity = 5,
/// <summary>
/// Authenticates all previous levels and encrypts the argument value of each remote procedure call.
/// </summary>
Privacy = 6,
}
#endregion
#region Public Methods
/// <summary>
/// Initializes COM security. This should be called directly at the beginning of an application and can only be called once.
/// </summary>
/// <param name="authenticationLevel">The default authentication level for the process. Both servers and clients use this parameter when they call CoInitializeSecurity. With the Windows Update KB5004442 a higher authentication level of Integrity must be used.</param>
public static void InitializeSecurity(AuthenticationLevel authenticationLevel)
{
if (!InitializeSecurityCalled)
{
Com.Interop.InitializeSecurity((uint)authenticationLevel);
InitializeSecurityCalled = true;
}
}
#endregion
#region Internal Fields
internal static bool InitializeSecurityCalled;
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,107 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using Technosoftware.OpcRcw.Comn;
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
/// <summary>
/// Adds and removes a connection point to a server.
/// </summary>
internal class ConnectionPoint : IDisposable
{
/// <summary>
/// The COM server that supports connection points.
/// </summary>
private IConnectionPoint server_;
/// <summary>
/// The id assigned to the connection by the COM server.
/// </summary>
private int cookie_;
/// <summary>
/// The number of times Advise() has been called without a matching Unadvise().
/// </summary>
private int refs_;
/// <summary>
/// Initializes the object by finding the specified connection point.
/// </summary>
public ConnectionPoint(object server, Guid iid)
{
((IConnectionPointContainer)server).FindConnectionPoint(ref iid, out server_);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (server_ != null)
{
while (Unadvise() > 0)
{
}
try
{
Utilities.Interop.ReleaseServer(server_);
}
catch
{
// Ignore. COM Server probably no longer connected
}
server_ = null;
}
}
/// <summary>
/// The cookie returned in the advise call.
/// </summary>
public int Cookie => cookie_;
//=====================================================================
// IConnectionPoint
/// <summary>
/// Establishes a connection, if necessary and increments the reference count.
/// </summary>
public int Advise(object callback)
{
if (refs_++ == 0) server_.Advise(callback, out cookie_);
return refs_;
}
/// <summary>
/// Decrements the reference count and closes the connection if no more references.
/// </summary>
public int Unadvise()
{
if (--refs_ == 0) server_.Unadvise(cookie_);
return refs_;
}
}
}

View File

@@ -0,0 +1,60 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using Technosoftware.DaAeHdaClient.Da;
#endregion
namespace Technosoftware.DaAeHdaClient.Com.Da
{
/// <summary>
/// Implements an object that handles multi-step browse operations.
/// </summary>
[Serializable]
internal class BrowsePosition : TsCDaBrowsePosition
{
/// <summary>
/// The continuation point for a browse operation.
/// </summary>
internal string ContinuationPoint = null;
/// <summary>
/// Indicates that elements that meet the filter criteria have not been returned.
/// </summary>
internal bool MoreElements = false;
/// <summary>
/// Initializes a browse position
/// </summary>
internal BrowsePosition(
OpcItem itemID,
TsCDaBrowseFilters filters,
string continuationPoint)
:
base(itemID, filters)
{
ContinuationPoint = continuationPoint;
}
}
}

View File

@@ -0,0 +1,906 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Reflection;
using Technosoftware.DaAeHdaClient.Da;
#endregion
#pragma warning disable 0618
namespace Technosoftware.DaAeHdaClient.Com.Da
{
/// <summary>
/// Contains state information for a single asynchronous Technosoftware.DaAeHdaClient.Com.Da.Interop.
/// </summary>
internal class Interop
{
/// <summary>
/// Converts a standard FILETIME to an OpcRcw.Da.FILETIME structure.
/// </summary>
internal static OpcRcw.Da.FILETIME Convert(FILETIME input)
{
var output = new OpcRcw.Da.FILETIME();
output.dwLowDateTime = input.dwLowDateTime;
output.dwHighDateTime = input.dwHighDateTime;
return output;
}
/// <summary>
/// Converts an OpcRcw.Da.FILETIME to a standard FILETIME structure.
/// </summary>
internal static FILETIME Convert(OpcRcw.Da.FILETIME input)
{
var output = new FILETIME();
output.dwLowDateTime = input.dwLowDateTime;
output.dwHighDateTime = input.dwHighDateTime;
return output;
}
/// <summary>
/// Allocates and marshals a OPCSERVERSTATUS structure.
/// </summary>
internal static OpcRcw.Da.OPCSERVERSTATUS GetServerStatus(OpcServerStatus input, int groupCount)
{
var output = new OpcRcw.Da.OPCSERVERSTATUS();
if (input != null)
{
output.szVendorInfo = input.VendorInfo;
output.wMajorVersion = 0;
output.wMinorVersion = 0;
output.wBuildNumber = 0;
output.dwServerState = (OpcRcw.Da.OPCSERVERSTATE)input.ServerState;
output.ftStartTime = Convert(Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(input.StartTime));
output.ftCurrentTime = Convert(Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(input.CurrentTime));
output.ftLastUpdateTime = Convert(Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(input.LastUpdateTime));
output.dwBandWidth = -1;
output.dwGroupCount = groupCount;
output.wReserved = 0;
if (input.ProductVersion != null)
{
var versions = input.ProductVersion.Split(new char[] { '.' });
if (versions.Length > 0)
{
try { output.wMajorVersion = System.Convert.ToInt16(versions[0]); }
catch { output.wMajorVersion = 0; }
}
if (versions.Length > 1)
{
try { output.wMinorVersion = System.Convert.ToInt16(versions[1]); }
catch { output.wMinorVersion = 0; }
}
output.wBuildNumber = 0;
for (var ii = 2; ii < versions.Length; ii++)
{
try
{
output.wBuildNumber = (short)(output.wBuildNumber * 100 + System.Convert.ToInt16(versions[ii]));
}
catch
{
output.wBuildNumber = 0;
break;
}
}
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates a OPCSERVERSTATUS structure.
/// </summary>
internal static OpcServerStatus GetServerStatus(ref IntPtr pInput, bool deallocate)
{
OpcServerStatus output = null;
if (pInput != IntPtr.Zero)
{
var status = (OpcRcw.Da.OPCSERVERSTATUS)Marshal.PtrToStructure(pInput, typeof(OpcRcw.Da.OPCSERVERSTATUS));
output = new OpcServerStatus();
output.VendorInfo = status.szVendorInfo;
output.ProductVersion = string.Format("{0}.{1}.{2}", status.wMajorVersion, status.wMinorVersion, status.wBuildNumber);
output.ServerState = (OpcServerState)status.dwServerState;
output.StatusInfo = null;
output.StartTime = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(status.ftStartTime));
output.CurrentTime = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(status.ftCurrentTime));
output.LastUpdateTime = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(status.ftLastUpdateTime));
if (deallocate)
{
Marshal.DestroyStructure(pInput, typeof(OpcRcw.Da.OPCSERVERSTATUS));
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Converts a browseFilter values to the COM equivalent.
/// </summary>
internal static OpcRcw.Da.OPCBROWSEFILTER GetBrowseFilter(TsCDaBrowseFilter input)
{
switch (input)
{
case TsCDaBrowseFilter.All: return OpcRcw.Da.OPCBROWSEFILTER.OPC_BROWSE_FILTER_ALL;
case TsCDaBrowseFilter.Branch: return OpcRcw.Da.OPCBROWSEFILTER.OPC_BROWSE_FILTER_BRANCHES;
case TsCDaBrowseFilter.Item: return OpcRcw.Da.OPCBROWSEFILTER.OPC_BROWSE_FILTER_ITEMS;
}
return OpcRcw.Da.OPCBROWSEFILTER.OPC_BROWSE_FILTER_ALL;
}
/// <summary>
/// Converts a browseFilter values from the COM equivalent.
/// </summary>
internal static TsCDaBrowseFilter GetBrowseFilter(OpcRcw.Da.OPCBROWSEFILTER input)
{
switch (input)
{
case OpcRcw.Da.OPCBROWSEFILTER.OPC_BROWSE_FILTER_ALL: return TsCDaBrowseFilter.All;
case OpcRcw.Da.OPCBROWSEFILTER.OPC_BROWSE_FILTER_BRANCHES: return TsCDaBrowseFilter.Branch;
case OpcRcw.Da.OPCBROWSEFILTER.OPC_BROWSE_FILTER_ITEMS: return TsCDaBrowseFilter.Item;
}
return TsCDaBrowseFilter.All;
}
/// <summary>
/// Allocates and marshals an array of HRESULT codes.
/// </summary>
internal static IntPtr GetHRESULTs(IOpcResult[] results)
{
// extract error codes from results.
var errors = new int[results.Length];
for (var ii = 0; ii < results.Length; ii++)
{
if (results[ii] != null)
{
errors[ii] = Technosoftware.DaAeHdaClient.Com.Interop.GetResultID(results[ii].Result);
}
else
{
errors[ii] = Result.E_INVALIDHANDLE;
}
}
// marshal error codes.
var pErrors = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)) * results.Length);
Marshal.Copy(errors, 0, pErrors, results.Length);
// return results.
return pErrors;
}
/// <summary>
/// Unmarshals and deallocates an array of OPCBROWSEELEMENT structures.
/// </summary>
internal static TsCDaBrowseElement[] GetBrowseElements(ref IntPtr pInput, int count, bool deallocate)
{
TsCDaBrowseElement[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new TsCDaBrowseElement[count];
var pos = pInput;
for (var ii = 0; ii < count; ii++)
{
output[ii] = GetBrowseElement(pos, deallocate);
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCBROWSEELEMENT)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Allocates and marshals an array of OPCBROWSEELEMENT structures.
/// </summary>
internal static IntPtr GetBrowseElements(TsCDaBrowseElement[] input, bool propertiesRequested)
{
var output = IntPtr.Zero;
if (input != null && input.Length > 0)
{
output = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(OpcRcw.Da.OPCBROWSEELEMENT)) * input.Length);
var pos = output;
for (var ii = 0; ii < input.Length; ii++)
{
var element = GetBrowseElement(input[ii], propertiesRequested);
Marshal.StructureToPtr(element, pos, false);
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCBROWSEELEMENT)));
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates a OPCBROWSEELEMENT structures.
/// </summary>
internal static TsCDaBrowseElement GetBrowseElement(IntPtr pInput, bool deallocate)
{
TsCDaBrowseElement output = null;
if (pInput != IntPtr.Zero)
{
var element = (OpcRcw.Da.OPCBROWSEELEMENT)Marshal.PtrToStructure(pInput, typeof(OpcRcw.Da.OPCBROWSEELEMENT));
output = new TsCDaBrowseElement();
output.Name = element.szName;
output.ItemPath = null;
output.ItemName = element.szItemID;
output.IsItem = ((element.dwFlagValue & OpcRcw.Da.Constants.OPC_BROWSE_ISITEM) != 0);
output.HasChildren = ((element.dwFlagValue & OpcRcw.Da.Constants.OPC_BROWSE_HASCHILDREN) != 0);
output.Properties = GetItemProperties(ref element.ItemProperties, deallocate);
if (deallocate)
{
Marshal.DestroyStructure(pInput, typeof(OpcRcw.Da.OPCBROWSEELEMENT));
}
}
return output;
}
/// <summary>
/// Allocates and marshals an OPCBROWSEELEMENT structure.
/// </summary>
internal static OpcRcw.Da.OPCBROWSEELEMENT GetBrowseElement(TsCDaBrowseElement input, bool propertiesRequested)
{
var output = new OpcRcw.Da.OPCBROWSEELEMENT();
if (input != null)
{
output.szName = input.Name;
output.szItemID = input.ItemName;
output.dwFlagValue = 0;
output.ItemProperties = GetItemProperties(input.Properties);
if (input.IsItem)
{
output.dwFlagValue |= OpcRcw.Da.Constants.OPC_BROWSE_ISITEM;
}
if (input.HasChildren)
{
output.dwFlagValue |= OpcRcw.Da.Constants.OPC_BROWSE_HASCHILDREN;
}
}
return output;
}
/// <summary>
/// Creates an array of property codes.
/// </summary>
internal static int[] GetPropertyIDs(TsDaPropertyID[] propertyIDs)
{
var output = new ArrayList();
if (propertyIDs != null)
{
foreach (var propertyID in propertyIDs)
{
output.Add(propertyID.Code);
}
}
return (int[])output.ToArray(typeof(int));
}
/// <summary>
/// Creates an array of property codes.
/// </summary>
internal static TsDaPropertyID[] GetPropertyIDs(int[] propertyIDs)
{
var output = new ArrayList();
if (propertyIDs != null)
{
foreach (var propertyID in propertyIDs)
{
output.Add(GetPropertyID(propertyID));
}
}
return (TsDaPropertyID[])output.ToArray(typeof(TsDaPropertyID));
}
/// <summary>
/// Unmarshals and deallocates an array of OPCITEMPROPERTIES structures.
/// </summary>
internal static TsCDaItemPropertyCollection[] GetItemPropertyCollections(ref IntPtr pInput, int count, bool deallocate)
{
TsCDaItemPropertyCollection[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new TsCDaItemPropertyCollection[count];
var pos = pInput;
for (var ii = 0; ii < count; ii++)
{
var list = (OpcRcw.Da.OPCITEMPROPERTIES)Marshal.PtrToStructure(pos, typeof(OpcRcw.Da.OPCITEMPROPERTIES));
output[ii] = new TsCDaItemPropertyCollection();
output[ii].ItemPath = null;
output[ii].ItemName = null;
output[ii].Result = Technosoftware.DaAeHdaClient.Com.Interop.GetResultID(list.hrErrorID);
var properties = GetItemProperties(ref list, deallocate);
if (properties != null)
{
output[ii].AddRange(properties);
}
if (deallocate)
{
Marshal.DestroyStructure(pos, typeof(OpcRcw.Da.OPCITEMPROPERTIES));
}
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMPROPERTIES)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Allocates and marshals an array of OPCITEMPROPERTIES structures.
/// </summary>
internal static IntPtr GetItemPropertyCollections(TsCDaItemPropertyCollection[] input)
{
var output = IntPtr.Zero;
if (input != null && input.Length > 0)
{
output = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMPROPERTIES)) * input.Length);
var pos = output;
for (var ii = 0; ii < input.Length; ii++)
{
var properties = new OpcRcw.Da.OPCITEMPROPERTIES();
if (input[ii].Count > 0)
{
properties = GetItemProperties((TsCDaItemProperty[])input[ii].ToArray(typeof(TsCDaItemProperty)));
}
properties.hrErrorID = Technosoftware.DaAeHdaClient.Com.Interop.GetResultID(input[ii].Result);
Marshal.StructureToPtr(properties, pos, false);
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMPROPERTIES)));
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates a OPCITEMPROPERTIES structures.
/// </summary>
internal static TsCDaItemProperty[] GetItemProperties(ref OpcRcw.Da.OPCITEMPROPERTIES input, bool deallocate)
{
TsCDaItemProperty[] output = null;
if (input.dwNumProperties > 0)
{
output = new TsCDaItemProperty[input.dwNumProperties];
var pos = input.pItemProperties;
for (var ii = 0; ii < output.Length; ii++)
{
try
{
output[ii] = GetItemProperty(pos, deallocate);
}
catch (Exception e)
{
output[ii] = new TsCDaItemProperty();
output[ii].Description = e.Message;
output[ii].Result = OpcResult.E_FAIL;
}
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMPROPERTY)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(input.pItemProperties);
input.pItemProperties = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Allocates and marshals an array of OPCITEMPROPERTIES structures.
/// </summary>
internal static OpcRcw.Da.OPCITEMPROPERTIES GetItemProperties(TsCDaItemProperty[] input)
{
var output = new OpcRcw.Da.OPCITEMPROPERTIES();
if (input != null && input.Length > 0)
{
output.hrErrorID = Result.S_OK;
output.dwReserved = 0;
output.dwNumProperties = input.Length;
output.pItemProperties = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMPROPERTY)) * input.Length);
var error = false;
var pos = output.pItemProperties;
for (var ii = 0; ii < input.Length; ii++)
{
var property = GetItemProperty(input[ii]);
Marshal.StructureToPtr(property, pos, false);
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMPROPERTY)));
if (input[ii].Result.Failed())
{
error = true;
}
}
// set flag indicating one or more properties contained errors.
if (error)
{
output.hrErrorID = Result.S_FALSE;
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates a OPCITEMPROPERTY structures.
/// </summary>
internal static TsCDaItemProperty GetItemProperty(IntPtr pInput, bool deallocate)
{
TsCDaItemProperty output = null;
if (pInput != IntPtr.Zero)
{
try
{
var property = (OpcRcw.Da.OPCITEMPROPERTY)Marshal.PtrToStructure(pInput, typeof(OpcRcw.Da.OPCITEMPROPERTY));
output = new TsCDaItemProperty();
output.ID = GetPropertyID(property.dwPropertyID);
output.Description = property.szDescription;
output.DataType = Technosoftware.DaAeHdaClient.Com.Interop.GetType((VarEnum)property.vtDataType);
output.ItemPath = null;
output.ItemName = property.szItemID;
output.Value = UnmarshalPropertyValue(output.ID, property.vValue);
output.Result = Technosoftware.DaAeHdaClient.Com.Interop.GetResultID(property.hrErrorID);
// convert COM DA code to unified DA code.
if (property.hrErrorID == Result.E_BADRIGHTS) output.Result = new OpcResult(OpcResult.Da.E_WRITEONLY, Result.E_BADRIGHTS);
}
catch (Exception)
{
}
if (deallocate)
{
Marshal.DestroyStructure(pInput, typeof(OpcRcw.Da.OPCITEMPROPERTY));
}
}
return output;
}
/// <summary>
/// Allocates and marshals an arary of OPCITEMPROPERTY structures.
/// </summary>
internal static OpcRcw.Da.OPCITEMPROPERTY GetItemProperty(TsCDaItemProperty input)
{
var output = new OpcRcw.Da.OPCITEMPROPERTY();
if (input != null)
{
output.dwPropertyID = input.ID.Code;
output.szDescription = input.Description;
output.vtDataType = (short)Technosoftware.DaAeHdaClient.Com.Interop.GetType(input.DataType);
output.vValue = MarshalPropertyValue(input.ID, input.Value);
output.wReserved = 0;
output.hrErrorID = Technosoftware.DaAeHdaClient.Com.Interop.GetResultID(input.Result);
// set the property data type.
var description = TsDaPropertyDescription.Find(input.ID);
if (description != null)
{
output.vtDataType = (short)Technosoftware.DaAeHdaClient.Com.Interop.GetType(description.Type);
}
// convert unified DA code to COM DA code.
if (input.Result == OpcResult.Da.E_WRITEONLY) output.hrErrorID = Result.E_BADRIGHTS;
}
return output;
}
/// <remarks/>
public static TsDaPropertyID GetPropertyID(int input)
{
var fields = typeof(TsDaProperty).GetFields(BindingFlags.Static | BindingFlags.Public);
foreach (var field in fields)
{
var property = (TsDaPropertyID)field.GetValue(typeof(TsDaPropertyID));
if (input == property.Code)
{
return property;
}
}
return new TsDaPropertyID(input);
}
/// <summary>
/// Converts the property value to a type supported by the unified interface.
/// </summary>
internal static object UnmarshalPropertyValue(TsDaPropertyID propertyID, object input)
{
if (input == null) return null;
try
{
if (propertyID == TsDaProperty.DATATYPE)
{
return Technosoftware.DaAeHdaClient.Com.Interop.GetType((VarEnum)System.Convert.ToUInt16(input));
}
if (propertyID == TsDaProperty.ACCESSRIGHTS)
{
switch (System.Convert.ToInt32(input))
{
case OpcRcw.Da.Constants.OPC_READABLE: return TsDaAccessRights.Readable;
case OpcRcw.Da.Constants.OPC_WRITEABLE: return TsDaAccessRights.Writable;
case OpcRcw.Da.Constants.OPC_READABLE | OpcRcw.Da.Constants.OPC_WRITEABLE:
{
return TsDaAccessRights.ReadWritable;
}
}
return null;
}
if (propertyID == TsDaProperty.EUTYPE)
{
switch ((OpcRcw.Da.OPCEUTYPE)input)
{
case OpcRcw.Da.OPCEUTYPE.OPC_NOENUM: return TsDaEuType.NoEnum;
case OpcRcw.Da.OPCEUTYPE.OPC_ANALOG: return TsDaEuType.Analog;
case OpcRcw.Da.OPCEUTYPE.OPC_ENUMERATED: return TsDaEuType.Enumerated;
}
return null;
}
if (propertyID == TsDaProperty.QUALITY)
{
return new TsCDaQuality(System.Convert.ToInt16(input));
}
// convert UTC time in property to local time for the unified DA interface.
if (propertyID == TsDaProperty.TIMESTAMP)
{
if (input.GetType() == typeof(DateTime))
{
var dateTime = (DateTime)input;
if (dateTime != DateTime.MinValue)
{
return dateTime.ToLocalTime();
}
return dateTime;
}
}
}
catch { }
return input;
}
/// <summary>
/// Converts the property value to a type supported by COM-DA interface.
/// </summary>
internal static object MarshalPropertyValue(TsDaPropertyID propertyID, object input)
{
if (input == null) return null;
try
{
if (propertyID == TsDaProperty.DATATYPE)
{
return (short)Technosoftware.DaAeHdaClient.Com.Interop.GetType((Type)input);
}
if (propertyID == TsDaProperty.ACCESSRIGHTS)
{
switch ((TsDaAccessRights)input)
{
case TsDaAccessRights.Readable: return OpcRcw.Da.Constants.OPC_READABLE;
case TsDaAccessRights.Writable: return OpcRcw.Da.Constants.OPC_WRITEABLE;
case TsDaAccessRights.ReadWritable: return OpcRcw.Da.Constants.OPC_READABLE | OpcRcw.Da.Constants.OPC_WRITEABLE;
}
return null;
}
if (propertyID == TsDaProperty.EUTYPE)
{
switch ((TsDaEuType)input)
{
case TsDaEuType.NoEnum: return OpcRcw.Da.OPCEUTYPE.OPC_NOENUM;
case TsDaEuType.Analog: return OpcRcw.Da.OPCEUTYPE.OPC_ANALOG;
case TsDaEuType.Enumerated: return OpcRcw.Da.OPCEUTYPE.OPC_ENUMERATED;
}
return null;
}
if (propertyID == TsDaProperty.QUALITY)
{
return ((TsCDaQuality)input).GetCode();
}
// convert local time in property to UTC time for the COM DA interface.
if (propertyID == TsDaProperty.TIMESTAMP)
{
if (input.GetType() == typeof(DateTime))
{
var dateTime = (DateTime)input;
if (dateTime != DateTime.MinValue)
{
return dateTime.ToUniversalTime();
}
return dateTime;
}
}
}
catch { }
return input;
}
/// <summary>
/// Converts an array of item values to an array of OPCITEMVQT objects.
/// </summary>
internal static OpcRcw.Da.OPCITEMVQT[] GetOPCITEMVQTs(TsCDaItemValue[] input)
{
OpcRcw.Da.OPCITEMVQT[] output = null;
if (input != null)
{
output = new OpcRcw.Da.OPCITEMVQT[input.Length];
for (var ii = 0; ii < input.Length; ii++)
{
output[ii] = new OpcRcw.Da.OPCITEMVQT();
var timestamp = (input[ii].TimestampSpecified) ? input[ii].Timestamp : DateTime.MinValue;
output[ii].vDataValue = Technosoftware.DaAeHdaClient.Com.Interop.GetVARIANT(input[ii].Value);
output[ii].bQualitySpecified = (input[ii].QualitySpecified) ? 1 : 0;
output[ii].wQuality = (input[ii].QualitySpecified) ? input[ii].Quality.GetCode() : (short)0;
output[ii].bTimeStampSpecified = (input[ii].TimestampSpecified) ? 1 : 0;
output[ii].ftTimeStamp = Convert(Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(timestamp));
}
}
return output;
}
/// <summary>
/// Converts an array of item objects to an array of GetOPCITEMDEF objects.
/// </summary>
internal static OpcRcw.Da.OPCITEMDEF[] GetOPCITEMDEFs(TsCDaItem[] input)
{
OpcRcw.Da.OPCITEMDEF[] output = null;
if (input != null)
{
output = new OpcRcw.Da.OPCITEMDEF[input.Length];
for (var ii = 0; ii < input.Length; ii++)
{
output[ii] = new OpcRcw.Da.OPCITEMDEF();
output[ii].szItemID = input[ii].ItemName;
output[ii].szAccessPath = (input[ii].ItemPath == null) ? string.Empty : input[ii].ItemPath;
output[ii].bActive = (input[ii].ActiveSpecified) ? ((input[ii].Active) ? 1 : 0) : 1;
output[ii].vtRequestedDataType = (short)Technosoftware.DaAeHdaClient.Com.Interop.GetType(input[ii].ReqType);
output[ii].hClient = 0;
output[ii].dwBlobSize = 0;
output[ii].pBlob = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates a OPCITEMSTATE structures.
/// </summary>
internal static TsCDaItemValue[] GetItemValues(ref IntPtr pInput, int count, bool deallocate)
{
TsCDaItemValue[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new TsCDaItemValue[count];
var pos = pInput;
for (var ii = 0; ii < count; ii++)
{
var result = (OpcRcw.Da.OPCITEMSTATE)Marshal.PtrToStructure(pos, typeof(OpcRcw.Da.OPCITEMSTATE));
output[ii] = new TsCDaItemValue();
output[ii].ClientHandle = result.hClient;
output[ii].Value = result.vDataValue;
output[ii].Quality = new TsCDaQuality(result.wQuality);
output[ii].QualitySpecified = true;
output[ii].Timestamp = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(Convert(result.ftTimeStamp));
output[ii].TimestampSpecified = output[ii].Timestamp != DateTime.MinValue;
if (deallocate)
{
Marshal.DestroyStructure(pos, typeof(OpcRcw.Da.OPCITEMSTATE));
}
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMSTATE)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates a OPCITEMRESULT structures.
/// </summary>
internal static int[] GetItemResults(ref IntPtr pInput, int count, bool deallocate)
{
int[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new int[count];
var pos = pInput;
for (var ii = 0; ii < count; ii++)
{
var result = (OpcRcw.Da.OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OpcRcw.Da.OPCITEMRESULT));
output[ii] = result.hServer;
if (deallocate)
{
Marshal.FreeCoTaskMem(result.pBlob);
result.pBlob = IntPtr.Zero;
Marshal.DestroyStructure(pos, typeof(OpcRcw.Da.OPCITEMRESULT));
}
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMRESULT)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Allocates and marshals an array of OPCBROWSEELEMENT structures.
/// </summary>
internal static IntPtr GetItemStates(TsCDaItemValueResult[] input)
{
var output = IntPtr.Zero;
if (input != null && input.Length > 0)
{
output = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMSTATE)) * input.Length);
var pos = output;
for (var ii = 0; ii < input.Length; ii++)
{
var item = new OpcRcw.Da.OPCITEMSTATE();
item.hClient = System.Convert.ToInt32(input[ii].ClientHandle);
item.vDataValue = input[ii].Value;
item.wQuality = (input[ii].QualitySpecified) ? input[ii].Quality.GetCode() : (short)0;
item.ftTimeStamp = Convert(Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(input[ii].Timestamp));
item.wReserved = 0;
Marshal.StructureToPtr(item, pos, false);
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Da.OPCITEMSTATE)));
}
}
return output;
}
}
}

View File

@@ -0,0 +1,128 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
namespace Da
{
/// <summary>
/// Defines all well known COM DA HRESULT codes.
/// </summary>
internal struct Result
{
/// <remarks/>
public const int S_OK = +0x00000000; // 0x00000000
/// <remarks/>
public const int S_FALSE = +0x00000001; // 0x00000001
/// <remarks/>
public const int E_NOTIMPL = -0x7FFFBFFF; // 0x80004001
/// <remarks/>
public const int E_OUTOFMEMORY = -0x7FF8FFF2; // 0x8007000E
/// <remarks/>
public const int E_INVALIDARG = -0x7FF8FFA9; // 0x80070057
/// <remarks/>
public const int E_NOINTERFACE = -0x7FFFBFFE; // 0x80004002
/// <remarks/>
public const int E_POINTER = -0x7FFFBFFD; // 0x80004003
/// <remarks/>
public const int E_FAIL = -0x7FFFBFFB; // 0x80004005
/// <remarks/>
public const int CONNECT_E_NOCONNECTION = -0x7FFBFE00; // 0x80040200
/// <remarks/>
public const int CONNECT_E_ADVISELIMIT = -0x7FFBFDFF; // 0x80040201
/// <remarks/>
public const int DISP_E_TYPEMISMATCH = -0x7FFDFFFB; // 0x80020005
/// <remarks/>
public const int DISP_E_OVERFLOW = -0x7FFDFFF6; // 0x8002000A
/// <remarks/>
public const int E_INVALIDHANDLE = -0x3FFBFFFF; // 0xC0040001
/// <remarks/>
public const int E_BADTYPE = -0x3FFBFFFC; // 0xC0040004
/// <remarks/>
public const int E_PUBLIC = -0x3FFBFFFB; // 0xC0040005
/// <remarks/>
public const int E_BADRIGHTS = -0x3FFBFFFA; // 0xC0040006
/// <remarks/>
public const int E_UNKNOWNITEMID = -0x3FFBFFF9; // 0xC0040007
/// <remarks/>
public const int E_INVALIDITEMID = -0x3FFBFFF8; // 0xC0040008
/// <remarks/>
public const int E_INVALIDFILTER = -0x3FFBFFF7; // 0xC0040009
/// <remarks/>
public const int E_UNKNOWNPATH = -0x3FFBFFF6; // 0xC004000A
/// <remarks/>
public const int E_RANGE = -0x3FFBFFF5; // 0xC004000B
/// <remarks/>
public const int E_DUPLICATENAME = -0x3FFBFFF4; // 0xC004000C
/// <remarks/>
public const int S_UNSUPPORTEDRATE = +0x0004000D; // 0x0004000D
/// <remarks/>
public const int S_CLAMP = +0x0004000E; // 0x0004000E
/// <remarks/>
public const int S_INUSE = +0x0004000F; // 0x0004000F
/// <remarks/>
public const int E_INVALIDCONFIGFILE = -0x3FFBFFF0; // 0xC0040010
/// <remarks/>
public const int E_NOTFOUND = -0x3FFBFFEF; // 0xC0040011
/// <remarks/>
public const int E_INVALID_PID = -0x3FFBFDFD; // 0xC0040203
/// <remarks/>
public const int E_DEADBANDNOTSET = -0x3FFBFC00; // 0xC0040400
/// <remarks/>
public const int E_DEADBANDNOTSUPPORTED = -0x3FFBFBFF; // 0xC0040401
/// <remarks/>
public const int E_NOBUFFERING = -0x3FFBFBFE; // 0xC0040402
/// <remarks/>
public const int E_INVALIDCONTINUATIONPOINT = -0x3FFBFBFD; // 0xC0040403
/// <remarks/>
public const int S_DATAQUEUEOVERFLOW = +0x00040404; // 0x00040404
/// <remarks/>
public const int E_RATENOTSET = -0x3FFBFBFB; // 0xC0040405
/// <remarks/>
public const int E_NOTSUPPORTED = -0x3FFBFBFA; // 0xC0040406
}
}
namespace Cpx
{
/// <summary>
/// Defines all well known Complex Data HRESULT codes.
/// </summary>
internal struct Result
{
/// <remarks/>
public const int E_TYPE_CHANGED = -0x3FFBFBF9; // 0xC0040407
/// <remarks/>
public const int E_FILTER_DUPLICATE = -0x3FFBFBF8; // 0xC0040408
/// <remarks/>
public const int E_FILTER_INVALID = -0x3FFBFBF7; // 0xC0040409
/// <remarks/>
public const int E_FILTER_ERROR = -0x3FFBFBF6; // 0xC004040A
/// <remarks/>
public const int S_FILTER_NO_DATA = +0x0004040B; // 0xC004040B
}
}
}

View File

@@ -0,0 +1,984 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
using Technosoftware.DaAeHdaClient.Da;
using Technosoftware.DaAeHdaClient.Utilities;
using Technosoftware.OpcRcw.Da;
using Technosoftware.DaAeHdaClient.Com.Utilities;
#endregion
namespace Technosoftware.DaAeHdaClient.Com.Da
{
/// <summary>
/// A .NET wrapper for a COM server that implements the DA server interfaces.
/// </summary>
internal class Server : Com.Server, ITsDaServer
{
#region Fields
/// <summary>
/// The default result filters for the server.
/// </summary>
private int filters_ = (int)TsCDaResultFilter.All | (int)TsCDaResultFilter.ClientHandle;
/// <summary>
/// A table of active subscriptions for the server.
/// </summary>
private readonly Hashtable subscriptions_ = new Hashtable();
#endregion
#region Constructors
/// <summary>
/// Initializes the object.
/// </summary>
internal Server() { }
/// <summary>
/// Initializes the object with the specified COM server.
/// </summary>
internal Server(OpcUrl url, object server)
{
if (url == null) throw new ArgumentNullException(nameof(url));
url_ = (OpcUrl)url.Clone();
server_ = server;
}
#endregion
#region IDisposable Members
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing">If true managed and unmanaged resources can be disposed. If false only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (!disposed_)
{
lock (this)
{
if (disposing)
{
// Release managed resources.
if (server_ != null)
{
// release all groups.
foreach (Subscription subscription in subscriptions_.Values)
{
var methodName = "IOPCServer.RemoveGroup";
// remove subscription from server.
try
{
var state = subscription.GetState();
if (state != null)
{
var server = BeginComCall<IOPCServer>(methodName, true);
server?.RemoveGroup((int)state.ServerHandle, 0);
}
}
catch
{
// Ignore error during Dispose
}
finally
{
EndComCall(methodName);
}
// dispose of the subscription object (disconnects all subscription connections).
subscription.Dispose();
}
// clear subscription table.
subscriptions_.Clear();
}
}
// Release unmanaged resources.
// Set large fields to null.
if (server_ != null)
{
// release the COM server.
Technosoftware.DaAeHdaClient.Com.Interop.ReleaseServer(server_);
server_ = null;
}
}
// Call Dispose on your base class.
disposed_ = true;
}
base.Dispose(disposing);
}
private bool disposed_;
#endregion
#region Technosoftware.DaAeHdaClient.Com.Server Overrides
/// <summary>
/// Returns the localized text for the specified result code.
/// </summary>
/// <param name="locale">The locale name in the format "[languagecode]-[country/regioncode]".</param>
/// <param name="resultId">The result code identifier.</param>
/// <returns>A message localized for the best match for the requested locale.</returns>
public override string GetErrorText(string locale, OpcResult resultId)
{
lock (this)
{
if (server_ == null) throw new NotConnectedException();
var methodName = "IOPCServer.GetErrorString";
// invoke COM method.
try
{
var server = BeginComCall<IOPCServer>(methodName, true);
(server).GetErrorString(
resultId.Code,
Technosoftware.DaAeHdaClient.Com.Interop.GetLocale(locale),
out var errorText);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
return errorText;
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException("IOPCServer.GetErrorString", e);
}
finally
{
EndComCall(methodName);
}
}
}
#endregion
#region Technosoftware.DaAeHdaClient.IOpcServer Members
/// <summary>
/// Returns the filters applied by the server to any item results returned to the client.
/// </summary>
/// <returns>A bit mask indicating which fields should be returned in any item results.</returns>
public int GetResultFilters()
{
lock (this)
{
if (server_ == null) throw new NotConnectedException();
return filters_;
}
}
/// <summary>
/// Sets the filters applied by the server to any item results returned to the client.
/// </summary>
/// <param name="filters">A bit mask indicating which fields should be returned in any item results.</param>
public void SetResultFilters(int filters)
{
lock (this)
{
if (server_ == null) throw new NotConnectedException();
filters_ = filters;
}
}
/// <summary>
/// Returns the current server status.
/// </summary>
/// <returns>The current server status.</returns>
public OpcServerStatus GetServerStatus()
{
lock (this)
{
if (server_ == null) throw new NotConnectedException();
var methodName = "IOPCServer.GetStatus";
// initialize arguments.
IntPtr pStatus;
// invoke COM method.
try
{
var server = BeginComCall<IOPCServer>(methodName, true);
(server).GetStatus(out pStatus);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
// return status.
return Interop.GetServerStatus(ref pStatus, true);
}
}
/// <summary>
/// Reads the current values for a set of items.
/// </summary>
/// <param name="items">The set of items to read.</param>
/// <returns>The results of the read operation for each item.</returns>
public virtual TsCDaItemValueResult[] Read(TsCDaItem[] items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
lock (this)
{
var methodName = "IOPCItemIO.Read";
if (server_ == null) throw new NotConnectedException();
var count = items.Length;
if (count == 0) throw new ArgumentOutOfRangeException(nameof(items.Length), @"0");
// initialize arguments.
var itemIDs = new string[count];
var maxAges = new int[count];
for (var ii = 0; ii < count; ii++)
{
itemIDs[ii] = items[ii].ItemName;
maxAges[ii] = (items[ii].MaxAgeSpecified) ? items[ii].MaxAge : 0;
}
var pValues = IntPtr.Zero;
var pQualities = IntPtr.Zero;
var pTimestamps = IntPtr.Zero;
var pErrors = IntPtr.Zero;
// invoke COM method.
try
{
var server = BeginComCall<IOPCItemIO>(methodName, true);
server.Read(
count,
itemIDs,
maxAges,
out pValues,
out pQualities,
out pTimestamps,
out pErrors);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
// unmarshal results.
var values = Technosoftware.DaAeHdaClient.Com.Interop.GetVARIANTs(ref pValues, count, true);
var qualities = Technosoftware.DaAeHdaClient.Com.Interop.GetInt16s(ref pQualities, count, true);
var timestamps = Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIMEs(ref pTimestamps, count, true);
var errors = Technosoftware.DaAeHdaClient.Com.Interop.GetInt32s(ref pErrors, count, true);
// pre-fetch the current locale to use for data conversions.
var locale = GetLocale();
// construct result array.
var results = new TsCDaItemValueResult[count];
for (var ii = 0; ii < results.Length; ii++)
{
results[ii] = new TsCDaItemValueResult(items[ii]);
results[ii].ServerHandle = null;
results[ii].Value = values[ii];
results[ii].Quality = new TsCDaQuality(qualities[ii]);
results[ii].QualitySpecified = true;
results[ii].Timestamp = timestamps[ii];
results[ii].TimestampSpecified = timestamps[ii] != DateTime.MinValue;
results[ii].Result = Utilities.Interop.GetResultId(errors[ii]);
results[ii].DiagnosticInfo = null;
// convert COM code to unified DA code.
if (errors[ii] == Result.E_BADRIGHTS) { results[ii].Result = new OpcResult(OpcResult.Da.E_WRITEONLY, Result.E_BADRIGHTS); }
// convert the data type since the server does not support the feature.
if (results[ii].Value != null && items[ii].ReqType != null)
{
try
{
results[ii].Value = ChangeType(values[ii], items[ii].ReqType, locale);
}
catch (Exception e)
{
results[ii].Value = null;
results[ii].Quality = TsCDaQuality.Bad;
results[ii].QualitySpecified = true;
results[ii].Timestamp = DateTime.MinValue;
results[ii].TimestampSpecified = false;
if (e.GetType() == typeof(OverflowException))
{
results[ii].Result = Utilities.Interop.GetResultId(Result.E_RANGE);
}
else
{
results[ii].Result = Utilities.Interop.GetResultId(Result.E_BADTYPE);
}
}
}
// apply request options.
if ((filters_ & (int)TsCDaResultFilter.ItemName) == 0) results[ii].ItemName = null;
if ((filters_ & (int)TsCDaResultFilter.ItemPath) == 0) results[ii].ItemPath = null;
if ((filters_ & (int)TsCDaResultFilter.ClientHandle) == 0) results[ii].ClientHandle = null;
if ((filters_ & (int)TsCDaResultFilter.ItemTime) == 0)
{
results[ii].Timestamp = DateTime.MinValue;
results[ii].TimestampSpecified = false;
}
}
// return results.
return results;
}
}
/// <summary>
/// Writes the value, quality and timestamp for a set of items.
/// </summary>
/// <param name="items">The set of item values to write.</param>
/// <returns>The results of the write operation for each item.</returns>
public virtual OpcItemResult[] Write(TsCDaItemValue[] items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
lock (this)
{
if (server_ == null) throw new NotConnectedException();
var methodName = "IOPCItemIO.WriteVQT";
var count = items.Length;
if (count == 0) throw new ArgumentOutOfRangeException("items.Length", "0");
// initialize arguments.
var itemIDs = new string[count];
for (var ii = 0; ii < count; ii++)
{
itemIDs[ii] = items[ii].ItemName;
}
var values = Interop.GetOPCITEMVQTs(items);
var pErrors = IntPtr.Zero;
// invoke COM method.
try
{
var server = BeginComCall<IOPCItemIO>(methodName, true);
server.WriteVQT(
count,
itemIDs,
values,
out pErrors);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
// unmarshal results.
var errors = Utilities.Interop.GetInt32s(ref pErrors, count, true);
// construct result array.
var results = new OpcItemResult[count];
for (var ii = 0; ii < count; ii++)
{
results[ii] = new OpcItemResult(items[ii]);
results[ii].ServerHandle = null;
results[ii].Result = Utilities.Interop.GetResultId(errors[ii]);
results[ii].DiagnosticInfo = null;
// convert COM code to unified DA code.
if (errors[ii] == Result.E_BADRIGHTS) { results[ii].Result = new OpcResult(OpcResult.Da.E_READONLY, Result.E_BADRIGHTS); }
// apply request options.
if ((filters_ & (int)TsCDaResultFilter.ItemName) == 0) results[ii].ItemName = null;
if ((filters_ & (int)TsCDaResultFilter.ItemPath) == 0) results[ii].ItemPath = null;
if ((filters_ & (int)TsCDaResultFilter.ClientHandle) == 0) results[ii].ClientHandle = null;
}
// return results.
return results;
}
}
/// <summary>
/// Creates a new subscription.
/// </summary>
/// <param name="state">The initial state of the subscription.</param>
/// <returns>The new subscription object.</returns>
public ITsCDaSubscription CreateSubscription(TsCDaSubscriptionState state)
{
if (state == null) throw new ArgumentNullException(nameof(state));
lock (this)
{
if (server_ == null) throw new NotConnectedException();
var methodName = "IOPCServer.AddGroup";
// copy the subscription state.
var result = (TsCDaSubscriptionState)state.Clone();
// initialize arguments.
var iid = typeof(IOPCItemMgt).GUID;
object group = null;
var serverHandle = 0;
var revisedUpdateRate = 0;
var hDeadband = GCHandle.Alloc(result.Deadband, GCHandleType.Pinned);
// invoke COM method.
try
{
var server = BeginComCall<IOPCServer>(methodName, true);
server.AddGroup(
(result.Name != null) ? result.Name : "",
(result.Active) ? 1 : 0,
result.UpdateRate,
0,
IntPtr.Zero,
hDeadband.AddrOfPinnedObject(),
Technosoftware.DaAeHdaClient.Com.Interop.GetLocale(result.Locale),
out serverHandle,
out revisedUpdateRate,
ref iid,
out group);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Utilities.Interop.CreateException(methodName, e);
}
finally
{
if (hDeadband.IsAllocated)
{
hDeadband.Free();
}
EndComCall(methodName);
}
if (group == null) throw new OpcResultException(OpcResult.E_FAIL, "The subscription was not created.");
methodName = "IOPCGroupStateMgt2.SetKeepAlive";
// set the keep alive rate if requested.
try
{
var keepAlive = 0;
var comObject = BeginComCall<IOPCGroupStateMgt2>(group, methodName, true);
comObject.SetKeepAlive(result.KeepAlive, out keepAlive);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
result.KeepAlive = keepAlive;
}
catch (Exception e1)
{
result.KeepAlive = 0;
ComCallError(methodName, e1);
}
finally
{
EndComCall(methodName);
}
// save server handle.
result.ServerHandle = serverHandle;
// set the revised update rate.
if (revisedUpdateRate > result.UpdateRate)
{
result.UpdateRate = revisedUpdateRate;
}
// create the subscription object.
var subscription = CreateSubscription(group, result, filters_);
// index by server handle.
subscriptions_[serverHandle] = subscription;
// return subscription.
return subscription;
}
}
/// <summary>
/// Cancels a subscription and releases all resources allocated for it.
/// </summary>
/// <param name="subscription">The subscription to cancel.</param>
public void CancelSubscription(ITsCDaSubscription subscription)
{
if (subscription == null) throw new ArgumentNullException(nameof(subscription));
lock (this)
{
if (server_ == null) throw new NotConnectedException();
var methodName = "IOPCServer.RemoveGroup";
// validate argument.
if (!typeof(Subscription).IsInstanceOfType(subscription))
{
throw new ArgumentException("Incorrect object type.", nameof(subscription));
}
// get the subscription state.
var state = subscription.GetState();
if (!subscriptions_.ContainsKey(state.ServerHandle))
{
throw new ArgumentException("Handle not found.", nameof(subscription));
}
subscriptions_.Remove(state.ServerHandle);
// release all subscription resources.
subscription.Dispose();
// invoke COM method.
try
{
var server = BeginComCall<IOPCServer>(methodName, true);
server.RemoveGroup((int)state.ServerHandle, 0);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Utilities.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
}
}
/// <summary>
/// Fetches the children of a branch that meet the filter criteria.
/// </summary>
/// <param name="itemId">The identifier of branch which is the target of the search.</param>
/// <param name="filters">The filters to use to limit the set of child elements returned.</param>
/// <param name="position">An object used to continue a browse that could not be completed.</param>
/// <returns>The set of elements found.</returns>
public virtual TsCDaBrowseElement[] Browse(
OpcItem itemId,
TsCDaBrowseFilters filters,
out TsCDaBrowsePosition position)
{
if (filters == null) throw new ArgumentNullException(nameof(filters));
lock (this)
{
if (server_ == null) throw new NotConnectedException();
var methodName = "IOPCBrowse.Browse";
position = null;
// initialize arguments.
var count = 0;
var moreElements = 0;
var pContinuationPoint = IntPtr.Zero;
var pElements = IntPtr.Zero;
// invoke COM method.
try
{
var server = BeginComCall<IOPCBrowse>(methodName, true);
server.Browse(
(itemId != null && itemId.ItemName != null) ? itemId.ItemName : "",
ref pContinuationPoint,
filters.MaxElementsReturned,
Interop.GetBrowseFilter(filters.BrowseFilter),
(filters.ElementNameFilter != null) ? filters.ElementNameFilter : "",
(filters.VendorFilter != null) ? filters.VendorFilter : "",
(filters.ReturnAllProperties) ? 1 : 0,
(filters.ReturnPropertyValues) ? 1 : 0,
(filters.PropertyIDs != null) ? filters.PropertyIDs.Length : 0,
Interop.GetPropertyIDs(filters.PropertyIDs),
out moreElements,
out count,
out pElements);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
// unmarshal results.
var elements = Interop.GetBrowseElements(ref pElements, count, true);
var continuationPoint = Marshal.PtrToStringUni(pContinuationPoint);
Marshal.FreeCoTaskMem(pContinuationPoint);
// check if more results exist.
if (moreElements != 0 || (continuationPoint != null && continuationPoint != ""))
{
// allocate new browse position object.
position = new BrowsePosition(itemId, filters, continuationPoint);
}
// process results.
ProcessResults(elements, filters.PropertyIDs);
return elements;
}
}
/// <summary>
/// Continues a browse operation with previously specified search criteria.
/// </summary>
/// <param name="position">An object containing the browse operation state information.</param>
/// <returns>The set of elements found.</returns>
public virtual TsCDaBrowseElement[] BrowseNext(ref TsCDaBrowsePosition position)
{
lock (this)
{
if (server_ == null) throw new NotConnectedException();
var methodName = "IOPCBrowse.Browse";
// check for valid position object.
if (position == null || position.GetType() != typeof(BrowsePosition))
{
throw new BrowseCannotContinueException();
}
var pos = (BrowsePosition)position;
// check for valid continuation point.
if (pos == null || pos.ContinuationPoint == null || pos.ContinuationPoint == "")
{
throw new BrowseCannotContinueException();
}
// initialize arguments.
var count = 0;
var moreElements = 0;
var itemID = ((BrowsePosition)position).ItemID;
var filters = ((BrowsePosition)position).Filters;
var pContinuationPoint = Marshal.StringToCoTaskMemUni(pos.ContinuationPoint);
var pElements = IntPtr.Zero;
// invoke COM method.
try
{
var server = BeginComCall<IOPCBrowse>(methodName, true);
server.Browse(
(itemID != null && itemID.ItemName != null) ? itemID.ItemName : "",
ref pContinuationPoint,
filters.MaxElementsReturned,
Interop.GetBrowseFilter(filters.BrowseFilter),
(filters.ElementNameFilter != null) ? filters.ElementNameFilter : "",
(filters.VendorFilter != null) ? filters.VendorFilter : "",
(filters.ReturnAllProperties) ? 1 : 0,
(filters.ReturnPropertyValues) ? 1 : 0,
(filters.PropertyIDs != null) ? filters.PropertyIDs.Length : 0,
Interop.GetPropertyIDs(filters.PropertyIDs),
out moreElements,
out count,
out pElements);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
// unmarshal results.
var elements = Interop.GetBrowseElements(ref pElements, count, true);
pos.ContinuationPoint = Marshal.PtrToStringUni(pContinuationPoint);
Marshal.FreeCoTaskMem(pContinuationPoint);
// check if more no results exist.
if (moreElements == 0 && (pos.ContinuationPoint == null || pos.ContinuationPoint == ""))
{
position = null;
}
// process results.
ProcessResults(elements, filters.PropertyIDs);
return elements;
}
}
/// <summary>
/// Returns the item properties for a set of items.
/// </summary>
/// <param name="itemIds">A list of item identifiers.</param>
/// <param name="propertyIDs">A list of properties to fetch for each item.</param>
/// <param name="returnValues">Whether the property values should be returned with the properties.</param>
/// <returns>A list of properties for each item.</returns>
public virtual TsCDaItemPropertyCollection[] GetProperties(
OpcItem[] itemIds,
TsDaPropertyID[] propertyIDs,
bool returnValues)
{
if (itemIds == null) throw new ArgumentNullException(nameof(itemIds));
lock (this)
{
if (server_ == null) throw new NotConnectedException();
var methodName = "IOPCBrowse.GetProperties";
// initialize arguments.
var pItemIDs = new string[itemIds.Length];
for (var ii = 0; ii < itemIds.Length; ii++)
{
pItemIDs[ii] = itemIds[ii].ItemName;
}
var pPropertyLists = IntPtr.Zero;
// invoke COM method.
try
{
var server = BeginComCall<IOPCBrowse>(methodName, true);
server.GetProperties(
itemIds.Length,
pItemIDs,
(returnValues) ? 1 : 0,
(propertyIDs != null) ? propertyIDs.Length : 0,
Interop.GetPropertyIDs(propertyIDs),
out pPropertyLists);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
// unmarshal results.
var resultLists = Interop.GetItemPropertyCollections(ref pPropertyLists, itemIds.Length, true);
// replace integer codes with qnames passed in.
if (propertyIDs != null && propertyIDs.Length > 0)
{
foreach (var resultList in resultLists)
{
for (var ii = 0; ii < resultList.Count; ii++)
{
resultList[ii].ID = propertyIDs[ii];
}
}
}
// return the results.
return resultLists;
}
}
#endregion
#region Private Methods
/// <summary>
/// Converts a value to the specified type using the specified locale.
/// </summary>
protected object ChangeType(object source, Type type, string locale)
{
var culture = Thread.CurrentThread.CurrentCulture;
// override the current thread culture to ensure conversions happen correctly.
try
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(locale);
}
catch
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
}
try
{
var result = OpcConvert.ChangeType(source, type);
// check for overflow converting to float.
if (typeof(float) == type)
{
if (float.IsInfinity(Convert.ToSingle(result)))
{
throw new OverflowException();
}
}
return result;
}
// restore the current thread culture after conversion.
finally
{
Thread.CurrentThread.CurrentCulture = culture;
}
}
/// <summary>
/// Creates a new instance of a subscription.
/// </summary>
protected virtual Subscription CreateSubscription(
object group,
TsCDaSubscriptionState state,
int filters)
{
return new Subscription(group, state, filters);
}
/// <summary>
/// Updates the properties to convert COM values to OPC .NET API results.
/// </summary>
private void ProcessResults(TsCDaBrowseElement[] elements, TsDaPropertyID[] propertyIds)
{
// check for null.
if (elements == null)
{
return;
}
// process each element.
foreach (var element in elements)
{
// check if no properties.
if (element.Properties == null)
{
continue;
}
// process each property.
foreach (var property in element.Properties)
{
// replace the property ids which on contain the codes with the proper qualified names passed in.
if (propertyIds != null)
{
foreach (var propertyId in propertyIds)
{
if (property.ID.Code == propertyId.Code)
{
property.ID = propertyId;
break;
}
}
}
}
}
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,586 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using Technosoftware.DaAeHdaClient.Da;
using Technosoftware.DaAeHdaClient.Com.Da;
using Technosoftware.DaAeHdaClient.Utilities;
using Technosoftware.OpcRcw.Da;
using Technosoftware.DaAeHdaClient.Com.Utilities;
#endregion
namespace Technosoftware.DaAeHdaClient.Com.Da20
{
/// <summary>
/// An in-process wrapper for a remote OPC Data Access 2.0X subscription.
/// </summary>
internal class Subscription : Technosoftware.DaAeHdaClient.Com.Da.Subscription
{
#region Constructors
/// <summary>
/// Initializes a new instance of a subscription.
/// </summary>
internal Subscription(object subscription, TsCDaSubscriptionState state, int filters) :
base(subscription, state, filters)
{
}
#endregion
#region ISubscription Members
/// <summary>
/// Returns the current state of the subscription.
/// </summary>
/// <returns>The current state of the subscription.</returns>
public override TsCDaSubscriptionState GetState()
{
if (subscription_ == null) throw new NotConnectedException();
lock (lock_)
{
var methodName = "IOPCGroupStateMgt.GetState";
var state = new TsCDaSubscriptionState { ClientHandle = _handle };
string name = null;
try
{
var active = 0;
var updateRate = 0;
float deadband = 0;
var timebias = 0;
var localeID = 0;
var clientHandle = 0;
var serverHandle = 0;
var subscription = BeginComCall<IOPCGroupStateMgt>(methodName, true);
subscription.GetState(
out updateRate,
out active,
out name,
out timebias,
out deadband,
out localeID,
out clientHandle,
out serverHandle);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
state.Name = name;
state.ServerHandle = serverHandle;
state.Active = active != 0;
state.UpdateRate = updateRate;
state.TimeBias = timebias;
state.Deadband = deadband;
state.Locale = Technosoftware.DaAeHdaClient.Com.Interop.GetLocale(localeID);
// cache the name separately.
name_ = state.Name;
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
state.KeepAlive = 0;
return state;
}
}
/// <summary>
/// Tells the server to send an data change update for all subscription items containing the cached values.
/// </summary>
public override void Refresh()
{
if (subscription_ == null) throw new NotConnectedException();
lock (lock_)
{
var methodName = "IOPCAsyncIO2.Refresh2";
try
{
var cancelID = 0;
var subscription = BeginComCall<IOPCAsyncIO2>(methodName, true);
subscription.Refresh2(OPCDATASOURCE.OPC_DS_CACHE, ++_counter, out cancelID);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Utilities.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
}
}
/// <summary>
/// Sets whether data change callbacks are enabled.
/// </summary>
public override void SetEnabled(bool enabled)
{
if (subscription_ == null) throw new NotConnectedException();
lock (lock_)
{
var methodName = "IOPCAsyncIO2.SetEnable";
try
{
var subscription = BeginComCall<IOPCAsyncIO2>(methodName, true);
subscription.SetEnable((enabled) ? 1 : 0);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Utilities.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
}
}
/// <summary>
/// Gets whether data change callbacks are enabled.
/// </summary>
public override bool GetEnabled()
{
if (subscription_ == null) throw new NotConnectedException();
lock (lock_)
{
var methodName = "IOPCAsyncIO2.GetEnable";
try
{
var enabled = 0;
var subscription = BeginComCall<IOPCAsyncIO2>(methodName, true);
subscription.GetEnable(out enabled);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
return enabled != 0;
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Utilities.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
}
}
#endregion
#region Private and Protected Members
/// <summary>
/// Reads a set of items using DA2.0 interfaces.
/// </summary>
protected override TsCDaItemValueResult[] Read(OpcItem[] itemIDs, TsCDaItem[] items)
{
if (subscription_ == null) throw new NotConnectedException();
// create result list.
var results = new TsCDaItemValueResult[itemIDs.Length];
// separate into cache reads and device reads.
var cacheReads = new ArrayList();
var deviceReads = new ArrayList();
for (var ii = 0; ii < itemIDs.Length; ii++)
{
results[ii] = new TsCDaItemValueResult(itemIDs[ii]);
if (items[ii].MaxAgeSpecified && (items[ii].MaxAge < 0 || items[ii].MaxAge == int.MaxValue))
{
cacheReads.Add(results[ii]);
}
else
{
deviceReads.Add(results[ii]);
}
}
// read items from cache.
if (cacheReads.Count > 0)
{
Read((TsCDaItemValueResult[])cacheReads.ToArray(typeof(TsCDaItemValueResult)), true);
}
// read items from device.
if (deviceReads.Count > 0)
{
Read((TsCDaItemValueResult[])deviceReads.ToArray(typeof(TsCDaItemValueResult)), false);
}
// return results.
return results;
}
/// <summary>
/// Reads a set of values.
/// </summary>
private void Read(TsCDaItemValueResult[] items, bool cache)
{
if (items.Length == 0) return;
// marshal input parameters.
var serverHandles = new int[items.Length];
for (var ii = 0; ii < items.Length; ii++)
{
serverHandles[ii] = (int)items[ii].ServerHandle;
}
// initialize output parameters.
var pValues = IntPtr.Zero;
var pErrors = IntPtr.Zero;
var methodName = "IOPCSyncIO.Read";
try
{
var subscription = BeginComCall<IOPCSyncIO>(methodName, true);
subscription.Read(
(cache) ? OPCDATASOURCE.OPC_DS_CACHE : OPCDATASOURCE.OPC_DS_DEVICE,
items.Length,
serverHandles,
out pValues,
out pErrors);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Utilities.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
// unmarshal output parameters.
var values = Technosoftware.DaAeHdaClient.Com.Da.Interop.GetItemValues(ref pValues, items.Length, true);
var errors = Utilities.Interop.GetInt32s(ref pErrors, items.Length, true);
// construct results list.
for (var ii = 0; ii < items.Length; ii++)
{
items[ii].Result = Utilities.Interop.GetResultId(errors[ii]);
items[ii].DiagnosticInfo = null;
// convert COM code to unified DA code.
if (errors[ii] == Result.E_BADRIGHTS) { items[ii].Result = new OpcResult(OpcResult.Da.E_WRITEONLY, Result.E_BADRIGHTS); }
if (items[ii].Result.Succeeded())
{
items[ii].Value = values[ii].Value;
items[ii].Quality = values[ii].Quality;
items[ii].QualitySpecified = values[ii].QualitySpecified;
items[ii].Timestamp = values[ii].Timestamp;
items[ii].TimestampSpecified = values[ii].TimestampSpecified;
}
}
}
/// <summary>
/// Writes a set of items using DA2.0 interfaces.
/// </summary>
protected override OpcItemResult[] Write(OpcItem[] itemIDs, TsCDaItemValue[] items)
{
if (subscription_ == null) throw new NotConnectedException();
// create result list.
var results = new OpcItemResult[itemIDs.Length];
// construct list of valid items to write.
var writeItems = new ArrayList(itemIDs.Length);
var writeValues = new ArrayList(itemIDs.Length);
for (var ii = 0; ii < items.Length; ii++)
{
results[ii] = new OpcItemResult(itemIDs[ii]);
if (items[ii].QualitySpecified || items[ii].TimestampSpecified)
{
results[ii].Result = OpcResult.Da.E_NO_WRITEQT;
results[ii].DiagnosticInfo = null;
continue;
}
writeItems.Add(results[ii]);
writeValues.Add(items[ii]);
}
// check if there is nothing to do.
if (writeItems.Count == 0)
{
return results;
}
// initialize input parameters.
var serverHandles = new int[writeItems.Count];
var values = new object[writeItems.Count];
for (var ii = 0; ii < serverHandles.Length; ii++)
{
serverHandles[ii] = (int)((OpcItemResult)writeItems[ii]).ServerHandle;
values[ii] = Utilities.Interop.GetVARIANT(((TsCDaItemValue)writeValues[ii]).Value);
}
var pErrors = IntPtr.Zero;
// write item values.
var methodName = "IOPCSyncIO.Write";
try
{
var subscription = BeginComCall<IOPCSyncIO>(methodName, true);
subscription.Write(
writeItems.Count,
serverHandles,
values,
out pErrors);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Utilities.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
// unmarshal results.
var errors = Utilities.Interop.GetInt32s(ref pErrors, writeItems.Count, true);
for (var ii = 0; ii < writeItems.Count; ii++)
{
var result = (OpcItemResult)writeItems[ii];
result.Result = Utilities.Interop.GetResultId(errors[ii]);
result.DiagnosticInfo = null;
// convert COM code to unified DA code.
if (errors[ii] == Result.E_BADRIGHTS) { results[ii].Result = new OpcResult(OpcResult.Da.E_READONLY, Result.E_BADRIGHTS); }
}
// return results.
return results;
}
/// <summary>
/// Begins an asynchronous read of a set of items using DA2.0 interfaces.
/// </summary>
protected override OpcItemResult[] BeginRead(
OpcItem[] itemIDs,
TsCDaItem[] items,
int requestID,
out int cancelID)
{
var methodName = "IOPCAsyncIO2.Read";
try
{
// marshal input parameters.
var serverHandles = new int[itemIDs.Length];
for (var ii = 0; ii < itemIDs.Length; ii++)
{
serverHandles[ii] = (int)itemIDs[ii].ServerHandle;
}
// initialize output parameters.
var pErrors = IntPtr.Zero;
var subscription = BeginComCall<IOPCAsyncIO2>(methodName, true);
subscription.Read(
itemIDs.Length,
serverHandles,
requestID,
out cancelID,
out pErrors);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
// unmarshal output parameters.
var errors = Utilities.Interop.GetInt32s(ref pErrors, itemIDs.Length, true);
// create item results.
var results = new OpcItemResult[itemIDs.Length];
for (var ii = 0; ii < itemIDs.Length; ii++)
{
results[ii] = new OpcItemResult(itemIDs[ii]);
results[ii].Result = Utilities.Interop.GetResultId(errors[ii]);
results[ii].DiagnosticInfo = null;
// convert COM code to unified DA code.
if (errors[ii] == Result.E_BADRIGHTS) { results[ii].Result = new OpcResult(OpcResult.Da.E_WRITEONLY, Result.E_BADRIGHTS); }
}
// return results.
return results;
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Utilities.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
}
/// <summary>
/// Begins an asynchronous write for a set of items using DA2.0 interfaces.
/// </summary>
protected override OpcItemResult[] BeginWrite(
OpcItem[] itemIDs,
TsCDaItemValue[] items,
int requestID,
out int cancelID)
{
cancelID = 0;
var validItems = new ArrayList();
var validValues = new ArrayList();
// construct initial result list.
var results = new OpcItemResult[itemIDs.Length];
for (var ii = 0; ii < itemIDs.Length; ii++)
{
results[ii] = new OpcItemResult(itemIDs[ii]);
results[ii].Result = OpcResult.S_OK;
results[ii].DiagnosticInfo = null;
if (items[ii].QualitySpecified || items[ii].TimestampSpecified)
{
results[ii].Result = OpcResult.Da.E_NO_WRITEQT;
results[ii].DiagnosticInfo = null;
continue;
}
validItems.Add(results[ii]);
validValues.Add(Utilities.Interop.GetVARIANT(items[ii].Value));
}
// check if any valid items exist.
if (validItems.Count == 0)
{
return results;
}
var methodName = "IOPCAsyncIO2.Write";
try
{
// initialize input parameters.
var serverHandles = new int[validItems.Count];
for (var ii = 0; ii < validItems.Count; ii++)
{
serverHandles[ii] = (int)((OpcItemResult)validItems[ii]).ServerHandle;
}
// write to sever.
var pErrors = IntPtr.Zero;
var subscription = BeginComCall<IOPCAsyncIO2>(methodName, true);
subscription.Write(
validItems.Count,
serverHandles,
(object[])validValues.ToArray(typeof(object)),
requestID,
out cancelID,
out pErrors);
if (DCOMCallWatchdog.IsCancelled)
{
throw new Exception($"{methodName} call was cancelled due to response timeout");
}
// unmarshal results.
var errors = Utilities.Interop.GetInt32s(ref pErrors, validItems.Count, true);
// create result list.
for (var ii = 0; ii < validItems.Count; ii++)
{
var result = (OpcItemResult)validItems[ii];
result.Result = Utilities.Interop.GetResultId(errors[ii]);
result.DiagnosticInfo = null;
// convert COM code to unified DA code.
if (errors[ii] == Result.E_BADRIGHTS) { results[ii].Result = new OpcResult(OpcResult.Da.E_READONLY, Result.E_BADRIGHTS); }
}
}
catch (Exception e)
{
ComCallError(methodName, e);
throw Utilities.Interop.CreateException(methodName, e);
}
finally
{
EndComCall(methodName);
}
// return results.
return results;
}
#endregion
}
}

View File

@@ -0,0 +1,128 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Runtime.InteropServices;
using Technosoftware.OpcRcw.Comn;
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
/// <summary>
/// A wrapper for the COM IEnumString interface.
/// </summary>
internal class EnumString : IDisposable
{
/// <summary>
/// A reference to the remote COM object.
/// </summary>
private IEnumString m_enumerator = null;
/// <summary>
/// Initializes the object with an enumerator.
/// </summary>
public EnumString(object enumerator)
{
m_enumerator = (IEnumString)enumerator;
}
/// <summary>
/// Releases the remote COM object.
/// </summary>
public void Dispose()
{
Utilities.Interop.ReleaseServer(m_enumerator);
m_enumerator = null;
}
//=====================================================================
// IEnumString
/// <summary>
/// Fetches the next subscription of strings.
/// </summary>
public string[] Next(int count)
{
try
{
// create buffer.
var buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr))*count);
try
{
// fetch next subscription of strings.
var fetched = 0;
m_enumerator.RemoteNext(
count,
buffer,
out fetched);
// return empty array if at end of list.
if (fetched == 0)
{
return new string[0];
}
return Interop.GetUnicodeStrings(ref buffer, fetched, true);
}
finally
{
Marshal.FreeCoTaskMem(buffer);
}
}
// return null on any error.
catch (Exception)
{
return null;
}
}
/// <summary>
/// Skips a number of strings.
/// </summary>
public void Skip(int count)
{
m_enumerator.Skip(count);
}
/// <summary>
/// Sets pointer to the start of the list.
/// </summary>
public void Reset()
{
m_enumerator.Reset();
}
/// <summary>
/// Clones the enumerator.
/// </summary>
public EnumString Clone()
{
IEnumString enumerator;
m_enumerator.Clone(out enumerator);
return new EnumString(enumerator);
}
}
}

View File

@@ -0,0 +1,44 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
/// <summary>
/// The COM FILETIME structure.
/// </summary>
public struct FILETIME
{
/// <summary>
/// The least significant DWORD.
/// </summary>
public int dwLowDateTime;
/// <summary>
/// The most significant DWORD.
/// </summary>
public int dwHighDateTime;
}
}

View File

@@ -0,0 +1,290 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Xml;
using System.Net;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Collections.Generic;
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
/// <summary>
/// The default class used to instantiate server objects.
/// </summary>
[Serializable]
public class Factory : OpcFactory
{
//======================================================================
// Construction
/// <summary>
/// Initializes an instance for use for in process objects.
/// </summary>
public Factory() : base(null)
{
// do nothing.
}
//======================================================================
// ISerializable
/// <summary>
/// Contructs a server by de-serializing its URL from the stream.
/// </summary>
protected Factory(SerializationInfo info, StreamingContext context) : base(info, context)
{
// do nothing.
}
//======================================================================
// IOpcFactory
/// <summary>
/// Creates a new instance of the server.
/// </summary>
public override IOpcServer CreateInstance(OpcUrl url, OpcConnectData connectData)
{
var comServer = Factory.Connect(url, connectData);
if (comServer == null)
{
return null;
}
Server server = null;
Type interfaceType = null;
try
{
if (string.IsNullOrEmpty(url.Scheme))
{
throw new NotSupportedException(string.Format("The URL scheme '{0}' is not supported.", url.Scheme));
}
// DA
else if (url.Scheme == OpcUrlScheme.DA)
{
// Verify that it is a DA server.
if (!typeof(OpcRcw.Da.IOPCServer).IsInstanceOfType(comServer))
{
interfaceType = typeof(OpcRcw.Da.IOPCServer);
throw new NotSupportedException();
}
// DA 3.00
if (!ForceDa20Usage && typeof(OpcRcw.Da.IOPCBrowse).IsInstanceOfType(comServer) && typeof(OpcRcw.Da.IOPCItemIO).IsInstanceOfType(comServer))
{
server = new Technosoftware.DaAeHdaClient.Com.Da.Server(url, comServer);
}
// DA 2.XX
else if (typeof(OpcRcw.Da.IOPCItemProperties).IsInstanceOfType(comServer))
{
server = new Technosoftware.DaAeHdaClient.Com.Da20.Server(url, comServer);
}
else
{
interfaceType = typeof(OpcRcw.Da.IOPCItemProperties);
throw new NotSupportedException();
}
}
// AE
else if (url.Scheme == OpcUrlScheme.AE)
{
// Verify that it is a AE server.
if (!typeof(OpcRcw.Ae.IOPCEventServer).IsInstanceOfType(comServer))
{
interfaceType = typeof(OpcRcw.Ae.IOPCEventServer);
throw new NotSupportedException();
}
server = new Technosoftware.DaAeHdaClient.Com.Ae.Server(url, comServer);
}
// HDA
else if (url.Scheme == OpcUrlScheme.HDA)
{
// Verify that it is a HDA server.
if (!typeof(OpcRcw.Hda.IOPCHDA_Server).IsInstanceOfType(comServer))
{
interfaceType = typeof(OpcRcw.Hda.IOPCHDA_Server);
throw new NotSupportedException();
}
server = new Technosoftware.DaAeHdaClient.Com.Hda.Server(url, comServer);
}
// All other specifications not supported yet.
else
{
throw new NotSupportedException(string.Format("The URL scheme '{0}' is not supported.", url.Scheme));
}
}
catch (NotSupportedException)
{
Utilities.Interop.ReleaseServer(server);
server = null;
if (interfaceType != null)
{
var message = new StringBuilder();
message.AppendFormat("The COM server does not support the interface ");
message.AppendFormat("'{0}'.", interfaceType.FullName);
message.Append("\r\n\r\nThis problem could be caused by:\r\n");
message.Append("- incorrectly installed proxy/stubs.\r\n");
message.Append("- problems with the DCOM security settings.\r\n");
message.Append("- a personal firewall (sometimes activated by default).\r\n");
throw new NotSupportedException(message.ToString());
}
throw;
}
catch (Exception)
{
Utilities.Interop.ReleaseServer(server);
throw;
}
// initialize the wrapper object.
if (server != null)
{
server.Initialize(url, connectData);
}
SupportedSpecifications = new List<OpcSpecification>();
if (server is Com.Da20.Server)
{
SupportedSpecifications.Add(OpcSpecification.OPC_DA_20);
}
else if (server is Com.Da.Server)
{
SupportedSpecifications.Add(OpcSpecification.OPC_DA_30);
SupportedSpecifications.Add(OpcSpecification.OPC_DA_20);
}
else if (server is Com.Ae.Server)
{
SupportedSpecifications.Add(OpcSpecification.OPC_AE_10);
}
else if (server is Com.Hda.Server)
{
SupportedSpecifications.Add(OpcSpecification.OPC_HDA_10);
}
return server;
}
/// <summary>
/// Connects to the specified COM server.
/// </summary>
public static object Connect(OpcUrl url, OpcConnectData connectData)
{
// parse path to find prog id and clsid.
var progID = url.Path;
string clsid = null;
var index = url.Path.IndexOf('/');
if (index >= 0)
{
progID = url.Path.Substring(0, index);
clsid = url.Path.Substring(index + 1);
}
// look up prog id if clsid not specified in the url.
Guid guid;
if (clsid == null)
{
// use OpcEnum to lookup the prog id.
guid = new ServerEnumerator().CLSIDFromProgID(progID, url.HostName, connectData);
// check if prog id is actually a clsid string.
if (guid == Guid.Empty)
{
try
{
guid = new Guid(progID);
}
catch
{
throw new OpcResultException(new OpcResult((int)OpcResult.CO_E_CLASSSTRING.Code, OpcResult.FuncCallType.SysFuncCall, null), string.Format("Could not connect to server {0}", progID));
}
}
}
// convert clsid string to a guid.
else
{
try
{
guid = new Guid(clsid);
}
catch
{
throw new OpcResultException(new OpcResult((int)OpcResult.CO_E_CLASSSTRING.Code, OpcResult.FuncCallType.SysFuncCall, null), string.Format("Could not connect to server {0}", progID));
}
}
// get the credentials.
var credentials = (connectData != null) ? connectData.UserIdentity : null;
// instantiate the server using CoCreateInstanceEx.
if (connectData == null || connectData.LicenseKey == null)
{
try
{
return Utilities.Interop.CreateInstance(guid, url.HostName, credentials);
}
catch (Exception e)
{
throw new OpcResultException(OpcResult.CO_E_CLASSSTRING, e.Message, e);
}
}
// instantiate the server using IClassFactory2.
else
{
try
{
return null;
//return Technosoftware.DaAeHdaClient.Utilities.Interop.CreateInstanceWithLicenseKey(guid, url.HostName, credentials, connectData.LicenseKey);
}
catch (Exception e)
{
throw new OpcResultException(OpcResult.CO_E_CLASSSTRING, e.Message, e);
}
}
}
}
}

View File

@@ -0,0 +1,441 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using Technosoftware.DaAeHdaClient.Hda;
using Technosoftware.OpcRcw.Hda;
using Technosoftware.OpcRcw.Comn;
#endregion
namespace Technosoftware.DaAeHdaClient.Com.Hda
{
/// <summary>
/// An in-process wrapper an OPC HDA browser object.
/// </summary>
internal class Browser : ITsCHdaBrowser
{
//======================================================================
// Construction
/// <summary>
/// Initializes the object with the specifed COM server.
/// </summary>
internal Browser(Server server, IOPCHDA_Browser browser, TsCHdaBrowseFilter[] filters, OpcResult[] results)
{
if (browser == null) throw new ArgumentNullException(nameof(browser));
// save the server object that created the browser.
m_server = server;
// save the COM server (released in Dispose()).
m_browser = browser;
// save only the filters that were accepted.
if (filters != null)
{
var validFilters = new ArrayList();
for (var ii = 0; ii < filters.Length; ii++)
{
if (results[ii].Succeeded())
{
validFilters.Add(filters[ii]);
}
}
m_filters = new TsCHdaBrowseFilterCollection(validFilters);
}
}
#region IDisposable Members
/// <summary>
/// This must be called explicitly by clients to ensure the COM server is released.
/// </summary>
public virtual void Dispose()
{
lock (this)
{
m_server = null;
Utilities.Interop.ReleaseServer(m_browser);
m_browser = null;
}
}
#endregion
//======================================================================
// Filters
/// <summary>
/// Returns the set of attribute filters used by the browser.
/// </summary>
public TsCHdaBrowseFilterCollection Filters
{
get
{
lock (this)
{
return (TsCHdaBrowseFilterCollection)m_filters.Clone();
}
}
}
//======================================================================
// Browse
/// <summary>
/// Browses the server's address space at the specified branch.
/// </summary>
/// <param name="itemID">The item id of the branch to search.</param>
/// <returns>The set of elements that meet the filter criteria.</returns>
public TsCHdaBrowseElement[] Browse(OpcItem itemID)
{
IOpcBrowsePosition position;
var elements = Browse(itemID, 0, out position);
if (position != null)
{
position.Dispose();
}
return elements;
}
/// <summary>
/// Begins a browsing the server's address space at the specified branch.
/// </summary>
/// <param name="itemID">The item id of the branch to search.</param>
/// <param name="maxElements">The maximum number of elements to return.</param>
/// <param name="position">The position object used to continue a browse operation.</param>
/// <returns>The set of elements that meet the filter criteria.</returns>
public TsCHdaBrowseElement[] Browse(OpcItem itemID, int maxElements, out IOpcBrowsePosition position)
{
position = null;
// interpret invalid values as 'no limit'.
if (maxElements <= 0)
{
maxElements = int.MaxValue;
}
lock (this)
{
var branchPath = (itemID != null && itemID.ItemName != null)?itemID.ItemName:"";
// move to the correct position in the server's address space.
try
{
m_browser.ChangeBrowsePosition(OPCHDA_BROWSEDIRECTION.OPCHDA_BROWSE_DIRECT, branchPath);
}
catch (Exception e)
{
throw Utilities.Interop.CreateException("IOPCHDA_Browser.ChangeBrowsePosition", e);
}
// browse for branches
var enumerator = GetEnumerator(true);
var elements = FetchElements(enumerator, maxElements, true);
// check if max element count reached.
if (elements.Count >= maxElements)
{
position = new BrowsePosition(branchPath, enumerator, false);
return (TsCHdaBrowseElement[])elements.ToArray(typeof(TsCHdaBrowseElement));
}
// release enumerator.
enumerator.Dispose();
// browse for items
enumerator = GetEnumerator(false);
var items = FetchElements(enumerator, maxElements-elements.Count, false);
if (items != null)
{
elements.AddRange(items);
}
// check if max element count reached.
if (elements.Count >= maxElements)
{
position = new BrowsePosition(branchPath, enumerator, true);
return (TsCHdaBrowseElement[])elements.ToArray(typeof(TsCHdaBrowseElement));
}
// release enumerator.
enumerator.Dispose();
return (TsCHdaBrowseElement[])elements.ToArray(typeof(TsCHdaBrowseElement));
}
}
//======================================================================
// BrowseNext
/// <summary>
/// Continues browsing the server's address space at the specified position.
/// </summary>
/// <param name="maxElements">The maximum number of elements to return.</param>
/// <param name="position">The position object used to continue a browse operation.</param>
/// <returns>The set of elements that meet the filter criteria.</returns>
public TsCHdaBrowseElement[] BrowseNext(int maxElements, ref IOpcBrowsePosition position)
{
// check arguments.
if (position == null || position.GetType() != typeof(BrowsePosition))
{
throw new ArgumentException("Not a valid browse position object.", nameof(position));
}
// interpret invalid values as 'no limit'.
if (maxElements <= 0)
{
maxElements = int.MaxValue;
}
lock (this)
{
var pos = (BrowsePosition)position;
var elements = new ArrayList();
if (!pos.FetchingItems)
{
elements = FetchElements(pos.Enumerator, maxElements, true);
// check if max element count reached.
if (elements.Count >= maxElements)
{
return (TsCHdaBrowseElement[])elements.ToArray(typeof(TsCHdaBrowseElement));
}
// release enumerator.
pos.Enumerator.Dispose();
pos.Enumerator = null;
pos.FetchingItems = true;
// move to the correct position in the server's address space.
try
{
m_browser.ChangeBrowsePosition(OPCHDA_BROWSEDIRECTION.OPCHDA_BROWSE_DIRECT, pos.BranchPath);
}
catch (Exception e)
{
throw Utilities.Interop.CreateException("IOPCHDA_Browser.ChangeBrowsePosition", e);
}
// create enumerator for items.
pos.Enumerator = GetEnumerator(false);
}
// fetch next set of items.
var items = FetchElements(pos.Enumerator, maxElements-elements.Count, false);
if (items != null)
{
elements.AddRange(items);
}
// check if max element count reached.
if (elements.Count >= maxElements)
{
return (TsCHdaBrowseElement[])elements.ToArray(typeof(TsCHdaBrowseElement));
}
// release position object.
position.Dispose();
position = null;
// return elements.
return (TsCHdaBrowseElement[])elements.ToArray(typeof(TsCHdaBrowseElement));
}
}
#region Private Methods
/// <summary>
/// Creates an enumerator for the elements contained with the current branch.
/// </summary>
private EnumString GetEnumerator(bool isBranch)
{
try
{
var browseType = (isBranch)?OPCHDA_BROWSETYPE.OPCHDA_BRANCH:OPCHDA_BROWSETYPE.OPCHDA_LEAF;
IEnumString pEnumerator = null;
m_browser.GetEnum(browseType, out pEnumerator);
return new EnumString(pEnumerator);
}
catch (Exception e)
{
throw Utilities.Interop.CreateException("IOPCHDA_Browser.GetEnum", e);
}
}
/// <summary>
/// Fetches the element names and item ids for each element.
/// </summary>
private ArrayList FetchElements(EnumString enumerator, int maxElements, bool isBranch)
{
var elements = new ArrayList();
while (elements.Count < maxElements)
{
// fetch next batch of element names.
var count = BLOCK_SIZE;
if (elements.Count + count > maxElements)
{
count = maxElements - elements.Count;
}
var names = enumerator.Next(count);
// check if no more elements found.
if (names == null || names.Length == 0)
{
break;
}
// create new element objects.
foreach (var name in names)
{
var element = new TsCHdaBrowseElement();
element.Name = name;
// lookup item id for element.
try
{
string itemID = null;
m_browser.GetItemID(name, out itemID);
element.ItemName = itemID;
element.ItemPath = null;
element.HasChildren = isBranch;
}
catch
{
// ignore errors.
}
elements.Add(element);
}
}
// validate items - this is necessary to set the IsItem flag correctly.
var results = m_server.ValidateItems((OpcItem[])elements.ToArray(typeof(OpcItem)));
if (results != null)
{
for (var ii = 0; ii < results.Length; ii++)
{
if (results[ii].Result.Succeeded())
{
((TsCHdaBrowseElement)elements[ii]).IsItem = true;
}
}
}
// return results.
return elements;
}
#endregion
#region Private Members
private Server m_server = null;
private IOPCHDA_Browser m_browser = null;
private TsCHdaBrowseFilterCollection m_filters = new TsCHdaBrowseFilterCollection();
private const int BLOCK_SIZE = 10;
#endregion
}
/// <summary>
/// Stores the state of a browse operation that was halted.
/// </summary>
internal class BrowsePosition : TsCHdaBrowsePosition
{
/// <summary>
/// Initializes a the object with the browse operation state information.
/// </summary>
/// <param name="branchPath">The item id of branch used in the browse operation.</param>
/// <param name="enumerator">The enumerator used for the browse operation.</param>
/// <param name="fetchingItems">Whether the enumerator is return branches or items.</param>
internal BrowsePosition(string branchPath, EnumString enumerator, bool fetchingItems)
{
m_branchPath = branchPath;
m_enumerator = enumerator;
m_fetchingItems = fetchingItems;
}
/// <summary>
/// The item id of the branch being browsed.
/// </summary>
internal string BranchPath
{
get => m_branchPath;
set => m_branchPath = value;
}
/// <summary>
/// The enumerator that was in use when the browse halted.
/// </summary>
internal EnumString Enumerator
{
get => m_enumerator;
set => m_enumerator = value;
}
/// <summary>
/// Whether the browse halted while fetching items.
/// </summary>
internal bool FetchingItems
{
get => m_fetchingItems;
set => m_fetchingItems = value;
}
#region IDisposable Members
/// <summary>
/// Releases any unmanaged resources held by the object.
/// </summary>
public override void Dispose()
{
if (m_enumerator != null)
{
m_enumerator.Dispose();
m_enumerator = null;
}
base.Dispose();
}
#endregion
#region Private Members
private string m_branchPath = null;
private EnumString m_enumerator = null;
private bool m_fetchingItems = false;
#endregion
}
}

View File

@@ -0,0 +1,591 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using Technosoftware.DaAeHdaClient.Hda;
using Technosoftware.OpcRcw.Hda;
#endregion
namespace Technosoftware.DaAeHdaClient.Com.Hda
{
/// <summary>
/// A class that implements the HDA data callback interface.
/// </summary>
internal class DataCallback : IOPCHDA_DataCallback
{
/// <summary>
/// Initializes the object with the containing subscription object.
/// </summary>
public DataCallback() {}
/// <summary>
/// Fired when an exception occurs during callback processing.
/// </summary>
public event TsCHdaCallbackExceptionEventHandler CallbackExceptionEvent
{
add {lock (this) { _callbackExceptionEvent += value; }}
remove {lock (this) { _callbackExceptionEvent -= value; }}
}
/// <summary>
/// Creates a new request object.
/// </summary>
public Request CreateRequest(object requestHandle, Delegate callback)
{
lock (this)
{
// create a new request.
var request = new Request(requestHandle, callback, ++m_nextID);
// no items yet - callback may return before async call returns.
m_requests[request.RequestID] = request;
// return requests.
return request;
}
}
/// <summary>
/// Cancels an existing request.
/// </summary>
public bool CancelRequest(Request request, TsCHdaCancelCompleteEventHandler callback)
{
lock (this)
{
// check if it is a valid request.
if (!m_requests.Contains(request.RequestID))
{
return false;
}
// request will be removed when the cancel complete callback arrives.
if (callback != null)
{
request.CancelCompleteEvent += callback;
}
// no confirmation required - remove request immediately.
else
{
m_requests.Remove(request.RequestID);
}
// request will be cancelled.
return true;
}
}
#region IOPCHDA_DataCallback Members
/// <summary>
/// Called when new data arrives for a subscription.
/// </summary>
public void OnDataChange(
int dwTransactionID,
int hrStatus,
int dwNumItems,
OPCHDA_ITEM[] pItemValues,
int[] phrErrors)
{
try
{
lock (this)
{
// lookup request transaction.
var request = (Request)m_requests[dwTransactionID];
if (request == null)
{
return;
}
// unmarshal results.
var results = new TsCHdaItemValueCollection[pItemValues.Length];
for (var ii = 0; ii < pItemValues.Length; ii++)
{
results[ii] = Interop.GetItemValueCollection(pItemValues[ii], false);
results[ii].ServerHandle = results[ii].ClientHandle;
results[ii].ClientHandle = null;
results[ii].Result = Utilities.Interop.GetResultId(phrErrors[ii]);
}
// invoke callback - remove request if unexpected error occured.
if (request.InvokeCallback(results))
{
m_requests.Remove(request.RequestID);
}
}
}
catch (Exception exception)
{
HandleException(dwTransactionID, exception);
}
}
/// <summary>
/// Called when an asynchronous read request completes.
/// </summary>
public void OnReadComplete(
int dwTransactionID,
int hrStatus,
int dwNumItems,
OPCHDA_ITEM[] pItemValues,
int[] phrErrors)
{
try
{
lock (this)
{
// lookup request transaction.
var request = (Request)m_requests[dwTransactionID];
if (request == null)
{
return;
}
// unmarshal results.
var results = new TsCHdaItemValueCollection[pItemValues.Length];
for (var ii = 0; ii < pItemValues.Length; ii++)
{
results[ii] = Interop.GetItemValueCollection(pItemValues[ii], false);
results[ii].ServerHandle = pItemValues[ii].hClient;
results[ii].Result = Utilities.Interop.GetResultId(phrErrors[ii]);
}
// invoke callback - remove request if all results arrived.
if (request.InvokeCallback(results))
{
m_requests.Remove(request.RequestID);
}
}
}
catch (Exception exception)
{
HandleException(dwTransactionID, exception);
}
}
/// <summary>
/// Called when an asynchronous read modified request completes.
/// </summary>
public void OnReadModifiedComplete(
int dwTransactionID,
int hrStatus,
int dwNumItems,
OPCHDA_MODIFIEDITEM[] pItemValues,
int[] phrErrors)
{
try
{
lock (this)
{
// lookup request transaction.
var request = (Request)m_requests[dwTransactionID];
if (request == null)
{
return;
}
// unmarshal results.
var results = new TsCHdaModifiedValueCollection[pItemValues.Length];
for (var ii = 0; ii < pItemValues.Length; ii++)
{
results[ii] = Interop.GetModifiedValueCollection(pItemValues[ii], false);
results[ii].ServerHandle = pItemValues[ii].hClient;
results[ii].Result = Utilities.Interop.GetResultId(phrErrors[ii]);
}
// invoke callback - remove request if all results arrived.
if (request.InvokeCallback(results))
{
m_requests.Remove(request.RequestID);
}
}
}
catch (Exception exception)
{
HandleException(dwTransactionID, exception);
}
}
/// <summary>
/// Called when an asynchronous read attributes request completes.
/// </summary>
public void OnReadAttributeComplete(
int dwTransactionID,
int hrStatus,
int hClient,
int dwNumItems,
OPCHDA_ATTRIBUTE[] pAttributeValues,
int[] phrErrors)
{
try
{
lock (this)
{
// lookup request transaction.
var request = (Request)m_requests[dwTransactionID];
if (request == null)
{
return;
}
// create item object to collect results.
var item = new TsCHdaItemAttributeCollection();
item.ServerHandle = hClient;
// unmarshal results.
var results = new TsCHdaAttributeValueCollection[pAttributeValues.Length];
for (var ii = 0; ii < pAttributeValues.Length; ii++)
{
results[ii] = Interop.GetAttributeValueCollection(pAttributeValues[ii], false);
results[ii].Result = Utilities.Interop.GetResultId(phrErrors[ii]);
item.Add(results[ii]);
}
// invoke callback - remove request if all results arrived.
if (request.InvokeCallback(item))
{
m_requests.Remove(request.RequestID);
}
}
}
catch (Exception exception)
{
HandleException(dwTransactionID, exception);
}
}
/// <summary>
/// Called when an asynchronous read annotations request completes.
/// </summary>
public void OnReadAnnotations(
int dwTransactionID,
int hrStatus,
int dwNumItems,
OPCHDA_ANNOTATION[] pAnnotationValues,
int[] phrErrors)
{
try
{
lock (this)
{
// lookup request transaction.
var request = (Request)m_requests[dwTransactionID];
if (request == null)
{
return;
}
// unmarshal results.
var results = new TsCHdaAnnotationValueCollection[pAnnotationValues.Length];
for (var ii = 0; ii < pAnnotationValues.Length; ii++)
{
results[ii] = Interop.GetAnnotationValueCollection(pAnnotationValues[ii], false);
results[ii].ServerHandle = pAnnotationValues[ii].hClient;
results[ii].Result = Utilities.Interop.GetResultId(phrErrors[ii]);
}
// invoke callback - remove request if all results arrived.
if (request.InvokeCallback(results))
{
m_requests.Remove(request.RequestID);
}
}
}
catch (Exception exception)
{
HandleException(dwTransactionID, exception);
}
}
/// <summary>
/// Called when an asynchronous insert annotations request completes.
/// </summary>
public void OnInsertAnnotations(
int dwTransactionID,
int hrStatus,
int dwCount,
int[] phClients,
int[] phrErrors)
{
try
{
lock (this)
{
// lookup request transaction.
var request = (Request)m_requests[dwTransactionID];
if (request == null)
{
return;
}
// unmarshal results.
var results = new ArrayList();
if (dwCount > 0)
{
// subscription results in collections for the same item id.
var currentHandle = phClients[0];
var itemResults = new TsCHdaResultCollection();
for (var ii = 0; ii < dwCount; ii++)
{
// create a new collection for the next item's results.
if (phClients[ii] != currentHandle)
{
itemResults.ServerHandle = currentHandle;
results.Add(itemResults);
currentHandle = phClients[ii];
itemResults = new TsCHdaResultCollection();
}
var result = new TsCHdaResult(Utilities.Interop.GetResultId(phrErrors[ii]));
itemResults.Add(result);
}
// add the last set of item results.
itemResults.ServerHandle = currentHandle;
results.Add(itemResults);
}
// invoke callback - remove request if all results arrived.
if (request.InvokeCallback((TsCHdaResultCollection[])results.ToArray(typeof(TsCHdaResultCollection))))
{
m_requests.Remove(request.RequestID);
}
}
}
catch (Exception exception)
{
HandleException(dwTransactionID, exception);
}
}
/// <summary>
/// Called when a batch of data from playback request arrives.
/// </summary>
public void OnPlayback(
int dwTransactionID,
int hrStatus,
int dwNumItems,
IntPtr ppItemValues,
int[] phrErrors)
{
try
{
lock (this)
{
// lookup request transaction.
var request = (Request)m_requests[dwTransactionID];
if (request == null)
{
return;
}
// unmarshal results.
var results = new TsCHdaItemValueCollection[dwNumItems];
// the data is transfered as a array of pointers to items instead of simply
// as an array of items. This is due to a mistake in the HDA IDL.
var pItems = Utilities.Interop.GetInt32s(ref ppItemValues, dwNumItems, false);
for (var ii = 0; ii < dwNumItems; ii++)
{
// get pointer to item.
var pItem = (IntPtr)pItems[ii];
// unmarshal item as an array of length 1.
var item = Interop.GetItemValueCollections(ref pItem, 1, false);
if (item != null && item.Length == 1)
{
results[ii] = item[0];
results[ii].ServerHandle = results[ii].ClientHandle;
results[ii].ClientHandle = null;
results[ii].Result = Utilities.Interop.GetResultId(phrErrors[ii]);
}
}
// invoke callback - remove request if unexpected error occured.
if (request.InvokeCallback(results))
{
m_requests.Remove(request.RequestID);
}
}
}
catch (Exception exception)
{
HandleException(dwTransactionID, exception);
}
}
/// <summary>
/// Called when an asynchronous update request completes.
/// </summary>
public void OnUpdateComplete(
int dwTransactionID,
int hrStatus,
int dwCount,
int[] phClients,
int[] phrErrors)
{
try
{
lock (this)
{
// lookup request transaction.
var request = (Request)m_requests[dwTransactionID];
if (request == null)
{
return;
}
// unmarshal results.
var results = new ArrayList();
if (dwCount > 0)
{
// subscription results in collections for the same item id.
var currentHandle = phClients[0];
var itemResults = new TsCHdaResultCollection();
for (var ii = 0; ii < dwCount; ii++)
{
// create a new collection for the next item's results.
if (phClients[ii] != currentHandle)
{
itemResults.ServerHandle = currentHandle;
results.Add(itemResults);
currentHandle = phClients[ii];
itemResults = new TsCHdaResultCollection();
}
var result = new TsCHdaResult(Utilities.Interop.GetResultId(phrErrors[ii]));
itemResults.Add(result);
}
// add the last set of item results.
itemResults.ServerHandle = currentHandle;
results.Add(itemResults);
}
// invoke callback - remove request if all results arrived.
if (request.InvokeCallback((TsCHdaResultCollection[])results.ToArray(typeof(TsCHdaResultCollection))))
{
m_requests.Remove(request.RequestID);
}
}
}
catch (Exception exception)
{
HandleException(dwTransactionID, exception);
}
}
/// <summary>
/// Called when an asynchronous request was cancelled successfully.
/// </summary>
public void OnCancelComplete(int dwCancelID)
{
try
{
lock (this)
{
// lookup request.
var request = (Request)m_requests[dwCancelID];
if (request == null)
{
return;
}
// send the cancel complete notification.
request.OnCancelComplete();
// remove the request.
m_requests.Remove(request.RequestID);
}
}
catch (Exception exception)
{
HandleException(dwCancelID, exception);
}
}
#endregion
#region Private Methods
/// <summary>
/// Fires an event indicating an exception occurred during callback processing.
/// </summary>
void HandleException(int requestID, Exception exception)
{
lock (this)
{
// lookup request.
var request = (Request)m_requests[requestID];
if (request != null)
{
// send notification.
if (_callbackExceptionEvent != null)
{
_callbackExceptionEvent(request, exception);
}
}
}
}
#endregion
#region Private Members
private int m_nextID;
private Hashtable m_requests = new Hashtable();
private TsCHdaCallbackExceptionEventHandler _callbackExceptionEvent;
#endregion
}
}

View File

@@ -0,0 +1,441 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Runtime.InteropServices;
using Technosoftware.DaAeHdaClient.Da;
using Technosoftware.DaAeHdaClient.Hda;
#endregion
#pragma warning disable 0618
namespace Technosoftware.DaAeHdaClient.Com.Hda
{
/// <summary>
/// Contains state information for a single asynchronous Technosoftware.DaAeHdaClient.Com.Hda.Interop.
/// </summary>
internal class Interop
{
/// <summary>
/// Converts a standard FILETIME to an OpcRcw.Da.FILETIME structure.
/// </summary>
internal static OpcRcw.Hda.OPCHDA_FILETIME Convert(FILETIME input)
{
var output = new OpcRcw.Hda.OPCHDA_FILETIME();
output.dwLowDateTime = input.dwLowDateTime;
output.dwHighDateTime = input.dwHighDateTime;
return output;
}
/// <summary>
/// Converts an OpcRcw.Da.FILETIME to a standard FILETIME structure.
/// </summary>
internal static FILETIME Convert(OpcRcw.Hda.OPCHDA_FILETIME input)
{
var output = new FILETIME();
output.dwLowDateTime = input.dwLowDateTime;
output.dwHighDateTime = input.dwHighDateTime;
return output;
}
/// <summary>
/// Converts a decimal value to a OpcRcw.Hda.OPCHDA_TIME structure.
/// </summary>
internal static OpcRcw.Hda.OPCHDA_FILETIME GetFILETIME(decimal input)
{
var output = new OpcRcw.Hda.OPCHDA_FILETIME();
output.dwHighDateTime = (int)((((ulong)(input*10000000)) & 0xFFFFFFFF00000000)>>32);
output.dwLowDateTime = (int)((((ulong)(input*10000000)) & 0x00000000FFFFFFFF));
return output;
}
/// <summary>
/// Returns an array of FILETIMEs.
/// </summary>
internal static OpcRcw.Hda.OPCHDA_FILETIME[] GetFILETIMEs(DateTime[] input)
{
OpcRcw.Hda.OPCHDA_FILETIME[] output = null;
if (input != null)
{
output = new OpcRcw.Hda.OPCHDA_FILETIME[input.Length];
for (var ii = 0; ii < input.Length; ii++)
{
output[ii] = Convert(Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(input[ii]));
}
}
return output;
}
/// <summary>
/// Converts a Technosoftware.DaAeHdaClient.Time object to a Technosoftware.DaAeHdaClient.Com.Hda.OPCHDA_TIME structure.
/// </summary>
internal static OpcRcw.Hda.OPCHDA_TIME GetTime(TsCHdaTime input)
{
var output = new OpcRcw.Hda.OPCHDA_TIME();
if (input != null)
{
output.ftTime = Convert(Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(input.AbsoluteTime));
output.szTime = (input.IsRelative)?input.ToString():"";
output.bString = (input.IsRelative)?1:0;
}
// create a null value for a time structure.
else
{
output.ftTime = Convert(Technosoftware.DaAeHdaClient.Com.Interop.GetFILETIME(DateTime.MinValue));
output.szTime = "";
output.bString = 1;
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an array of OPCHDA_ITEM structures.
/// </summary>
internal static TsCHdaItemValueCollection[] GetItemValueCollections(ref IntPtr pInput, int count, bool deallocate)
{
TsCHdaItemValueCollection[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new TsCHdaItemValueCollection[count];
var pos = pInput;
for (var ii = 0; ii < count; ii++)
{
output[ii] = GetItemValueCollection(pos, deallocate);
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Hda.OPCHDA_ITEM)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an OPCHDA_ITEM structure.
/// </summary>
internal static TsCHdaItemValueCollection GetItemValueCollection(IntPtr pInput, bool deallocate)
{
TsCHdaItemValueCollection output = null;
if (pInput != IntPtr.Zero)
{
var item = Marshal.PtrToStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ITEM));
output = GetItemValueCollection((OpcRcw.Hda.OPCHDA_ITEM)item, deallocate);
if (deallocate)
{
Marshal.DestroyStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ITEM));
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an OPCHDA_ITEM structure.
/// </summary>
internal static TsCHdaItemValueCollection GetItemValueCollection(OpcRcw.Hda.OPCHDA_ITEM input, bool deallocate)
{
var output = new TsCHdaItemValueCollection();
output.ClientHandle = input.hClient;
output.Aggregate = input.haAggregate;
var values = Com.Interop.GetVARIANTs(ref input.pvDataValues, input.dwCount, deallocate);
var timestamps = Utilities.Interop.GetDateTimes(ref input.pftTimeStamps, input.dwCount, deallocate);
var qualities = Utilities.Interop.GetInt32s(ref input.pdwQualities, input.dwCount, deallocate);
for (var ii = 0; ii < input.dwCount; ii++)
{
var value = new TsCHdaItemValue();
value.Value = values[ii];
value.Timestamp = timestamps[ii];
value.Quality = new TsCDaQuality((short)(qualities[ii] & 0x0000FFFF));
value.HistorianQuality = (TsCHdaQuality)((int)(qualities[ii] & 0xFFFF0000));
output.Add(value);
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an array of OPCHDA_MODIFIEDITEM structures.
/// </summary>
internal static TsCHdaModifiedValueCollection[] GetModifiedValueCollections(ref IntPtr pInput, int count, bool deallocate)
{
TsCHdaModifiedValueCollection[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new TsCHdaModifiedValueCollection[count];
var pos = pInput;
for (var ii = 0; ii < count; ii++)
{
output[ii] = GetModifiedValueCollection(pos, deallocate);
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Hda.OPCHDA_MODIFIEDITEM)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an OPCHDA_MODIFIEDITEM structure.
/// </summary>
internal static TsCHdaModifiedValueCollection GetModifiedValueCollection(IntPtr pInput, bool deallocate)
{
TsCHdaModifiedValueCollection output = null;
if (pInput != IntPtr.Zero)
{
var item = Marshal.PtrToStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_MODIFIEDITEM));
output = GetModifiedValueCollection((OpcRcw.Hda.OPCHDA_MODIFIEDITEM)item, deallocate);
if (deallocate)
{
Marshal.DestroyStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_MODIFIEDITEM));
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an OPCHDA_MODIFIEDITEM structure.
/// </summary>
internal static TsCHdaModifiedValueCollection GetModifiedValueCollection(OpcRcw.Hda.OPCHDA_MODIFIEDITEM input, bool deallocate)
{
var output = new TsCHdaModifiedValueCollection();
output.ClientHandle = input.hClient;
var values = Com.Interop.GetVARIANTs(ref input.pvDataValues, input.dwCount, deallocate);
var timestamps = Utilities.Interop.GetDateTimes(ref input.pftTimeStamps, input.dwCount, deallocate);
var qualities = Utilities.Interop.GetInt32s(ref input.pdwQualities, input.dwCount, deallocate);
var modificationTimes = Utilities.Interop.GetDateTimes(ref input.pftModificationTime, input.dwCount, deallocate);
var editTypes = Utilities.Interop.GetInt32s(ref input.pEditType, input.dwCount, deallocate);
var users = Utilities.Interop.GetUnicodeStrings(ref input.szUser, input.dwCount, deallocate);
for (var ii = 0; ii < input.dwCount; ii++)
{
var value = new TsCHdaModifiedValue();
value.Value = values[ii];
value.Timestamp = timestamps[ii];
value.Quality = new TsCDaQuality((short)(qualities[ii] & 0x0000FFFF));
value.HistorianQuality = (TsCHdaQuality)((int)(qualities[ii] & 0xFFFF0000));
value.ModificationTime = modificationTimes[ii];
value.EditType = (TsCHdaEditType)editTypes[ii];
value.User = users[ii];
output.Add(value);
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an array of OPCHDA_ATTRIBUTE structures.
/// </summary>
internal static TsCHdaAttributeValueCollection[] GetAttributeValueCollections(ref IntPtr pInput, int count, bool deallocate)
{
TsCHdaAttributeValueCollection[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new TsCHdaAttributeValueCollection[count];
var pos = pInput;
for (var ii = 0; ii < count; ii++)
{
output[ii] = GetAttributeValueCollection(pos, deallocate);
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Hda.OPCHDA_ATTRIBUTE)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an OPCHDA_ATTRIBUTE structure.
/// </summary>
internal static TsCHdaAttributeValueCollection GetAttributeValueCollection(IntPtr pInput, bool deallocate)
{
TsCHdaAttributeValueCollection output = null;
if (pInput != IntPtr.Zero)
{
var item = Marshal.PtrToStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ATTRIBUTE));
output = GetAttributeValueCollection((OpcRcw.Hda.OPCHDA_ATTRIBUTE)item, deallocate);
if (deallocate)
{
Marshal.DestroyStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ATTRIBUTE));
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an OPCHDA_ATTRIBUTE structure.
/// </summary>
internal static TsCHdaAttributeValueCollection GetAttributeValueCollection(OpcRcw.Hda.OPCHDA_ATTRIBUTE input, bool deallocate)
{
var output = new TsCHdaAttributeValueCollection();
output.AttributeID = input.dwAttributeID;
var values = Com.Interop.GetVARIANTs(ref input.vAttributeValues, input.dwNumValues, deallocate);
var timestamps = Utilities.Interop.GetDateTimes(ref input.ftTimeStamps, input.dwNumValues, deallocate);
for (var ii = 0; ii < input.dwNumValues; ii++)
{
var value = new TsCHdaAttributeValue();
value.Value = values[ii];
value.Timestamp = timestamps[ii];
output.Add(value);
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an array of OPCHDA_ANNOTATION structures.
/// </summary>
internal static TsCHdaAnnotationValueCollection[] GetAnnotationValueCollections(ref IntPtr pInput, int count, bool deallocate)
{
TsCHdaAnnotationValueCollection[] output = null;
if (pInput != IntPtr.Zero && count > 0)
{
output = new TsCHdaAnnotationValueCollection[count];
var pos = pInput;
for (var ii = 0; ii < count; ii++)
{
output[ii] = GetAnnotationValueCollection(pos, deallocate);
pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Hda.OPCHDA_ANNOTATION)));
}
if (deallocate)
{
Marshal.FreeCoTaskMem(pInput);
pInput = IntPtr.Zero;
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an OPCHDA_ANNOTATION structure.
/// </summary>
internal static TsCHdaAnnotationValueCollection GetAnnotationValueCollection(IntPtr pInput, bool deallocate)
{
TsCHdaAnnotationValueCollection output = null;
if (pInput != IntPtr.Zero)
{
var item = Marshal.PtrToStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ANNOTATION));
output = GetAnnotationValueCollection((OpcRcw.Hda.OPCHDA_ANNOTATION)item, deallocate);
if (deallocate)
{
Marshal.DestroyStructure(pInput, typeof(OpcRcw.Hda.OPCHDA_ANNOTATION));
}
}
return output;
}
/// <summary>
/// Unmarshals and deallocates an OPCHDA_ANNOTATION structure.
/// </summary>
internal static TsCHdaAnnotationValueCollection GetAnnotationValueCollection(OpcRcw.Hda.OPCHDA_ANNOTATION input, bool deallocate)
{
var output = new TsCHdaAnnotationValueCollection();
output.ClientHandle = input.hClient;
var timestamps = Utilities.Interop.GetDateTimes(ref input.ftTimeStamps, input.dwNumValues, deallocate);
var annotations = Utilities.Interop.GetUnicodeStrings(ref input.szAnnotation, input.dwNumValues, deallocate);
var creationTimes = Utilities.Interop.GetDateTimes(ref input.ftAnnotationTime, input.dwNumValues, deallocate);
var users = Utilities.Interop.GetUnicodeStrings(ref input.szUser, input.dwNumValues, deallocate);
for (var ii = 0; ii < input.dwNumValues; ii++)
{
var value = new TsCHdaAnnotationValue();
value.Timestamp = timestamps[ii];
value.Annotation = annotations[ii];
value.CreationTime = creationTimes[ii];
value.User = users[ii];
output.Add(value);
}
return output;
}
}
}

View File

@@ -0,0 +1,404 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using Technosoftware.DaAeHdaClient.Hda;
#endregion
namespace Technosoftware.DaAeHdaClient.Com.Hda
{
/// <summary>
/// An object that mainatains the state of asynchronous requests.
/// </summary>
internal class Request : IOpcRequest, ITsCHdaActualTime
{
/// <summary>
/// The unique id assigned to the request when it was created.
/// </summary>
public int RequestID => m_requestID;
/// <summary>
/// The unqiue id assigned by the server when it was created.
/// </summary>
public int CancelID => m_cancelID;
/// <summary>
/// Fired when the server acknowledges that a request was cancelled.
/// </summary>
public event TsCHdaCancelCompleteEventHandler CancelCompleteEvent
{
add { lock (this) { m_cancelCompleteEvent += value; } }
remove { lock (this) { m_cancelCompleteEvent -= value; } }
}
/// <summary>
/// Initializes the object with all required information.
/// </summary>
public Request(object requestHandle, Delegate callback, int requestID)
{
m_requestHandle = requestHandle;
m_callback = callback;
m_requestID = requestID;
}
/// <summary>
/// Updates the request with the initial results.
/// </summary>
public bool Update(int cancelID, OpcItem[] results)
{
lock (this)
{
// save the server assigned id.
m_cancelID = cancelID;
// create a table of items indexed by the handle returned by the server in a callback.
m_items = new Hashtable();
foreach (var result in results)
{
if (!typeof(IOpcResult).IsInstanceOfType(result) || ((IOpcResult)result).Result.Succeeded())
{
m_items[result.ServerHandle] = new OpcItem(result);
}
}
// nothing more to do - no good items.
if (m_items.Count == 0)
{
return true;
}
// invoke callbacks for results that have already arrived.
var complete = false;
if (m_results != null)
{
foreach (var result in m_results)
{
complete = InvokeCallback(result);
}
}
// all done.
return complete;
}
}
/// <summary>
/// Invokes the callback for the request.
/// </summary>
public bool InvokeCallback(object results)
{
lock (this)
{
// save the results if the initial call to the server has not completed yet.
if (m_items == null)
{
// create cache for results.
if (m_results == null)
{
m_results = new ArrayList();
}
m_results.Add(results);
// request not initialized completely
return false;
}
// invoke on data update callback.
if (typeof(TsCHdaDataUpdateEventHandler).IsInstanceOfType(m_callback))
{
return InvokeCallback((TsCHdaDataUpdateEventHandler)m_callback, results);
}
// invoke read completed callback.
if (typeof(TsCHdaReadValuesCompleteEventHandler).IsInstanceOfType(m_callback))
{
return InvokeCallback((TsCHdaReadValuesCompleteEventHandler)m_callback, results);
}
// invoke read attributes completed callback.
if (typeof(TsCHdaReadAttributesCompleteEventHandler).IsInstanceOfType(m_callback))
{
return InvokeCallback((TsCHdaReadAttributesCompleteEventHandler)m_callback, results);
}
// invoke read annotations completed callback.
if (typeof(TsCHdaReadAnnotationsCompleteEventHandler).IsInstanceOfType(m_callback))
{
return InvokeCallback((TsCHdaReadAnnotationsCompleteEventHandler)m_callback, results);
}
// invoke update completed callback.
if (typeof(TsCHdaUpdateCompleteEventHandler).IsInstanceOfType(m_callback))
{
return InvokeCallback((TsCHdaUpdateCompleteEventHandler)m_callback, results);
}
// callback not supported.
return true;
}
}
/// <summary>
/// Called when the server acknowledges that a request was cancelled.
/// </summary>
public void OnCancelComplete()
{
lock (this)
{
if (m_cancelCompleteEvent != null)
{
m_cancelCompleteEvent(this);
}
}
}
#region IOpcRequest Members
/// <summary>
/// An unique identifier, assigned by the client, for the request.
/// </summary>
public object Handle => m_requestHandle;
#endregion
#region IActualTime Members
/// <summary>
/// The actual start time used by a server while processing a request.
/// </summary>
public DateTime StartTime
{
get => m_startTime;
set => m_startTime = value;
}
/// <summary>
/// The actual end time used by a server while processing a request.
/// </summary>
public DateTime EndTime
{
get => m_endTime;
set => m_endTime = value;
}
#endregion
#region Private Methods
/// <summary>
/// Invokes callback for a data change update.
/// </summary>
private bool InvokeCallback(TsCHdaDataUpdateEventHandler callback, object results)
{
// check for valid result type.
if (!typeof(TsCHdaItemValueCollection[]).IsInstanceOfType(results))
{
return false;
}
var values = (TsCHdaItemValueCollection[])results;
// update item handles and actual times.
UpdateResults(values);
try
{
callback(this, values);
}
catch
{
// ignore exceptions in the callbacks.
}
// request never completes.
return false;
}
/// <summary>
/// Invokes callback for a read request.
/// </summary>
private bool InvokeCallback(TsCHdaReadValuesCompleteEventHandler callback, object results)
{
// check for valid result type.
if (!typeof(TsCHdaItemValueCollection[]).IsInstanceOfType(results))
{
return false;
}
var values = (TsCHdaItemValueCollection[])results;
// update item handles and actual times.
UpdateResults(values);
try
{
callback(this, values);
}
catch
{
// ignore exceptions in the callbacks.
}
// check if all data has been sent.
foreach (var value in values)
{
if (value.Result == OpcResult.Hda.S_MOREDATA)
{
return false;
}
}
// request is complete.
return true;
}
/// <summary>
/// Invokes callback for a read attributes request.
/// </summary>
private bool InvokeCallback(TsCHdaReadAttributesCompleteEventHandler callback, object results)
{
// check for valid result type.
if (!typeof(TsCHdaItemAttributeCollection).IsInstanceOfType(results))
{
return false;
}
var values = (TsCHdaItemAttributeCollection)results;
// update item handles and actual times.
UpdateResults(new TsCHdaItemAttributeCollection[] { values });
try
{
callback(this, values);
}
catch
{
// ignore exceptions in the callbacks.
}
// request always completes
return true;
}
/// <summary>
/// Invokes callback for a read annotations request.
/// </summary>
private bool InvokeCallback(TsCHdaReadAnnotationsCompleteEventHandler callback, object results)
{
// check for valid result type.
if (!typeof(TsCHdaAnnotationValueCollection[]).IsInstanceOfType(results))
{
return false;
}
var values = (TsCHdaAnnotationValueCollection[])results;
// update item handles and actual times.
UpdateResults(values);
try
{
callback(this, values);
}
catch
{
// ignore exceptions in the callbacks.
}
// request always completes
return true;
}
/// <summary>
/// Invokes callback for a read annotations request.
/// </summary>
private bool InvokeCallback(TsCHdaUpdateCompleteEventHandler callback, object results)
{
// check for valid result type.
if (!typeof(TsCHdaResultCollection[]).IsInstanceOfType(results))
{
return false;
}
var values = (TsCHdaResultCollection[])results;
// update item handles and actual times.
UpdateResults(values);
try
{
callback(this, values);
}
catch
{
// ignore exceptions in the callbacks.
}
// request always completes
return true;
}
/// <summary>
/// Updates the result objects with locally cached information.
/// </summary>
private void UpdateResults(OpcItem[] results)
{
foreach (var result in results)
{
// update actual times.
if (typeof(ITsCHdaActualTime).IsInstanceOfType(result))
{
((ITsCHdaActualTime)result).StartTime = StartTime;
((ITsCHdaActualTime)result).EndTime = EndTime;
}
// add item identifier to value collection.
var itemID = (OpcItem)m_items[result.ServerHandle];
if (itemID != null)
{
result.ItemName = itemID.ItemName;
result.ItemPath = itemID.ItemPath;
result.ServerHandle = itemID.ServerHandle;
result.ClientHandle = itemID.ClientHandle;
}
}
}
#endregion
#region Private Members
private object m_requestHandle = null;
private Delegate m_callback = null;
private int m_requestID = 0;
private int m_cancelID = 0;
private DateTime m_startTime = DateTime.MinValue;
private DateTime m_endTime = DateTime.MinValue;
private Hashtable m_items = null;
private ArrayList m_results = null;
private event TsCHdaCancelCompleteEventHandler m_cancelCompleteEvent = null;
#endregion
}
}

View File

@@ -0,0 +1,68 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
namespace Hda
{
/// <summary>
/// Defines all well known COM HDA HRESULT codes.
/// </summary>
internal struct Result
{
/// <remarks/>
public const int E_MAXEXCEEDED = -0X3FFBEFFF; // 0xC0041001
/// <remarks/>
public const int S_NODATA = +0x40041002; // 0x40041002
/// <remarks/>
public const int S_MOREDATA = +0x40041003; // 0x40041003
/// <remarks/>
public const int E_INVALIDAGGREGATE = -0X3FFBEFFC; // 0xC0041004
/// <remarks/>
public const int S_CURRENTVALUE = +0x40041005; // 0x40041005
/// <remarks/>
public const int S_EXTRADATA = +0x40041006; // 0x40041006
/// <remarks/>
public const int W_NOFILTER = -0x7FFBEFF9; // 0x80041007
/// <remarks/>
public const int E_UNKNOWNATTRID = -0x3FFBEFF8; // 0xC0041008
/// <remarks/>
public const int E_NOT_AVAIL = -0x3FFBEFF7; // 0xC0041009
/// <remarks/>
public const int E_INVALIDDATATYPE = -0x3FFBEFF6; // 0xC004100A
/// <remarks/>
public const int E_DATAEXISTS = -0x3FFBEFF5; // 0xC004100B
/// <remarks/>
public const int E_INVALIDATTRID = -0x3FFBEFF4; // 0xC004100C
/// <remarks/>
public const int E_NODATAEXISTS = -0x3FFBEFF3; // 0xC004100D
/// <remarks/>
public const int S_INSERTED = +0x4004100E; // 0x4004100E
/// <remarks/>
public const int S_REPLACED = +0x4004100F; // 0x4004100F
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,204 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections.Generic;
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
/// <summary>Provides methods for discover (search) of OPC Servers.</summary>
public class OpcDiscovery
{
#region Fields
private static ServerEnumerator discovery_;
private static string hostName_;
private bool disposed_;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// The finalizer implementation.
/// </summary>
~OpcDiscovery()
{
Dispose(false);
}
/// <summary>
/// Implements <see cref="IDisposable.Dispose"/>.
/// </summary>
public virtual void Dispose()
{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing">If true managed and unmanaged resources can be disposed. If false only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!disposed_)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
discovery_?.Dispose();
}
// Release unmanaged resources. If disposing is false,
// only the following code is executed.
}
disposed_ = true;
}
#endregion
#region Public Methods (Host related)
/// <summary>
/// Returns a list of host names which could contain OPC servers.
/// </summary>
/// <returns>List of available network host names.</returns>
public static List<string> GetHostNames()
{
return ComUtils.EnumComputers();
}
#endregion
#region Public Methods (Returns a list of OpcServer)
/// <summary>
/// Returns a list of servers that support the specified specification.
/// </summary>
/// <param name="specification">Unique identifier for one OPC specification.</param>
/// <returns>Returns a list of found OPC servers.</returns>
public static List<OpcServer> GetServers(OpcSpecification specification)
{
var identity = new OpcUserIdentity("", "");
return GetServers(specification, null, identity);
}
/// <summary>
/// Returns a list of servers that support the specified specification.
/// </summary>
/// <param name="specification">Unique identifier for one OPC specification.</param>
/// <param name="discoveryServerUrl">The URL of the discovery server to be used.</param>
/// <returns>Returns a list of found OPC servers.</returns>
public static List<OpcServer> GetServers(OpcSpecification specification, string discoveryServerUrl)
{
var identity = new OpcUserIdentity("", "");
return GetServers(specification, discoveryServerUrl, identity);
}
/// <summary>
/// Returns a list of servers that support the specified specification.
/// </summary>
/// <param name="specification">Unique identifier for one OPC specification.</param>
/// <param name="discoveryServerUrl">The URL of the discovery server to be used.</param>
/// <param name="identity">The user identity to use when discovering the servers.</param>
/// <returns>Returns a list of found OPC servers.</returns>
public static List<OpcServer> GetServers(OpcSpecification specification, string discoveryServerUrl, OpcUserIdentity identity)
{
var serverList = new List<OpcServer>();
var discovery = specification == OpcSpecification.OPC_AE_10 || (specification == OpcSpecification.OPC_DA_20 ||
specification == OpcSpecification.OPC_DA_30) || specification == OpcSpecification.OPC_HDA_10;
if (discovery)
{
if (discovery_ == null || hostName_ != discoveryServerUrl)
{
discovery_?.Dispose();
hostName_ = discoveryServerUrl;
discovery_ = new ServerEnumerator();
}
var servers = discovery_.GetAvailableServers(specification);
if (servers != null)
{
foreach (var server in servers)
{
serverList.Add(server);
}
}
}
return serverList;
}
#endregion
#region Public Methods (Returns OpcServer object for a specific URL)
/// <summary>
/// Creates a server object for the specified URL.
/// </summary>
/// <param name="url">The OpcUrl of the OPC server.</param>
/// <returns>The OpcServer object.</returns>
public static OpcServer GetServer(OpcUrl url)
{
if (url == null) throw new ArgumentNullException(nameof(url));
OpcServer server = null;
// create an unconnected server object for COM based servers.
// DA
if (string.CompareOrdinal(url.Scheme, OpcUrlScheme.DA) == 0)
{
server = new Technosoftware.DaAeHdaClient.Da.TsCDaServer(new Factory(), url);
}
// AE
else if (string.CompareOrdinal(url.Scheme, OpcUrlScheme.AE) == 0)
{
server = new Technosoftware.DaAeHdaClient.Ae.TsCAeServer(new Factory(), url);
}
// HDA
else if (string.CompareOrdinal(url.Scheme, OpcUrlScheme.HDA) == 0)
{
server = new Technosoftware.DaAeHdaClient.Hda.TsCHdaServer(new Factory(), url);
}
// Other specifications not supported yet.
if (server == null)
{
throw new NotSupportedException(url.Scheme);
}
return server;
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,599 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using Technosoftware.DaAeHdaClient.Com.Utilities;
using Technosoftware.DaAeHdaClient.Utilities;
using Technosoftware.OpcRcw.Comn;
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
/// <summary>
/// An in-process wrapper for a remote OPC COM server (not thread safe).
/// </summary>
internal class Server : IOpcServer
{
#region Fields
/// <summary>
/// The COM server wrapped by the object.
/// </summary>
protected object server_;
/// <summary>
/// The URL containing host, prog id and clsid information for The remote server.
/// </summary>
protected OpcUrl url_;
/// <summary>
/// A connect point with the COM server.
/// </summary>
private ConnectionPoint connection_;
/// <summary>
/// The internal object that implements the IOPCShutdown interface.
/// </summary>
private Callback callback_;
/// <summary>
/// The synchronization object for server access
/// </summary>
private static volatile object lock_ = new object();
private int outstandingCalls_;
#endregion
#region Constructors
/// <summary>
/// Initializes the object.
/// </summary>
internal Server()
{
url_ = null;
server_ = null;
callback_ = new Callback(this);
}
/// <summary>
/// Initializes the object with the specifed COM server.
/// </summary>
internal Server(OpcUrl url, object server)
{
if (url == null) throw new ArgumentNullException(nameof(url));
url_ = (OpcUrl)url.Clone();
server_ = server;
callback_ = new Callback(this);
}
#endregion
#region IDisposable Members
/// <summary>
/// The finalizer.
/// </summary>
~Server()
{
Dispose(false);
}
/// <summary>
/// Releases unmanaged resources held by the object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing">If true managed and unmanaged resources can be disposed. If false only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!disposed_)
{
lock (this)
{
if (disposing)
{
// Free other state (managed objects).
// close callback connections.
if (connection_ != null)
{
connection_.Dispose();
connection_ = null;
}
}
DisableDCOMCallCancellation();
// Free your own state (unmanaged objects).
// Set large fields to null.
// release server.
Interop.ReleaseServer(server_);
server_ = null;
}
disposed_ = true;
}
}
private bool disposed_;
#endregion
#region Public Methods
/// <summary>
/// Connects to the server with the specified URL and credentials.
/// </summary>
public virtual void Initialize(OpcUrl url, OpcConnectData connectData)
{
if (url == null) throw new ArgumentNullException(nameof(url));
lock (lock_)
{
// re-connect only if the url has changed or has not been initialized.
if (url_ == null || !url_.Equals(url))
{
// release the current server.
if (server_ != null)
{
Uninitialize();
}
// instantiate a new server.
server_ = (IOPCCommon)Factory.Connect(url, connectData);
}
// save url.
url_ = (OpcUrl)url.Clone();
}
}
/// <summary>
/// Releases The remote server.
/// </summary>
public virtual void Uninitialize()
{
lock (lock_)
{
Dispose();
}
}
/// <summary>
/// Allows the client to optionally register a client name with the server. This is included primarily for debugging purposes. The recommended behavior is that the client set his Node name and EXE name here.
/// </summary>
public virtual void SetClientName(string clientName)
{
try
{
((IOPCCommon)server_).SetClientName(clientName);
}
catch (Exception e)
{
throw Utilities.Interop.CreateException("IOPCCommon.SetClientName", e);
}
}
/// <summary>
/// Allows cancellation control of DCOM callbacks to the server - by default DCOM calls will wait the default DCOM timeout
/// to fail - this method allows for tigher control of the timeout to wait. Note that DOCM calls can only be controlled
/// on a COM Single Threaded Apartment thread - use [STAThread] attribute on your application entry point or use Thread SetThreadApartment
/// before the thread the server is operating on is created to STA.
/// </summary>
/// <param name="timeout">The DCOM call timeout - uses the default timeout if not specified</param>
public void EnableDCOMCallCancellation(TimeSpan timeout = default)
{
DCOMCallWatchdog.Enable(timeout);
}
/// <summary>
/// Disables cancellation control of DCOM calls to the server
/// </summary>
public void DisableDCOMCallCancellation()
{
DCOMCallWatchdog.Disable();
}
#endregion
#region IOpcServer Members
/// <summary>
/// An event to receive server shutdown notifications.
/// </summary>
public virtual event OpcServerShutdownEventHandler ServerShutdownEvent
{
add
{
lock (lock_)
{
try
{
Advise();
callback_.ServerShutdown += value;
}
catch
{
// shutdown not supported.
}
}
}
remove
{
lock (lock_)
{
callback_.ServerShutdown -= value;
Unadvise();
}
}
}
/// <summary>
/// The locale used in any error messages or results returned to the client.
/// </summary>
/// <returns>The locale name in the format "[languagecode]-[country/regioncode]".</returns>
public virtual string GetLocale()
{
lock (this)
{
if (server_ == null) throw new NotConnectedException();
try
{
((IOPCCommon)server_).GetLocaleID(out var localeId);
return Interop.GetLocale(localeId);
}
catch (Exception e)
{
throw Interop.CreateException("IOPCCommon.GetLocaleID", e);
}
}
}
/// <summary>
/// Sets the locale used in any error messages or results returned to the client.
/// </summary>
/// <param name="locale">The locale name in the format "[languagecode]-[country/regioncode]".</param>
/// <returns>A locale that the server supports and is the best match for the requested locale.</returns>
public virtual string SetLocale(string locale)
{
lock (this)
{
if (server_ == null) throw new NotConnectedException();
var lcid = Interop.GetLocale(locale);
try
{
((IOPCCommon)server_).SetLocaleID(lcid);
}
catch (Exception e)
{
if (lcid != 0)
{
throw Interop.CreateException("IOPCCommon.SetLocaleID", e);
}
// use LOCALE_SYSTEM_DEFAULT if the server does not support the Neutral LCID.
try { ((IOPCCommon)server_).SetLocaleID(0x800); }
catch { }
}
return GetLocale();
}
}
/// <summary>
/// Returns the locales supported by the server
/// </summary>
/// <remarks>The first element in the array must be the default locale for the server.</remarks>
/// <returns>An array of locales with the format "[languagecode]-[country/regioncode]".</returns>
public virtual string[] GetSupportedLocales()
{
lock (lock_)
{
if (server_ == null) throw new NotConnectedException();
try
{
var count = 0;
var pLocaleIDs = IntPtr.Zero;
((IOPCCommon)server_).QueryAvailableLocaleIDs(out count, out pLocaleIDs);
var localeIDs = Interop.GetInt32s(ref pLocaleIDs, count, true);
if (localeIDs != null)
{
var locales = new ArrayList();
foreach (var localeID in localeIDs)
{
try { locales.Add(Interop.GetLocale(localeID)); }
catch { }
}
return (string[])locales.ToArray(typeof(string));
}
return null;
}
catch
{
//throw Interop.CreateException("IOPCCommon.QueryAvailableLocaleIDs", e);
return null;
}
}
}
/// <summary>
/// Returns the localized text for the specified result code.
/// </summary>
/// <param name="locale">The locale name in the format "[languagecode]-[country/regioncode]".</param>
/// <param name="resultId">The result code identifier.</param>
/// <returns>A message localized for the best match for the requested locale.</returns>
public virtual string GetErrorText(string locale, OpcResult resultId)
{
lock (lock_)
{
if (server_ == null) throw new NotConnectedException();
try
{
var currentLocale = GetLocale();
if (currentLocale != locale)
{
SetLocale(locale);
}
((IOPCCommon)server_).GetErrorString(resultId.Code, out var errorText);
if (currentLocale != locale)
{
SetLocale(currentLocale);
}
return errorText;
}
catch (Exception e)
{
throw Utilities.Interop.CreateException("IOPCServer.GetErrorString", e);
}
}
}
#endregion
#region Protected Members
/// <summary>
/// Releases all references to the server.
/// </summary>
protected virtual void ReleaseServer()
{
lock (lock_)
{
SafeNativeMethods.ReleaseServer(server_);
server_ = null;
}
}
/// <summary>
/// Checks if the server supports the specified interface.
/// </summary>
/// <typeparam name="T">The interface to check.</typeparam>
/// <returns>True if the server supports the interface.</returns>
protected bool SupportsInterface<T>() where T : class
{
lock (lock_)
{
return server_ is T;
}
}
#endregion
#region COM Call Tracing
/// <summary>
/// Must be called before any COM call.
/// </summary>
/// <typeparam name="T">The interface to used when making the call.</typeparam>
/// <param name="methodName">Name of the method.</param>
/// <param name="isRequiredInterface">if set to <c>true</c> interface is an required interface and and exception is thrown on error.</param>
/// <returns></returns>
protected T BeginComCall<T>(string methodName, bool isRequiredInterface) where T : class
{
return BeginComCall<T>(server_, methodName, isRequiredInterface);
}
/// <summary>
/// Must be called before any COM call.
/// </summary>
/// <typeparam name="T">The interface to used when making the call.</typeparam>
/// <param name="parent">Parent COM object</param>
/// <param name="methodName">Name of the method.</param>
/// <param name="isRequiredInterface">if set to <c>true</c> interface is an required interface and and exception is thrown on error.</param>
/// <returns></returns>
protected T BeginComCall<T>(object parent, string methodName, bool isRequiredInterface) where T : class
{
Utils.Trace(Utils.TraceMasks.ExternalSystem, "{0} called.", methodName);
lock (lock_)
{
outstandingCalls_++;
if (parent == null)
{
if (isRequiredInterface)
{
throw new NotConnectedException();
}
}
var comObject = parent as T;
if (comObject == null)
{
if (isRequiredInterface)
{
throw new NotSupportedException(Utils.Format("OPC Interface '{0}' is a required interface but not supported by the server.", typeof(T).Name));
}
else
{
Utils.Trace(Utils.TraceMasks.ExternalSystem, "OPC Interface '{0}' is not supported by server but it is only an optional one.", typeof(T).Name);
}
}
DCOMCallWatchdog.Set();
return comObject;
}
}
/// <summary>
/// Must called if a COM call returns an unexpected exception.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <param name="e">The exception.</param>
/// <remarks>Note that some COM calls are expected to return errors.</remarks>
protected void ComCallError(string methodName, Exception e)
{
SafeNativeMethods.TraceComError(e, methodName);
}
/// <summary>
/// Must be called in the finally block after making a COM call.
/// </summary>
/// <param name="methodName">Name of the method.</param>
protected void EndComCall(string methodName)
{
Utils.Trace(Utils.TraceMasks.ExternalSystem, "{0} completed.", methodName);
lock (lock_)
{
outstandingCalls_--;
DCOMCallWatchdog.Reset();
}
}
#endregion
#region Private Methods
/// <summary>
/// Establishes a connection point callback with the COM server.
/// </summary>
private void Advise()
{
if (connection_ == null)
{
connection_ = new ConnectionPoint(server_, typeof(IOPCShutdown).GUID);
connection_.Advise(callback_);
}
}
/// <summary>
/// Closes a connection point callback with the COM server.
/// </summary>
private void Unadvise()
{
if (connection_ != null)
{
if (connection_.Unadvise() == 0)
{
connection_.Dispose();
connection_ = null;
}
}
}
/// <summary>
/// A class that implements the IOPCShutdown interface.
/// </summary>
private class Callback : IOPCShutdown
{
/// <summary>
/// Initializes the object with the containing subscription object.
/// </summary>
public Callback(Server server)
{
m_server = server;
}
/// <summary>
/// An event to receive server shutdown notificiations.
/// </summary>
public event OpcServerShutdownEventHandler ServerShutdown
{
add { lock (lock_) { m_serverShutdown += value; } }
remove { lock (lock_) { m_serverShutdown -= value; } }
}
/// <summary>
/// A table of item identifiers indexed by internal handle.
/// </summary>
private Server m_server = null;
/// <summary>
/// Raised when data changed callbacks arrive.
/// </summary>
private event OpcServerShutdownEventHandler m_serverShutdown = null;
/// <summary>
/// Called when a shutdown event is received.
/// </summary>
public void ShutdownRequest(string reason)
{
try
{
lock (lock_)
{
if (m_serverShutdown != null)
{
m_serverShutdown(reason);
}
}
}
catch (Exception e)
{
var stack = e.StackTrace;
}
}
}
#endregion
}
}

View File

@@ -0,0 +1,320 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Net;
using System.Collections;
using System.Runtime.InteropServices;
using Technosoftware.OpcRcw.Comn;
using Technosoftware.DaAeHdaClient.Ae;
using Technosoftware.DaAeHdaClient.Da;
using Technosoftware.DaAeHdaClient.Hda;
#endregion
namespace Technosoftware.DaAeHdaClient.Com
{
/// <summary>
/// A unique identifier for the result of an operation of an item.
/// </summary>
public class ServerEnumerator : IOpcDiscovery
{
//======================================================================
// IDisposable
/// <summary>
/// Frees all unmanaged resources
/// </summary>
public void Dispose() {}
//======================================================================
// IDiscovery
/// <summary>
/// Enumerates hosts that may be accessed for server discovery.
/// </summary>
public string[] EnumerateHosts()
{
return Interop.EnumComputers();
}
/// <summary>
/// Returns a list of servers that support the specified interface specification.
/// </summary>
public OpcServer[] GetAvailableServers(OpcSpecification specification)
{
return GetAvailableServers(specification, null, null);
}
/// <summary>
/// Returns a list of servers that support the specified specification on the specified host.
/// </summary>
public OpcServer[] GetAvailableServers(OpcSpecification specification, string host, OpcConnectData connectData)
{
lock (this)
{
var credentials = (connectData != null)?connectData.GetCredential(null, null):null;
// connect to the server.
m_server = (IOPCServerList2)Interop.CreateInstance(CLSID, host, credentials, connectData?.UseConnectSecurity ?? false);
m_host = host;
try
{
var servers = new ArrayList();
// convert the interface version to a guid.
var catid = new Guid(specification.Id);
// get list of servers in the specified specification.
IOPCEnumGUID enumerator = null;
m_server.EnumClassesOfCategories(
1,
new Guid[] { catid },
0,
null,
out enumerator);
// read clsids.
var clsids = ReadClasses(enumerator);
// release enumerator object.
Interop.ReleaseServer(enumerator);
enumerator = null;
// fetch class descriptions.
foreach (var clsid in clsids)
{
var factory = new Factory();
try
{
var url = CreateUrl(specification, clsid);
OpcServer server = null;
if (specification == OpcSpecification.OPC_DA_30)
{
server = new TsCDaServer(factory, url);
}
else if (specification == OpcSpecification.OPC_DA_20)
{
server = new TsCDaServer(factory, url);
}
else if (specification == OpcSpecification.OPC_AE_10)
{
server = new TsCAeServer(factory, url);
}
else if (specification == OpcSpecification.OPC_HDA_10)
{
server = new TsCHdaServer(factory, url);
}
servers.Add(server);
}
catch (Exception)
{
// ignore bad clsids.
}
}
return (OpcServer[])servers.ToArray(typeof(OpcServer));
}
finally
{
// free the server.
Interop.ReleaseServer(m_server);
m_server = null;
}
}
}
/// <summary>
/// Looks up the CLSID for the specified prog id on a remote host.
/// </summary>
public Guid CLSIDFromProgID(string progID, string host, OpcConnectData connectData)
{
lock (this)
{
var credentials = (connectData != null)?connectData.GetCredential(null, null):null;
// connect to the server.
m_server = (IOPCServerList2)Interop.CreateInstance(CLSID, host, credentials, connectData?.UseConnectSecurity ?? false);
m_host = host;
// lookup prog id.
Guid clsid;
try
{
m_server.CLSIDFromProgID(progID, out clsid);
}
catch
{
clsid = Guid.Empty;
}
finally
{
Interop.ReleaseServer(m_server);
m_server = null;
}
// return empty guid if prog id not found.
return clsid;
}
}
//======================================================================
// Private Members
/// <summary>
/// The server enumerator COM server.
/// </summary>
private IOPCServerList2 m_server = null;
/// <summary>
/// The host where the servers are being enumerated.
/// </summary>
private string m_host = null;
/// <summary>
/// The ProgID for the OPC Server Enumerator.
/// </summary>
private const string ProgID = "OPC.ServerList.1";
/// <summary>
/// The CLSID for the OPC Server Enumerator.
/// </summary>
private static readonly Guid CLSID = new Guid("13486D51-4821-11D2-A494-3CB306C10000");
//======================================================================
// Private Methods
/// <summary>
/// Reads the guids from the enumerator.
/// </summary>
private Guid[] ReadClasses(IOPCEnumGUID enumerator)
{
var guids = new ArrayList();
var count = 10;
// create buffer.
var buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Guid))*count);
try
{
int fetched;
do
{
try
{
enumerator.Next(count, buffer, out fetched);
var pPos = buffer;
for (var ii = 0; ii < fetched; ii++)
{
var guid = (Guid)Marshal.PtrToStructure(pPos, typeof(Guid));
guids.Add(guid);
pPos = (IntPtr)(pPos.ToInt64() + Marshal.SizeOf(typeof(Guid)));
}
}
catch
{
break;
}
}
while (fetched > 0);
return (Guid[])guids.ToArray(typeof(Guid));
}
finally
{
Marshal.FreeCoTaskMem(buffer);
}
}
/// <summary>
/// Reads the server details from the enumerator.
/// </summary>
OpcUrl CreateUrl(OpcSpecification specification, Guid clsid)
{
// initialize the server url.
var url = new OpcUrl();
url.HostName = m_host;
url.Port = 0;
url.Path = null;
if (specification == OpcSpecification.OPC_DA_30) { url.Scheme = OpcUrlScheme.DA; }
else if (specification == OpcSpecification.OPC_DA_20) { url.Scheme = OpcUrlScheme.DA; }
else if (specification == OpcSpecification.OPC_DA_10) { url.Scheme = OpcUrlScheme.DA; }
else if (specification == OpcSpecification.OPC_AE_10) { url.Scheme = OpcUrlScheme.AE; }
else if (specification == OpcSpecification.OPC_HDA_10) { url.Scheme = OpcUrlScheme.HDA; }
try
{
// fetch class details from the enumerator.
string progID = null;
string description = null;
string verIndProgID = null;
m_server.GetClassDetails(
ref clsid,
out progID,
out description,
out verIndProgID);
// create the server URL path.
if (verIndProgID != null)
{
url.Path = string.Format("{0}/{1}", verIndProgID, "{" + clsid.ToString() + "}");
}
else if (progID != null)
{
url.Path = string.Format("{0}/{1}", progID, "{" + clsid.ToString() + "}");
}
}
catch (Exception)
{
// bad value in registry.
}
finally
{
// default to the clsid if the prog is not known.
if (url.Path == null)
{
url.Path = string.Format("{0}", "{" + clsid.ToString() + "}");
}
}
// return the server url.
return url;
}
}
}

View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Technosoftware.DaAeHdaClient.Com</AssemblyName>
<TargetFrameworks>net6.0</TargetFrameworks>
<LangVersion>9.0</LangVersion>
<PackageId>Technosoftware.DaAeHdaSolution.DaAeHdaClient.Com</PackageId>
<Description>OPC DA/AE/HDA Client Solution .NET</Description>
<Platforms>AnyCPU</Platforms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\OpcRcw\Technosoftware.OpcRcw.csproj" />
<ProjectReference Include="..\DaAeHdaClient\Technosoftware.DaAeHdaClient.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,390 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Technosoftware.DaAeHdaClient.Utilities;
namespace Technosoftware.DaAeHdaClient.Com.Utilities
{
/// <summary>
/// The result of DCOM watchdog
/// </summary>
public enum DCOMWatchdogResult
{
/// <summary>
/// Watchdog has not been set/there is no result
/// </summary>
None = 0,
/// <summary>
/// The Set/Reset cycle was manually completed i.e. the DCOM call did not timeout
/// </summary>
Completed,
/// <summary>
/// No Reset call occurred with the timeout period thus the current DCOM call was automatically cancelled
/// </summary>
TimedOut,
/// <summary>
/// The current DCOM call was manually cancelled
/// </summary>
ManuallyCancelled
}
/// <summary>
/// Watchdog mechanism to allow for cancellation of DCOM calls. Note that this mechanism will only work for a STA thread apartment - the thread on which
/// the watchdog is Set and DCOM calls are made have to be the same thread and the thread apartment model has to be set to STA.
/// </summary>
public static class DCOMCallWatchdog
{
#region Fields
private const int DEFAULT_TIMEOUT_SECONDS = 10;
private static object watchdogLock_ = new object();
private static uint watchDogThreadID_;
private static bool isCancelled_;
private static TimeSpan timeout_ = TimeSpan.Zero; //disabled by default
private static Task watchdogTask_;
private static DCOMWatchdogResult lastWatchdogResult_ = DCOMWatchdogResult.None;
private static DateTime setStart_;
#endregion
#region Properties
/// <summary>
/// The result of the last watchdog set/reset operation
/// </summary>
public static DCOMWatchdogResult LastWatchdogResult
{
get { return lastWatchdogResult_; }
}
/// <summary>
/// The current native thread ID on which the watchdog has been enabled
/// </summary>
public static uint WatchDogThreadID
{
get => watchDogThreadID_;
}
/// <summary>
/// Indicates if the watchdog mechanism is active or not
/// </summary>
public static bool IsEnabled
{
get => timeout_ != TimeSpan.Zero;
}
/// <summary>
/// Indicates if the watchdog has been set and is busy waiting for a call completion Reset to be called or a timeout to occur.
/// </summary>
public static bool IsSet
{
get => WatchDogThreadID != 0;
}
/// <summary>
/// Indicates if the watchdog was cancelled due to a timeout
/// </summary>
public static bool IsCancelled
{
get => isCancelled_;
}
/// <summary>
/// The watchdog timeout timespan
/// </summary>
public static TimeSpan Timeout
{
get => timeout_;
set
{
Enable(value);
}
}
#endregion
#region Methods
/// <summary>
/// Enables the Watchdog mechanism. This can be called from any thread and does not have to be the DCOM call originator thread.
/// Uses the default call timeout.
/// </summary>
public static void Enable()
{
Enable(TimeSpan.FromSeconds(DEFAULT_TIMEOUT_SECONDS));
}
/// <summary>
/// Enables the Watchdog mechanism. This can be called from any thread and does not have to be the DCOM call originator thread.
/// </summary>
/// <param name="timeout">The maximum time to wait for a DCOM call to succeed before it is cancelled. Note that DCOM will typically timeout
/// between 1-2 minutes, depending on the OS</param>
public static void Enable(TimeSpan timeout)
{
if (timeout == TimeSpan.Zero)
{
timeout = TimeSpan.FromSeconds(DEFAULT_TIMEOUT_SECONDS);
}
lock (watchdogLock_)
{
timeout_ = timeout;
}
watchdogTask_ = Task.Run(() => WatchdogTask());
}
/// <summary>
/// Disables the watchdog mechanism and stops any call cancellations.
/// </summary>
/// <returns>True if enabled and now disabled, otherwise false</returns>
public static bool Disable()
{
lock (watchdogLock_)
{
if (IsEnabled)
{
timeout_ = TimeSpan.Zero;
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Sets the watchdog timer active on the current thread. If Reset is not called within the timeout period, any current thread DCOM call will be cancelled. The
/// calling thread must be the originator of the DCOM call and must be an STA thread.
/// </summary>
/// <returns>True if the watchdog set succeeds or was already set for the current thread, else false if the watchdog is not enabled.</returns>
public static bool Set()
{
if (IsEnabled)
{
var apartmentState = Thread.CurrentThread.GetApartmentState();
if (apartmentState != ApartmentState.STA)
{
throw new InvalidOperationException("COM calls can only be cancelled on a COM STA apartment thread - use [STAThread] attibute or set the state of the thread on creation");
}
lock (watchdogLock_)
{
var threadId = Interop.GetCurrentThreadId();
if (IsSet)
{
if (threadId != watchDogThreadID_)
{
throw new InvalidOperationException($"Attempt to set call cancellation on different thread [{threadId}] to where it was already enabled [{watchDogThreadID_}]");
}
}
else
{
isCancelled_ = false;
watchDogThreadID_ = 0;
lastWatchdogResult_ = DCOMWatchdogResult.None;
//enable DCOM call cancellation for duration of the watchdog
var hresult = Interop.CoEnableCallCancellation(IntPtr.Zero);
if (hresult == 0)
{
setStart_ = DateTime.UtcNow;
watchDogThreadID_ = threadId;
Utils.Trace(Utils.TraceMasks.Information, $"COM call cancellation on thread [{watchDogThreadID_}] was set with timeout [{timeout_.TotalSeconds} seconds]");
}
else
{
throw new Exception($"Failed to set COM call cancellation (HResult = {hresult})");
}
}
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Refreshes the watchdog activity timer to now, effectively resetting the time to wait.
/// </summary>
/// <returns>True if the watchdog time was updated, else False if the watchdog timer is not Enabled or Set</returns>
public static bool Update()
{
if (IsEnabled)
{
lock (watchdogLock_)
{
if (IsSet)
{
setStart_ = DateTime.UtcNow;
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
/// <summary>
/// Resets the watchdog timer for the current thread. This should be called after a DCOM call returns to indicate the call succeeded, and thus cancelling the
/// watchdog timer.
/// </summary>
/// <returns>True if the watchdog timer was reset for the current thread, else False if the timer was not set for the thread of the watchdog is not enabled.</returns>
public static bool Reset()
{
if (IsEnabled)
{
lock (watchdogLock_)
{
if (IsSet)
{
var threadId = Interop.GetCurrentThreadId();
if (threadId == watchDogThreadID_)
{
if (!IsCancelled)
{
lastWatchdogResult_ = DCOMWatchdogResult.Completed;
}
watchDogThreadID_ = 0;
isCancelled_ = false;
//disable DCOM call cancellation
var hresult = Interop.CoDisableCallCancellation(IntPtr.Zero);
Utils.Trace(Utils.TraceMasks.Information, $"COM call cancellation on thread [{watchDogThreadID_}] was reset [HRESULT = {hresult}]");
}
else
{
throw new Exception($"COM call cancellation cannot be reset from different thread [{threadId}] it was set on [{watchDogThreadID_}]");
}
}
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Allows for manual cancellation of the current DCOM call
/// </summary>
/// <returns></returns>
public static bool Cancel()
{
return Cancel(DCOMWatchdogResult.ManuallyCancelled);
}
/// <summary>
/// Cancels the current DCOM call if there is one active
/// </summary>
/// <param name="reason"></param>
/// <returns>The reason for the cancellation</returns>
private static bool Cancel(DCOMWatchdogResult reason)
{
if (IsEnabled)
{
lock (watchdogLock_)
{
if (!IsCancelled && IsSet)
{
isCancelled_ = true;
//cancel the current DCOM call immediately
var hresult = Interop.CoCancelCall(watchDogThreadID_, 0);
Utils.Trace(Utils.TraceMasks.Information, $"COM call on thread [{watchDogThreadID_}] was cancelled [HRESULT = {hresult}]");
lastWatchdogResult_ = reason;
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
/// <summary>
/// The Watchdog Task is a seperate thread that is activated when the Watchdog is enabled. It checks the time since the last Set was called and
/// then cancels the current DCOM call automatically if Reset is not called within the timeout period.
/// </summary>
private static void WatchdogTask()
{
while (IsEnabled)
{
try
{
if (IsSet & !IsCancelled)
{
if (TimeElapsed(setStart_) >= timeout_)
{
Utils.Trace(Utils.TraceMasks.Information, $"Sync call watchdog for thread [{watchDogThreadID_}] timed out - cancelling current call...");
Cancel(DCOMWatchdogResult.TimedOut);
}
}
}
catch (Exception e)
{
Utils.Trace(Utils.TraceMasks.Error, $"Error in Sync call watchdog thread : {e.ToString()}");
}
finally
{
Thread.Sleep(1);
}
}
}
private static TimeSpan TimeElapsed(DateTime startTime)
{
var now = DateTime.UtcNow;
startTime = startTime.ToUniversalTime();
if (startTime > now)
{
return startTime - now;
}
else
{
return now - startTime;
}
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,72 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The description of an attribute supported by the server.
/// </summary>
[Serializable]
public class TsCAeAttribute : ICloneable
{
#region Properties
/// <summary>
/// A unique identifier for the attribute.
/// </summary>
public int ID { get; set; }
/// <summary>
/// The unique name for the attribute.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The data type of the attribute.
/// </summary>
public Type DataType { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name;
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a shallow copy of the object.
/// </summary>
public virtual object Clone() { return MemberwiseClone(); }
#endregion
}
}

View File

@@ -0,0 +1,62 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Contains a writable collection attribute ids.
/// </summary>
[Serializable]
public class TsCAeAttributeCollection : OpcWriteableCollection
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Creates an empty collection.
/// </summary>
internal TsCAeAttributeCollection() : base(null, typeof(int)) { }
/// <summary>
/// Creates a collection from an array.
/// </summary>
internal TsCAeAttributeCollection(int[] attributeIDs) : base(attributeIDs, typeof(int)) { }
#endregion
#region Public Methods
/// <summary>
/// An indexer for the collection.
/// </summary>
public new int this[int index] => (int)Array[index];
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new int[] ToArray()
{
return (int[])Array.ToArray(typeof(int));
}
#endregion
}
}

View File

@@ -0,0 +1,91 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Contains multiple lists of the attributes indexed by category.
/// </summary>
[Serializable]
public sealed class TsCAeAttributeDictionary : OpcWriteableDictionary
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Constructs an empty dictionary.
/// </summary>
public TsCAeAttributeDictionary() : base(null, typeof(int), typeof(TsCAeAttributeCollection)) { }
/// <summary>
/// Constructs an dictionary from a set of category ids.
/// </summary>
public TsCAeAttributeDictionary(int[] categoryIds)
: base(null, typeof(int), typeof(TsCAeAttributeCollection))
{
foreach (var categoryId in categoryIds)
{
Add(categoryId, null);
}
}
#endregion
#region Public Methods
/// <summary>
/// Gets or sets the attribute collection for the specified category.
/// </summary>
public TsCAeAttributeCollection this[int categoryId]
{
get => (TsCAeAttributeCollection)base[categoryId];
set
{
if (value != null)
{
base[categoryId] = value;
}
else
{
base[categoryId] = new TsCAeAttributeCollection();
}
}
}
/// <summary>
/// Adds an element with the provided key and value to the IDictionary.
/// </summary>
public void Add(int key, int[] value)
{
if (value != null)
{
base.Add(key, new TsCAeAttributeCollection(value));
}
else
{
base.Add(key, new TsCAeAttributeCollection());
}
}
#endregion
}
}

View File

@@ -0,0 +1,79 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The value of an attribute for an event source.
/// </summary>
[Serializable]
public class TsCAeAttributeValue : ICloneable, IOpcResult
{
#region Fields
private OpcResult result_ = OpcResult.S_OK;
#endregion
#region Properties
/// <summary>
/// A unique identifier for the attribute.
/// </summary>
public int ID { get; set; }
/// <summary>
/// The attribute value.
/// </summary>
public object Value { get; set; }
#endregion
#region IOpcResult Members
/// <summary>
/// The error id for the result of an operation on an property.
/// </summary>
public OpcResult Result
{
get => result_;
set => result_ = value;
}
/// <summary>
/// Vendor specific diagnostic information (not the localized error text).
/// </summary>
public string DiagnosticInfo { get; set; }
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
var clone = (TsCAeAttributeValue)MemberwiseClone();
clone.Value = OpcConvert.Clone(Value);
return clone;
}
#endregion
}
}

View File

@@ -0,0 +1,70 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Contains a description of an element in the server address space.
/// </summary>
[Serializable]
public class TsCAeBrowseElement
{
#region Fields
private TsCAeBrowseType browseType_ = TsCAeBrowseType.Area;
#endregion
#region Properties
/// <summary>
/// A descriptive name for element that is unique within a branch.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The fully qualified name for the element.
/// </summary>
public string QualifiedName { get; set; }
/// <summary>
/// Whether the element is a source or an area.
/// </summary>
public TsCAeBrowseType NodeType
{
get => browseType_;
set => browseType_ = value;
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
return MemberwiseClone();
}
#endregion
};
}

View File

@@ -0,0 +1,129 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Stores the state of a browse operation.
/// </summary>
[Serializable]
public class TsCAeBrowsePosition : IOpcBrowsePosition
{
#region Fields
private bool disposed_;
private string areaId_;
private TsCAeBrowseType browseType_;
private string browseFilter_;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Saves the parameters for an incomplete browse information.
/// </summary>
public TsCAeBrowsePosition(
string areaId,
TsCAeBrowseType browseType,
string browseFilter)
{
areaId_ = areaId;
browseType_ = browseType;
browseFilter_ = browseFilter;
}
/// <summary>
/// The finalizer implementation.
/// </summary>
~TsCAeBrowsePosition()
{
Dispose(false);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing">If true managed and unmanaged resources can be disposed. If false only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!disposed_)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
}
// Release unmanaged resources. If disposing is false,
// only the following code is executed.
}
disposed_ = true;
}
#endregion
#region Properties
/// <summary>
/// The fully qualified id for the area being browsed.
/// </summary>
public string AreaID => areaId_;
/// <summary>
/// The type of child element being returned with the browse.
/// </summary>
public TsCAeBrowseType BrowseType => browseType_;
/// <summary>
/// The filter applied to the name of the elements being returned.
/// </summary>
public string BrowseFilter => browseFilter_;
#endregion
#region ICloneable Members
/// <summary>
/// Creates a shallow copy of the object.
/// </summary>
public virtual object Clone()
{
return (TsCAeBrowsePosition)MemberwiseClone();
}
#endregion
}
}

View File

@@ -0,0 +1,44 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The type of nodes to return during a browse.
/// </summary>
public enum TsCAeBrowseType
{
/// <summary>
/// Return only nodes that are process areas.
/// </summary>
Area,
/// <summary>
/// Return only nodes that are event sources.
/// </summary>
Source
}
}

View File

@@ -0,0 +1,63 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The description of an event category supported by the server.
/// </summary>
[Serializable]
public class TsCAeCategory : ICloneable
{
#region Properties
/// <summary>
/// A unique identifier for the category.
/// </summary>
public int ID { get; set; }
/// <summary>
/// The unique name for the category.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name;
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a shallow copy of the object.
/// </summary>
public virtual object Clone() { return MemberwiseClone(); }
#endregion
}
}

View File

@@ -0,0 +1,75 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The bits indicating what changes generated an event notification.
/// </summary>
[Flags]
public enum TsCAeChangeMask
{
/// <summary>
/// The conditions active state has changed.
/// </summary>
ActiveState = 0x0001,
/// <summary>
/// The conditions acknowledgment state has changed.
/// </summary>
AcknowledgeState = 0x0002,
/// <summary>
/// The conditions enabled state has changed.
/// </summary>
EnableState = 0x0004,
/// <summary>
/// The condition quality has changed.
/// </summary>
Quality = 0x0008,
/// <summary>
/// The severity level has changed.
/// </summary>
Severity = 0x0010,
/// <summary>
/// The condition has transitioned into a new sub-condition.
/// </summary>
SubCondition = 0x0020,
/// <summary>
/// The event message has changed.
/// </summary>
Message = 0x0040,
/// <summary>
/// One or more event attributes have changed.
/// </summary>
Attribute = 0x0080
}
}

View File

@@ -0,0 +1,217 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using Technosoftware.DaAeHdaClient.Da;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The description of an item condition state supported by the server.
/// </summary>
[Serializable]
public class TsCAeCondition : ICloneable
{
#region Fields
private TsCAeSubCondition _activeSubcondition = new TsCAeSubCondition();
private TsCDaQuality _quality = TsCDaQuality.Bad;
private DateTime _lastAckTime = DateTime.MinValue;
private DateTime _subCondLastActive = DateTime.MinValue;
private DateTime _condLastActive = DateTime.MinValue;
private DateTime _condLastInactive = DateTime.MinValue;
private SubConditionCollection _subconditions = new SubConditionCollection();
private AttributeValueCollection _attributes = new AttributeValueCollection();
#endregion
#region AttributeCollection Class
/// <summary>
/// Contains a read-only collection of AttributeValues.
/// </summary>
public class AttributeValueCollection : OpcWriteableCollection
{
/// <summary>
/// An indexer for the collection.
/// </summary>
public new TsCAeAttributeValue this[int index] => (TsCAeAttributeValue)Array[index];
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new TsCAeAttributeValue[] ToArray()
{
return (TsCAeAttributeValue[])Array.ToArray();
}
/// <summary>
/// Creates an empty collection.
/// </summary>
internal AttributeValueCollection() : base(null, typeof(TsCAeAttributeValue)) { }
}
#endregion
#region SubConditionCollection Class
/// <summary>
/// Contains a read-only collection of SubConditions.
/// </summary>
public class SubConditionCollection : OpcWriteableCollection
{
/// <summary>
/// An indexer for the collection.
/// </summary>
public new TsCAeSubCondition this[int index] => (TsCAeSubCondition)Array[index];
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new TsCAeSubCondition[] ToArray()
{
return (TsCAeSubCondition[])Array.ToArray();
}
/// <summary>
/// Creates an empty collection.
/// </summary>
internal SubConditionCollection() : base(null, typeof(TsCAeSubCondition)) { }
}
#endregion
#region Properties
/// <summary>
/// A bit mask indicating the current state of the condition
/// </summary>
public int State { get; set; }
/// <summary>
/// The currently active sub-condition, for multi-state conditions which are active.
/// For a single-state condition, this contains the information about the condition itself.
/// For inactive conditions, this value is null.
/// </summary>
public TsCAeSubCondition ActiveSubCondition
{
get => _activeSubcondition;
set => _activeSubcondition = value;
}
/// <summary>
/// The quality associated with the condition state.
/// </summary>
public TsCDaQuality Quality
{
get => _quality;
set => _quality = value;
}
/// <summary>
/// The time of the most recent acknowledgment of this condition (of any sub-condition).
/// The <see cref="ApplicationInstance.TimeAsUtc">ApplicationInstance.TimeAsUtc</see> property defines
/// the time format (UTC or local time).
/// </summary>
public DateTime LastAckTime
{
get => _lastAckTime;
set => _lastAckTime = value;
}
/// <summary>
/// Time of the most recent transition into active sub-condition.
/// This is the time value which must be specified when acknowledging the condition.
/// If the condition has never been active, this value is DateTime.MinValue.
/// The <see cref="ApplicationInstance.TimeAsUtc">ApplicationInstance.TimeAsUtc</see> property defines
/// the time format (UTC or local time).
/// </summary>
public DateTime SubCondLastActive
{
get => _subCondLastActive;
set => _subCondLastActive = value;
}
/// <summary>
/// Time of the most recent transition into the condition.
/// There may be transitions among the sub-conditions which are more recent.
/// If the condition has never been active, this value is DateTime.MinValue.
/// The <see cref="ApplicationInstance.TimeAsUtc">ApplicationInstance.TimeAsUtc</see> property defines
/// the time format (UTC or local time).
/// </summary>
public DateTime CondLastActive
{
get => _condLastActive;
set => _condLastActive = value;
}
/// <summary>
/// Time of the most recent transition out of this condition.
/// This value is DateTime.MinValue if the condition has never been active,
/// or if it is currently active for the first time and has never been exited.
/// The <see cref="ApplicationInstance.TimeAsUtc">ApplicationInstance.TimeAsUtc</see> property defines
/// the time format (UTC or local time).
/// </summary>
public DateTime CondLastInactive
{
get => _condLastInactive;
set => _condLastInactive = value;
}
/// <summary>
/// This is the ID of the client who last acknowledged this condition.
/// This value is null if the condition has never been acknowledged.
/// </summary>
public string AcknowledgerID { get; set; }
/// <summary>
/// The comment string passed in by the client who last acknowledged this condition.
/// This value is null if the condition has never been acknowledged.
/// </summary>
public string Comment { get; set; }
/// <summary>
/// The sub-conditions defined for this condition.
/// For single-state conditions, the collection will contain one element, the value of which describes the condition.
/// </summary>
public SubConditionCollection SubConditions => _subconditions;
/// <summary>
/// The values of the attributes requested for this condition.
/// </summary>
public AttributeValueCollection Attributes => _attributes;
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
var clone = (TsCAeCondition)MemberwiseClone();
clone._activeSubcondition = (TsCAeSubCondition)_activeSubcondition.Clone();
clone._subconditions = (SubConditionCollection)_subconditions.Clone();
clone._attributes = (AttributeValueCollection)_attributes.Clone();
return clone;
}
#endregion
}
}

View File

@@ -0,0 +1,50 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The possible states for a condition.
/// </summary>
[Flags]
public enum TsCAeConditionState
{
/// <summary>
/// The server is currently checking the state of the condition.
/// </summary>
Enabled = 0x0001,
/// <summary>
/// The associated object is in the state represented by the condition.
/// </summary>
Active = 0x0002,
/// <summary>
/// The condition has been acknowledged.
/// </summary>
Acknowledged = 0x0004
}
}

View File

@@ -0,0 +1,95 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The current state of a process area or an event source.
/// </summary>
public class TsCAeEnabledStateResult : IOpcResult
{
#region Fields
private string qualifiedName_;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with default values.
/// </summary>
public TsCAeEnabledStateResult() { }
/// <summary>
/// Initializes the object with an qualified name.
/// </summary>
public TsCAeEnabledStateResult(string qualifiedName)
{
qualifiedName_ = qualifiedName;
}
/// <summary>
/// Initializes the object with an qualified name and Result.
/// </summary>
public TsCAeEnabledStateResult(string qualifiedName, OpcResult result)
{
qualifiedName_ = qualifiedName;
Result = result;
}
#endregion
#region Properties
/// <summary>
/// Whether if the area or source is enabled.
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Whether the area or source is enabled and all areas within the hierarchy of its containing areas are enabled.
/// </summary>
public bool EffectivelyEnabled { get; set; }
#endregion
#region IOpcResult Members
/// <summary>
/// The error id for the result of an operation on an item.
/// </summary>
public OpcResult Result { get; set; } = OpcResult.S_OK;
/// <summary>
/// Vendor specific diagnostic information (not the localized error text).
/// </summary>
public string DiagnosticInfo { get; set; }
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
return MemberwiseClone();
}
#endregion
}
}

View File

@@ -0,0 +1,93 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Specifies the information required to acknowledge an event.
/// </summary>
[Serializable]
public class TsCAeEventAcknowledgement : ICloneable
{
#region Fields
private DateTime activeTime_ = DateTime.MinValue;
#endregion
#region Properties
/// <summary>
/// The name of the source that generated the event.
/// </summary>
public string SourceName { get; set; }
/// <summary>
/// The name of the condition that is being acknowledged.
/// </summary>
public string ConditionName { get; set; }
/// <summary>
/// The time that the condition or sub-condition became active.
/// The <see cref="ApplicationInstance.TimeAsUtc">ApplicationInstance.TimeAsUtc</see> property defines
/// the time format (UTC or local time).
/// </summary>
public DateTime ActiveTime
{
get => activeTime_;
set => activeTime_ = value;
}
/// <summary>
/// The cookie for the condition passed to client during the event notification.
/// </summary>
public int Cookie { get; set; }
/// <summary>
/// Constructs an acknowledgment with its default values.
/// </summary>
public TsCAeEventAcknowledgement() { }
/// <summary>
/// Constructs an acknowledgment from an event notification.
/// </summary>
public TsCAeEventAcknowledgement(TsCAeEventNotification notification)
{
SourceName = notification.SourceID;
ConditionName = notification.ConditionName;
activeTime_ = notification.ActiveTime;
Cookie = notification.Cookie;
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
return MemberwiseClone();
}
#endregion
}
}

View File

@@ -0,0 +1,275 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using Technosoftware.DaAeHdaClient.Da;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// A notification sent by the server when an event change occurs.
/// </summary>
[Serializable]
public class TsCAeEventNotification : ICloneable
{
#region Fields
private DateTime time_ = DateTime.MinValue;
private TsCAeEventType eventType_ = TsCAeEventType.Condition;
private int severity_ = 1;
private AttributeCollection attributes_ = new AttributeCollection();
private TsCDaQuality daQuality_ = TsCDaQuality.Bad;
private DateTime activeTime_ = DateTime.MinValue;
#endregion
#region AttributeCollection Class
/// <summary>
/// Contains a read-only collection of AttributeValues.
/// </summary>
[Serializable]
public class AttributeCollection : OpcReadOnlyCollection
{
/// <summary>
/// Creates an empty collection.
/// </summary>
internal AttributeCollection() : base(new object[0]) { }
/// <summary>
/// Creates a collection from an array of objects.
/// </summary>
internal AttributeCollection(object[] attributes) : base(attributes) { }
}
#endregion
#region Properties
/// <summary>
/// The handle of the subscription that requested the notification
/// </summary>
public object ClientHandle { get; set; }
/// <summary>
/// The identifier for the source that generated the event.
/// </summary>
public string SourceID { get; set; }
/// <summary>
/// The time of the event occurrence.
/// The <see cref="ApplicationInstance.TimeAsUtc">ApplicationInstance.TimeAsUtc</see> property defines
/// the time format (UTC or local time).
/// </summary>
public DateTime Time
{
get => time_;
set => time_ = value;
}
/// <summary>
/// Event notification message describing the event.
/// </summary>
public string Message { get; set; }
/// <summary>
/// The type of event that generated the notification.
/// </summary>
public TsCAeEventType EventType
{
get => eventType_;
set => eventType_ = value;
}
/// <summary>
/// The vendor defined category id for the event.
/// </summary>
public int EventCategory { get; set; }
/// <summary>
/// The severity of the event (1..1000).
/// </summary>
public int Severity
{
get => severity_;
set => severity_ = value;
}
/// <summary>
/// The name of the condition related to this event notification.
/// </summary>
public string ConditionName { get; set; }
/// <summary>
/// The name of the current sub-condition, for multi-state conditions.
/// For a single-state condition, this contains the condition name.
/// </summary>
public string SubConditionName { get; set; }
/// <summary>
/// The values of the attributes selected for the event subscription.
/// </summary>
public AttributeCollection Attributes => attributes_;
/// <summary>
/// Indicates which properties of the condition have changed, to have caused the server to send the event notification.
/// </summary>
public int ChangeMask { get; set; }
/// <summary>
/// Indicates which properties of the condition have changed, to have caused the server to send the event notification.
/// </summary>
// ReSharper disable once UnusedMember.Global
public string ChangeMaskAsText
{
get
{
string str = null;
if ((ChangeMask & 0x0001) == 0x0001) str = "Active State, ";
if ((ChangeMask & 0x0002) == 0x0002) str += "Ack State, ";
if ((ChangeMask & 0x0004) == 0x0004) str += "Enable State, ";
if ((ChangeMask & 0x0008) == 0x0005) str += "Quality, ";
if ((ChangeMask & 0x0010) == 0x0010) str += "Severity, ";
if ((ChangeMask & 0x0020) == 0x0020) str += "SubCondition, ";
if ((ChangeMask & 0x0040) == 0x0040) str += "Message, ";
if ((ChangeMask & 0x0080) == 0x0080) str += "Attribute";
return str;
}
}
/// <summary>
/// A bit mask specifying the new state of the condition.
/// </summary>
public int NewState { get; set; }
/// <summary>
/// A bit mask specifying the new state of the condition.
/// </summary>
// ReSharper disable once UnusedMember.Global
public string NewStateAsText
{
get
{
string str;
if ((NewState & 0x0001) == 0x0001)
{
str = "Active, ";
}
else
{
str = "Inactive, ";
}
if ((NewState & 0x0002) == 0x0002)
{
str += "Acknowledged, ";
}
else
{
str += "UnAcknowledged, ";
}
if ((NewState & 0x0004) == 0x0004)
{
str += "Enabled";
}
else
{
str += "Disabled";
}
return str;
}
}
/// <summary>
/// The quality associated with the condition state.
/// </summary>
public TsCDaQuality Quality
{
get => daQuality_;
set => daQuality_ = value;
}
/// <summary>
/// Whether the related condition requires acknowledgment of this event.
/// </summary>
public bool AckRequired { get; set; }
/// <summary>
/// The time that the condition became active (for single-state conditions), or the
/// time of the transition into the current sub-condition (for multi-state conditions).
/// The <see cref="ApplicationInstance.TimeAsUtc">ApplicationInstance.TimeAsUtc</see> property defines
/// the time format (UTC or local time).
/// </summary>
public DateTime ActiveTime
{
get => activeTime_;
set => activeTime_ = value;
}
/// <summary>
/// A server defined cookie associated with the event notification.
/// </summary>
public int Cookie { get; set; }
/// <summary>
/// For tracking events, this is the actor id for the event notification.
/// For condition-related events, this is the acknowledgment id passed by the client.
/// </summary>
public string ActorID { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Sets the list of attribute values.
/// </summary>
public void SetAttributes(object[] attributes)
{
if (attributes == null)
{
attributes_ = new AttributeCollection();
}
else
{
attributes_ = new AttributeCollection(attributes);
}
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
var clone = (TsCAeEventNotification)MemberwiseClone();
clone.attributes_ = (AttributeCollection)attributes_.Clone();
return clone;
}
#endregion
}
}

View File

@@ -0,0 +1,54 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The types of events that could be generated by a server.
/// </summary>
[Flags]
public enum TsCAeEventType
{
/// <summary>
/// Events that are not tracking or condition events.
/// </summary>
Simple = 0x0001,
/// <summary>
/// Events that represent occurrences which involve the interaction of the client with a target within the server.
/// </summary>
Tracking = 0x0002,
/// <summary>
/// Events that are associated with transitions in and out states defined by the server.
/// </summary>
Condition = 0x0004,
/// <summary>
/// All events generated by the server.
/// </summary>
All = 0xFFFF
}
}

View File

@@ -0,0 +1,65 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The types of event filters that the server could support.
/// </summary>
[Flags]
public enum TsCAeFilterType
{
/// <summary>
/// The server supports filtering by event type.
/// </summary>
Event = 0x0001,
/// <summary>
/// The server supports filtering by event categories.
/// </summary>
Category = 0x0002,
/// <summary>
/// The server supports filtering by severity levels.
/// </summary>
Severity = 0x0004,
/// <summary>
/// The server supports filtering by process area.
/// </summary>
Area = 0x0008,
/// <summary>
/// The server supports filtering by event sources.
/// </summary>
Source = 0x0010,
/// <summary>
/// All filters supported by the server.
/// </summary>
All = 0xFFFF
}
}

View File

@@ -0,0 +1,202 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Defines functionality that is common to all OPC Alarms and Events servers.
/// </summary>
public interface ITsCAeServer : IOpcServer
{
/// <summary>
/// Returns the current server status.
/// </summary>
/// <returns>The current server status.</returns>
OpcServerStatus GetServerStatus();
/// <summary>
/// Creates a new event subscription.
/// </summary>
/// <param name="state">The initial state for the subscription.</param>
/// <returns>The new subscription object.</returns>
ITsCAeSubscription CreateSubscription(TsCAeSubscriptionState state);
/// <summary>
/// Returns the event filters supported by the server.
/// </summary>
/// <returns>A bit mask of all event filters supported by the server.</returns>
int QueryAvailableFilters();
/// <summary>
/// Returns the event categories supported by the server for the specified event types.
/// </summary>
/// <param name="eventType">A bit mask for the event types of interest.</param>
/// <returns>A collection of event categories.</returns>
TsCAeCategory[] QueryEventCategories(int eventType);
/// <summary>
/// Returns the condition names supported by the server for the specified event categories.
/// </summary>
/// <param name="eventCategory">A bit mask for the event categories of interest.</param>
/// <returns>A list of condition names.</returns>
string[] QueryConditionNames(int eventCategory);
/// <summary>
/// Returns the sub-condition names supported by the server for the specified event condition.
/// </summary>
/// <param name="conditionName">The name of the condition.</param>
/// <returns>A list of sub-condition names.</returns>
string[] QuerySubConditionNames(string conditionName);
/// <summary>
/// Returns the condition names supported by the server for the specified event source.
/// </summary>
/// <param name="sourceName">The name of the event source.</param>
/// <returns>A list of condition names.</returns>
string[] QueryConditionNames(string sourceName);
/// <summary>
/// Returns the event attributes supported by the server for the specified event categories.
/// </summary>
/// <param name="eventCategory">The event category of interest.</param>
/// <returns>A collection of event attributes.</returns>
TsCAeAttribute[] QueryEventAttributes(int eventCategory);
/// <summary>
/// Returns the DA item ids for a set of attribute ids belonging to events which meet the specified filter criteria.
/// </summary>
/// <param name="sourceName">The event source of interest.</param>
/// <param name="eventCategory">The id of the event category for the events of interest.</param>
/// <param name="conditionName">The name of a condition within the event category.</param>
/// <param name="subConditionName">The name of a sub-condition within a multi-state condition.</param>
/// <param name="attributeIDs">The ids of the attributes to return item ids for.</param>
/// <returns>A list of item urls for each specified attribute.</returns>
TsCAeItemUrl[] TranslateToItemIDs(
string sourceName,
int eventCategory,
string conditionName,
string subConditionName,
int[] attributeIDs);
/// <summary>
/// Returns the current state information for the condition instance corresponding to the source and condition name.
/// </summary>
/// <param name="sourceName">The source name</param>
/// <param name="conditionName">A condition name for the source.</param>
/// <param name="attributeIDs">The list of attributes to return with the condition state.</param>
/// <returns>The current state of the connection.</returns>
TsCAeCondition GetConditionState(
string sourceName,
string conditionName,
int[] attributeIDs);
/// <summary>
/// Places the specified process areas into the enabled state.
/// </summary>
/// <param name="areas">A list of fully qualified area names.</param>
/// <returns>The results of the operation for each area.</returns>
OpcResult[] EnableConditionByArea(string[] areas);
/// <summary>
/// Places the specified process areas into the disabled state.
/// </summary>
/// <param name="areas">A list of fully qualified area names.</param>
/// <returns>The results of the operation for each area.</returns>
OpcResult[] DisableConditionByArea(string[] areas);
/// <summary>
/// Places the specified process areas into the enabled state.
/// </summary>
/// <param name="sources">A list of fully qualified source names.</param>
/// <returns>The results of the operation for each area.</returns>
OpcResult[] EnableConditionBySource(string[] sources);
/// <summary>
/// Places the specified process areas into the disabled state.
/// </summary>
/// <param name="sources">A list of fully qualified source names.</param>
/// <returns>The results of the operation for each area.</returns>
OpcResult[] DisableConditionBySource(string[] sources);
/// <summary>
/// Returns the enabled state for the specified process areas.
/// </summary>
/// <param name="areas">A list of fully qualified area names.</param>
TsCAeEnabledStateResult[] GetEnableStateByArea(string[] areas);
/// <summary>
/// Returns the enabled state for the specified event sources.
/// </summary>
/// <param name="sources">A list of fully qualified source names.</param>
TsCAeEnabledStateResult[] GetEnableStateBySource(string[] sources);
/// <summary>
/// Used to acknowledge one or more conditions in the event server.
/// </summary>
/// <param name="acknowledgerID">The identifier for who is acknowledging the condition.</param>
/// <param name="comment">A comment associated with the acknowledgment.</param>
/// <param name="conditions">The conditions being acknowledged.</param>
/// <returns>A list of result id indictaing whether each condition was successfully acknowledged.</returns>
OpcResult[] AcknowledgeCondition(
string acknowledgerID,
string comment,
TsCAeEventAcknowledgement[] conditions);
/// <summary>
/// Browses for all children of the specified area that meet the filter criteria.
/// </summary>
/// <param name="areaID">The full-qualified id for the area.</param>
/// <param name="browseType">The type of children to return.</param>
/// <param name="browseFilter">The expression used to filter the names of children returned.</param>
/// <returns>The set of elements that meet the filter criteria.</returns>
TsCAeBrowseElement[] Browse(
string areaID,
TsCAeBrowseType browseType,
string browseFilter);
/// <summary>
/// Browses for all children of the specified area that meet the filter criteria.
/// </summary>
/// <param name="areaID">The full-qualified id for the area.</param>
/// <param name="browseType">The type of children to return.</param>
/// <param name="browseFilter">The expression used to filter the names of children returned.</param>
/// <param name="maxElements">The maximum number of elements to return.</param>
/// <param name="position">The object used to continue the browse if the number nodes exceeds the maximum specified.</param>
/// <returns>The set of elements that meet the filter criteria.</returns>
TsCAeBrowseElement[] Browse(
string areaID,
TsCAeBrowseType browseType,
string browseFilter,
int maxElements,
out IOpcBrowsePosition position);
/// <summary>
/// Continues browsing the server's address space at the specified position.
/// </summary>
/// <param name="maxElements">The maximum number of elements to return.</param>
/// <param name="position">The position object used to continue a browse operation.</param>
/// <returns>The set of elements that meet the filter criteria.</returns>
TsCAeBrowseElement[] BrowseNext(int maxElements, ref IOpcBrowsePosition position);
}
}

View File

@@ -0,0 +1,109 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// An interface to an object which implements a AE event subscription.
/// </summary>
public interface ITsCAeSubscription : IDisposable
{
#region Events
/// <summary>
/// An event to receive event change updates.
/// </summary>
event TsCAeDataChangedEventHandler DataChangedEvent;
#endregion
#region State Management
/// <summary>
/// Returns the current state of the subscription.
/// </summary>
/// <returns>The current state of the subscription.</returns>
TsCAeSubscriptionState GetState();
/// <summary>
/// Changes the state of a subscription.
/// </summary>
/// <param name="masks">A bit mask that indicates which elements of the subscription state are changing.</param>
/// <param name="state">The new subscription state.</param>
/// <returns>The actual subscription state after applying the changes.</returns>
TsCAeSubscriptionState ModifyState(int masks, TsCAeSubscriptionState state);
#endregion
#region Filter Management
/// <summary>
/// Returns the current filters for the subscription.
/// </summary>
/// <returns>The current filters for the subscription.</returns>
TsCAeSubscriptionFilters GetFilters();
/// <summary>
/// Sets the current filters for the subscription.
/// </summary>
/// <param name="filters">The new filters to use for the subscription.</param>
void SetFilters(TsCAeSubscriptionFilters filters);
#endregion
#region Attribute Management
/// <summary>
/// Returns the set of attributes to return with event notifications.
/// </summary>
/// <param name="eventCategory">The specific event category for which the attributes apply.</param>
/// <returns>The set of attribute ids which returned with event notifications.</returns>
int[] GetReturnedAttributes(int eventCategory);
/// <summary>
/// Selects the set of attributes to return with event notifications.
/// </summary>
/// <param name="eventCategory">The specific event category for which the attributes apply.</param>
/// <param name="attributeIDs">The list of attribute ids to return.</param>
void SelectReturnedAttributes(int eventCategory, int[] attributeIDs);
#endregion
#region Refresh
/// <summary>
/// Force a refresh for all active conditions and inactive, unacknowledged conditions whose event notifications match the filter of the event subscription.
/// </summary>
void Refresh();
/// <summary>
/// Cancels an outstanding refresh request.
/// </summary>
void CancelRefresh();
#endregion
}
#region Delegate Declarations
/// <summary>
/// A delegate to receive data change updates from the server.
/// </summary>
/// <param name="notifications">The notifications sent by the server when a event change occurs.</param>
/// <param name="refresh">TRUE if this is a subscription refresh</param>
/// <param name="lastRefresh">TRUE if this is the last subscription refresh in response to a specific invocation of the Refresh method.</param>
public delegate void TsCAeDataChangedEventHandler(TsCAeEventNotification[] notifications, bool refresh, bool lastRefresh);
#endregion
}

View File

@@ -0,0 +1,93 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The item id and network location of a DA item associated with an event source.
/// </summary>
[Serializable]
public class TsCAeItemUrl : OpcItem
{
#region Fields
private OpcUrl url_ = new OpcUrl();
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with default values.
/// </summary>
public TsCAeItemUrl() {}
/// <summary>
/// Initializes the object with an ItemIdentifier object.
/// </summary>
public TsCAeItemUrl(OpcItem item) : base(item) {}
/// <summary>
/// Initializes the object with an ItemIdentifier object and url.
/// </summary>
public TsCAeItemUrl(OpcItem item, OpcUrl url)
: base(item)
{
Url = url;
}
/// <summary>
/// Initializes object with the specified ItemResult object.
/// </summary>
public TsCAeItemUrl(TsCAeItemUrl item) : base(item)
{
if (item != null)
{
Url = item.Url;
}
}
#endregion
#region Properties
/// <summary>
/// The url of the server that contains the item.
/// </summary>
public OpcUrl Url
{
get => url_;
set => url_ = value;
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public override object Clone()
{
return new TsCAeItemUrl(this);
}
#endregion
}
}

View File

@@ -0,0 +1,60 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Contains a collection of item urls.
/// </summary>
internal class TsCAeItemUrlCollection : OpcReadOnlyCollection
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Constructs an empty collection.
/// </summary>
public TsCAeItemUrlCollection() : base(new TsCAeItemUrl[0]) { }
/// <summary>
/// Constructs a collection from an array of item urls.
/// </summary>
public TsCAeItemUrlCollection(TsCAeItemUrl[] itemUrls) : base(itemUrls) { }
#endregion
#region Public Methods
/// <summary>
/// An indexer for the collection.
/// </summary>
public new TsCAeItemUrl this[int index] => (TsCAeItemUrl)Array.GetValue(index);
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new TsCAeItemUrl[] ToArray()
{
return (TsCAeItemUrl[])OpcConvert.Clone(Array);
}
#endregion
}
}

View File

@@ -0,0 +1,661 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using System.Runtime.Serialization;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// An in-process object which provides access to AE server objects.
/// </summary>
[Serializable]
public class TsCAeServer : OpcServer, ITsCAeServer
{
#region SubscriptionCollection Class
/// <summary>
/// A read-only collection of subscriptions.
/// </summary>
public class SubscriptionCollection : OpcReadOnlyCollection
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Creates an empty collection.
/// </summary>
internal SubscriptionCollection() : base(new TsCAeSubscription[0]) { }
#endregion
#region Public Methods
/// <summary>
/// An indexer for the collection.
/// </summary>
public new TsCAeSubscription this[int index] => (TsCAeSubscription)Array.GetValue(index);
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new TsCAeSubscription[] ToArray()
{
return (TsCAeSubscription[])Array;
}
/// <summary>
/// Adds a subscription to the end of the collection.
/// </summary>
internal void Add(TsCAeSubscription subscription)
{
var array = new TsCAeSubscription[Count + 1];
Array.CopyTo(array, 0);
array[Count] = subscription;
Array = array;
}
/// <summary>
/// Removes a subscription to the from the collection.
/// </summary>
internal void Remove(TsCAeSubscription subscription)
{
var array = new TsCAeSubscription[Count - 1];
var index = 0;
for (var ii = 0; ii < Array.Length; ii++)
{
var element = (TsCAeSubscription)Array.GetValue(ii);
if (subscription != element)
{
array[index++] = element;
}
}
Array = array;
}
#endregion
}
#endregion
#region Names Class
/// <summary>
/// A set of names for fields used in serialization.
/// </summary>
private class Names
{
internal const string Count = "CT";
internal const string Subscription = "SU";
}
#endregion
#region Fields
private int filters_;
private bool disposing_;
private SubscriptionCollection subscriptions_ = new SubscriptionCollection();
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with a factory and a default OpcUrl.
/// </summary>
/// <param name="factory">The OpcFactory used to connect to remote servers.</param>
/// <param name="url">The network address of a remote server.</param>
public TsCAeServer(OpcFactory factory, OpcUrl url)
: base(factory, url)
{
}
/// <summary>
/// Constructs a server by de-serializing its OpcUrl from the stream.
/// </summary>
protected TsCAeServer(SerializationInfo info, StreamingContext context)
:
base(info, context)
{
var count = (int)info.GetValue(Names.Count, typeof(int));
subscriptions_ = new SubscriptionCollection();
for (var ii = 0; ii < count; ii++)
{
var subscription = (TsCAeSubscription)info.GetValue(Names.Subscription + ii, typeof(TsCAeSubscription));
subscriptions_.Add(subscription);
}
}
#endregion
#region Properties
/// <summary>
/// The filters supported by the server.
/// </summary>
// ReSharper disable once UnusedMember.Global
public int AvailableFilters => filters_;
/// <summary>
/// The outstanding subscriptions for the server.
/// </summary>
public SubscriptionCollection Subscriptions => subscriptions_;
#endregion
#region Public Methods
/// <summary>
/// Connects to the server with the specified OpcUrl and credentials.
/// </summary>
public override void Connect(OpcUrl url, OpcConnectData connectData)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
// connect to server.
base.Connect(url, connectData);
// all done if no subscriptions.
if (subscriptions_.Count == 0)
{
return;
}
// create subscriptions (should only happen if server has been deserialized).
var subscriptions = new SubscriptionCollection();
foreach (TsCAeSubscription template in subscriptions_)
{
// create subscription for template.
try { subscriptions.Add(EstablishSubscription(template)); }
catch
{
// ignored
}
}
// save new set of subscriptions.
subscriptions_ = subscriptions;
}
/// <summary>
/// Disconnects from the server and releases all network resources.
/// </summary>
public override void Disconnect()
{
if (Server == null) throw new NotConnectedException();
// dispose of all subscriptions first.
disposing_ = true;
foreach (TsCAeSubscription subscription in subscriptions_)
{
subscription.Dispose();
}
disposing_ = false;
// disconnect from server.
base.Disconnect();
}
/// <summary>
/// Returns the current server status.
/// </summary>
/// <returns>The current server status.</returns>
public OpcServerStatus GetServerStatus()
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
var status = ((ITsCAeServer)Server).GetServerStatus();
if (status != null)
{
if (status.StatusInfo == null)
{
status.StatusInfo = GetString($"serverState.{status.ServerState}");
}
}
else
{
if (Server == null) throw new NotConnectedException();
}
return status;
}
/// <summary>
/// Creates a new event subscription.
/// </summary>
/// <param name="state">The initial state for the subscription.</param>
/// <returns>The new subscription object.</returns>
public ITsCAeSubscription CreateSubscription(TsCAeSubscriptionState state)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
// create remote object.
var subscription = ((ITsCAeServer)Server).CreateSubscription(state);
if (subscription != null)
{
// create wrapper.
var wrapper = new TsCAeSubscription(this, subscription, state);
subscriptions_.Add(wrapper);
return wrapper;
}
// should never happen.
return null;
}
/// <summary>
/// Returns the event filters supported by the server.
/// </summary>
/// <returns>A bit mask of all event filters supported by the server.</returns>
public int QueryAvailableFilters()
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
filters_ = ((ITsCAeServer)Server).QueryAvailableFilters();
return filters_;
}
/// <summary>
/// Returns the event categories supported by the server for the specified event types.
/// </summary>
/// <param name="eventType">A bit mask for the event types of interest.</param>
/// <returns>A collection of event categories.</returns>
public TsCAeCategory[] QueryEventCategories(int eventType)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
// fetch categories from server.
var categories = ((ITsCAeServer)Server).QueryEventCategories(eventType);
// return result.
return categories;
}
/// <summary>
/// Returns the condition names supported by the server for the specified event categories.
/// </summary>
/// <param name="eventCategory">A bit mask for the event categories of interest.</param>
/// <returns>A list of condition names.</returns>
public string[] QueryConditionNames(int eventCategory)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
// fetch condition names from the server.
var conditions = ((ITsCAeServer)Server).QueryConditionNames(eventCategory);
// return result.
return conditions;
}
/// <summary>
/// Returns the sub-condition names supported by the server for the specified event condition.
/// </summary>
/// <param name="conditionName">The name of the condition.</param>
/// <returns>A list of sub-condition names.</returns>
public string[] QuerySubConditionNames(string conditionName)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
// fetch sub-condition names from the server.
var subConditions = ((ITsCAeServer)Server).QuerySubConditionNames(conditionName);
// return result.
return subConditions;
}
/// <summary>
/// Returns the condition names supported by the server for the specified event source.
/// </summary>
/// <param name="sourceName">The name of the event source.</param>
/// <returns>A list of condition names.</returns>
public string[] QueryConditionNames(string sourceName)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
// fetch condition names from the server.
var conditions = ((ITsCAeServer)Server).QueryConditionNames(sourceName);
// return result.
return conditions;
}
/// <summary>
/// Returns the event attributes supported by the server for the specified event categories.
/// </summary>
/// <param name="eventCategory">A bit mask for the event categories of interest.</param>
/// <returns>A collection of event attributes.</returns>
public TsCAeAttribute[] QueryEventAttributes(int eventCategory)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
// fetch attributes from server.
var attributes = ((ITsCAeServer)Server).QueryEventAttributes(eventCategory);
// return result.
return attributes;
}
/// <summary>
/// Returns the DA item ids for a set of attribute ids belonging to events which meet the specified filter criteria.
/// </summary>
/// <param name="sourceName">The event source of interest.</param>
/// <param name="eventCategory">The id of the event category for the events of interest.</param>
/// <param name="conditionName">The name of a condition within the event category.</param>
/// <param name="subConditionName">The name of a sub-condition within a multi-state condition.</param>
/// <param name="attributeIDs">The ids of the attributes to return item ids for.</param>
/// <returns>A list of item urls for each specified attribute.</returns>
public TsCAeItemUrl[] TranslateToItemIDs(
string sourceName,
int eventCategory,
string conditionName,
string subConditionName,
int[] attributeIDs)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
var itemUrls = ((ITsCAeServer)Server).TranslateToItemIDs(
sourceName,
eventCategory,
conditionName,
subConditionName,
attributeIDs);
return itemUrls;
}
/// <summary>
/// Returns the current state information for the condition instance corresponding to the source and condition name.
/// </summary>
/// <param name="sourceName">The source name</param>
/// <param name="conditionName">A condition name for the source.</param>
/// <param name="attributeIDs">The list of attributes to return with the condition state.</param>
/// <returns>The current state of the connection.</returns>
public TsCAeCondition GetConditionState(
string sourceName,
string conditionName,
int[] attributeIDs)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
var condition = ((ITsCAeServer)Server).GetConditionState(sourceName, conditionName, attributeIDs);
return condition;
}
/// <summary>
/// Places the specified process areas into the enabled state.
/// </summary>
/// <param name="areas">A list of fully qualified area names.</param>
/// <returns>The results of the operation for each area.</returns>
public OpcResult[] EnableConditionByArea(string[] areas)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
var results = ((ITsCAeServer)Server).EnableConditionByArea(areas);
return results;
}
/// <summary>
/// Places the specified process areas into the disabled state.
/// </summary>
/// <param name="areas">A list of fully qualified area names.</param>
/// <returns>The results of the operation for each area.</returns>
public OpcResult[] DisableConditionByArea(string[] areas)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
var results = ((ITsCAeServer)Server).DisableConditionByArea(areas);
return results;
}
/// <summary>
/// Places the specified process areas into the enabled state.
/// </summary>
/// <param name="sources">A list of fully qualified source names.</param>
/// <returns>The results of the operation for each area.</returns>
public OpcResult[] EnableConditionBySource(string[] sources)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
var results = ((ITsCAeServer)Server).EnableConditionBySource(sources);
return results;
}
/// <summary>
/// Places the specified process areas into the disabled state.
/// </summary>
/// <param name="sources">A list of fully qualified source names.</param>
/// <returns>The results of the operation for each area.</returns>
public OpcResult[] DisableConditionBySource(string[] sources)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
var results = ((ITsCAeServer)Server).DisableConditionBySource(sources);
return results;
}
/// <summary>
/// Returns the enabled state for the specified process areas.
/// </summary>
/// <param name="areas">A list of fully qualified area names.</param>
public TsCAeEnabledStateResult[] GetEnableStateByArea(string[] areas)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
var results = ((ITsCAeServer)Server).GetEnableStateByArea(areas);
return results;
}
/// <summary>
/// Returns the enabled state for the specified event sources.
/// </summary>
/// <param name="sources">A list of fully qualified source names.</param>
public TsCAeEnabledStateResult[] GetEnableStateBySource(string[] sources)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
var results = ((ITsCAeServer)Server).GetEnableStateBySource(sources);
return results;
}
/// <summary>
/// Used to acknowledge one or more conditions in the event server.
/// </summary>
/// <param name="acknowledgmentId">The identifier for who is acknowledging the condition.</param>
/// <param name="comment">A comment associated with the acknowledgment.</param>
/// <param name="conditions">The conditions being acknowledged.</param>
/// <returns>A list of result id indicating whether each condition was successfully acknowledged.</returns>
public OpcResult[] AcknowledgeCondition(
string acknowledgmentId,
string comment,
TsCAeEventAcknowledgement[] conditions)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
return ((ITsCAeServer)Server).AcknowledgeCondition(acknowledgmentId, comment, conditions);
}
/// <summary>
/// Browses for all children of the specified area that meet the filter criteria.
/// </summary>
/// <param name="areaId">The full-qualified id for the area.</param>
/// <param name="browseType">The type of children to return.</param>
/// <param name="browseFilter">The expression used to filter the names of children returned.</param>
/// <returns>The set of elements that meet the filter criteria.</returns>
public TsCAeBrowseElement[] Browse(
string areaId,
TsCAeBrowseType browseType,
string browseFilter)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
return ((ITsCAeServer)Server).Browse(areaId, browseType, browseFilter);
}
/// <summary>
/// Browses for all children of the specified area that meet the filter criteria.
/// </summary>
/// <param name="areaId">The full-qualified id for the area.</param>
/// <param name="browseType">The type of children to return.</param>
/// <param name="browseFilter">The expression used to filter the names of children returned.</param>
/// <param name="maxElements">The maximum number of elements to return.</param>
/// <param name="position">The object used to continue the browse if the number nodes exceeds the maximum specified.</param>
/// <returns>The set of elements that meet the filter criteria.</returns>
public TsCAeBrowseElement[] Browse(
string areaId,
TsCAeBrowseType browseType,
string browseFilter,
int maxElements,
out IOpcBrowsePosition position)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
return ((ITsCAeServer)Server).Browse(areaId, browseType, browseFilter, maxElements, out position);
}
/// <summary>
/// Continues browsing the server's address space at the specified position.
/// </summary>
/// <param name="maxElements">The maximum number of elements to return.</param>
/// <param name="position">The position object used to continue a browse operation.</param>
/// <returns>The set of elements that meet the filter criteria.</returns>
public TsCAeBrowseElement[] BrowseNext(int maxElements, ref IOpcBrowsePosition position)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (Server == null) throw new NotConnectedException();
return ((ITsCAeServer)Server).BrowseNext(maxElements, ref position);
}
#endregion
#region ISerializable Members
/// <summary>
/// Serializes a server into a stream.
/// </summary>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(Names.Count, subscriptions_.Count);
for (var ii = 0; ii < subscriptions_.Count; ii++)
{
info.AddValue(Names.Subscription + ii, subscriptions_[ii]);
}
}
#endregion
#region Private Methods
/// <summary>
/// Called when a subscription object is disposed.
/// </summary>
/// <param name="subscription"></param>
internal void SubscriptionDisposed(TsCAeSubscription subscription)
{
if (!disposing_)
{
subscriptions_.Remove(subscription);
}
}
/// <summary>
/// Establishes a subscription based on the template provided.
/// </summary>
private TsCAeSubscription EstablishSubscription(TsCAeSubscription template)
{
ITsCAeSubscription remoteServer = null;
try
{
// create remote object.
remoteServer = ((ITsCAeServer)Server).CreateSubscription(template.State);
if (remoteServer == null)
{
return null;
}
// create wrapper.
var subscription = new TsCAeSubscription(this, remoteServer, template.State);
// set filters.
subscription.SetFilters(template.Filters);
// set attributes.
var enumerator = template.Attributes.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Key != null)
subscription.SelectReturnedAttributes(
(int)enumerator.Key,
((TsCAeSubscription.AttributeCollection)enumerator.Value).ToArray());
}
// return new subscription
return subscription;
}
catch
{
if (remoteServer != null)
{
remoteServer.Dispose();
}
}
// return null.
return null;
}
#endregion
}
}

View File

@@ -0,0 +1,68 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Current Status of an OPC AE server
/// </summary>
public enum TsCAeServerState
{
/// <summary>
/// The server state is not known.
/// </summary>
Unknown,
/// <summary>
/// The server is running normally. This is the usual state for a server
/// </summary>
Running,
/// <summary>
/// A vendor specific fatal error has occurred within the server. The server is no longer functioning. The recovery procedure from this situation is vendor specific. An error code of E_FAIL should generally be returned from any other server method.
/// </summary>
Failed,
/// <summary>
/// The server is running but has no configuration information loaded and thus cannot function normally. Note this state implies that the server needs configuration information in order to function. Servers which do not require configuration information should not return this state.
/// </summary>
NoConfig,
/// <summary>
/// The server has been temporarily suspended via some vendor specific method and is not getting or sending data. Note that Quality will be returned as OPC_QUALITY_OUT_OF_SERVICE.
/// </summary>
Suspended,
/// <summary>
/// The server is in Test Mode. The outputs are disconnected from the real hardware but the server will otherwise behave normally. Inputs may be real or may be simulated depending on the vendor implementation. Quality will generally be returned normally.
/// </summary>
Test,
/// <summary>
/// The server is in Test Mode. The outputs are disconnected from the real hardware but the server will otherwise behave normally. Inputs may be real or may be simulated depending on the vendor implementation. Quality will generally be returned normally.
/// </summary>
CommFault
}
}

View File

@@ -0,0 +1,70 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Defines masks to be used when modifying the subscription or item state.
/// </summary>
[Flags]
public enum TsCAeStateMask
{
/// <summary>
/// A name assigned to subscription.
/// </summary>
Name = 0x0001,
/// <summary>
/// The client assigned handle for the item or subscription.
/// </summary>
ClientHandle = 0x0002,
/// <summary>
/// Whether the subscription is active.
/// </summary>
Active = 0x0004,
/// <summary>
/// The maximum rate at which the server send event notifications.
/// </summary>
BufferTime = 0x0008,
/// <summary>
/// The requested maximum number of events that will be sent in a single callback.
/// </summary>
MaxSize = 0x0010,
/// <summary>
/// The maximum period between updates sent to the client.
/// </summary>
KeepAlive = 0x0020,
/// <summary>
/// All fields are valid.
/// </summary>
All = 0xFFFF
}
}

View File

@@ -0,0 +1,83 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The description of an item sub-condition supported by the server.
/// </summary>
[Serializable]
public class TsCAeSubCondition : ICloneable
{
#region Fields
private int severity_ = 1;
#endregion
#region Properties
/// <summary>
/// The name assigned to the sub-condition.
/// </summary>
public string Name { get; set; }
/// <summary>
/// A server-specific expression which defines the sub-state represented by the sub-condition.
/// </summary>
public string Definition { get; set; }
/// <summary>
/// The severity of any event notifications generated on behalf of this sub-condition.
/// </summary>
public int Severity
{
get => severity_;
set => severity_ = value;
}
/// <summary>
/// The text string to be included in any event notification generated on behalf of this sub-condition.
/// </summary>
public string Description { get; set; }
#endregion
#region Helper Methods
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name;
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a shallow copy of the object.
/// </summary>
public virtual object Clone() { return MemberwiseClone(); }
#endregion
}
}

View File

@@ -0,0 +1,610 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using System.Runtime.Serialization;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// An in-process object which provides access to AE subscription objects.
/// </summary>
[Serializable]
public class TsCAeSubscription : ITsCAeSubscription, ISerializable, ICloneable
{
#region CategoryCollection Class
/// <summary>
/// Contains a read-only collection category ids.
/// </summary>
public class CategoryCollection : OpcReadOnlyCollection
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Creates an empty collection.
/// </summary>
internal CategoryCollection() : base(new int[0]) { }
/// <summary>
/// Creates a collection containing the list of category ids.
/// </summary>
internal CategoryCollection(int[] categoryIDs) : base(categoryIDs) { }
#endregion
#region Public Methods
/// <summary>
/// An indexer for the collection.
/// </summary>
public new int this[int index] => (int)Array.GetValue(index);
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new int[] ToArray()
{
return (int[])OpcConvert.Clone(Array);
}
#endregion
}
#endregion
#region StringCollection Class
/// <summary>
/// Contains a read-only collection of strings.
/// </summary>
public class StringCollection : OpcReadOnlyCollection
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Creates an empty collection.
/// </summary>
internal StringCollection() : base(new string[0]) { }
/// <summary>
/// Creates a collection containing the specified strings.
/// </summary>
internal StringCollection(string[] strings) : base(strings) { }
#endregion
#region Public Methods
/// <summary>
/// An indexer for the collection.
/// </summary>
public new string this[int index] => (string)Array.GetValue(index);
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new string[] ToArray()
{
return (string[])OpcConvert.Clone(Array);
}
#endregion
}
#endregion
#region AttributeDictionary Class
/// <summary>
/// Contains a read-only dictionary of attribute lists indexed by category id.
/// </summary>
[Serializable]
public class AttributeDictionary : OpcReadOnlyDictionary
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Creates an empty collection.
/// </summary>
internal AttributeDictionary() : base(null) { }
/// <summary>
/// Constructs an dictionary from a set of category ids.
/// </summary>
internal AttributeDictionary(Hashtable dictionary) : base(dictionary) { }
#endregion
#region Public Methods
/// <summary>
/// Gets or sets the attribute collection for the specified category.
/// </summary>
public AttributeCollection this[int categoryId] => (AttributeCollection)base[categoryId];
/// <summary>
/// Adds or replaces the set of attributes associated with the category.
/// </summary>
internal void Update(int categoryId, int[] attributeIDs)
{
Dictionary[categoryId] = new AttributeCollection(attributeIDs);
}
#endregion
#region ISerializable Members
/// <summary>
/// Constructs an object by deserializing it from a stream.
/// </summary>
protected AttributeDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endregion
}
#endregion
#region AttributeCollection Class
/// <summary>
/// Contains a read-only collection attribute ids.
/// </summary>
[Serializable]
public class AttributeCollection : OpcReadOnlyCollection
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Creates an empty collection.
/// </summary>
internal AttributeCollection() : base(new int[0]) { }
/// <summary>
/// Creates a collection containing the specified attribute ids.
/// </summary>
internal AttributeCollection(int[] attributeIDs) : base(attributeIDs) { }
#endregion
#region Public Methods
/// <summary>
/// An indexer for the collection.
/// </summary>
public new int this[int index] => (int)Array.GetValue(index);
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new int[] ToArray()
{
return (int[])OpcConvert.Clone(Array);
}
#endregion
#region ISerializable Members
/// <summary>
/// Constructs an object by deserializing it from a stream.
/// </summary>
protected AttributeCollection(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endregion
}
#endregion
#region Names Class
/// <summary>
/// A set of names for fields used in serialization.
/// </summary>
private class Names
{
internal const string State = "ST";
internal const string Filters = "FT";
internal const string Attributes = "AT";
}
#endregion
#region Fields
private bool disposed_;
private TsCAeServer server_;
private ITsCAeSubscription subscription_;
// state
private TsCAeSubscriptionState state_;
private string name_;
// filters
private TsCAeSubscriptionFilters subscriptionFilters_ = new TsCAeSubscriptionFilters();
private CategoryCollection categories_ = new CategoryCollection();
private StringCollection areas_ = new StringCollection();
private StringCollection sources_ = new StringCollection();
// returned attributes
private AttributeDictionary attributes_ = new AttributeDictionary();
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes object with default values.
/// </summary>
public TsCAeSubscription(TsCAeServer server, ITsCAeSubscription subscription, TsCAeSubscriptionState state)
{
server_ = server ?? throw new ArgumentNullException(nameof(server));
subscription_ = subscription ?? throw new ArgumentNullException(nameof(subscription));
state_ = (TsCAeSubscriptionState)state.Clone();
name_ = state.Name;
}
/// <summary>
/// The finalizer implementation.
/// </summary>
~TsCAeSubscription()
{
Dispose(false);
}
/// <summary>
///
/// </summary>
public virtual void Dispose()
{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing">If true managed and unmanaged resources can be disposed. If false only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!disposed_)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
if (subscription_ != null)
{
server_.SubscriptionDisposed(this);
subscription_.Dispose();
}
}
// Release unmanaged resources. If disposing is false,
// only the following code is executed.
}
disposed_ = true;
}
#endregion
#region Properties
/// <summary>
/// The server that the subscription object belongs to.
/// </summary>
public TsCAeServer Server => server_;
/// <summary>
/// A descriptive name for the subscription.
/// </summary>
public string Name => state_.Name;
/// <summary>
/// A unique identifier for the subscription assigned by the client.
/// </summary>
public object ClientHandle => state_.ClientHandle;
/// <summary>
/// Whether the subscription is monitoring for events to send to the client.
/// </summary>
public bool Active => state_.Active;
/// <summary>
/// The maximum rate at which the server send event notifications.
/// The <see cref="ApplicationInstance.TimeAsUtc">ApplicationInstance.TimeAsUtc</see> property defines
/// the time format (UTC or local time).
/// </summary>
public int BufferTime => state_.BufferTime;
/// <summary>
/// The requested maximum number of events that will be sent in a single callback.
/// </summary>
public int MaxSize => state_.MaxSize;
/// <summary>
/// The maximum period between updates sent to the client.
/// </summary>
public int KeepAlive => state_.KeepAlive;
/// <summary>
/// A mask indicating which event types should be sent to the client.
/// </summary>
public int EventTypes => subscriptionFilters_.EventTypes;
/// <summary>
/// The highest severity for the events that should be sent to the client.
/// </summary>
// ReSharper disable once UnusedMember.Global
public int HighSeverity => subscriptionFilters_.HighSeverity;
/// <summary>
/// The lowest severity for the events that should be sent to the client.
/// </summary>
// ReSharper disable once UnusedMember.Global
public int LowSeverity => subscriptionFilters_.LowSeverity;
/// <summary>
/// The event category ids monitored by this subscription.
/// </summary>
public CategoryCollection Categories => categories_;
/// <summary>
/// A list of full-qualified ids for process areas of interest - only events or conditions in these areas will be reported.
/// </summary>
public StringCollection Areas => areas_;
/// <summary>
/// A list of full-qualified ids for sources of interest - only events or conditions from these sources will be reported.
/// </summary>
public StringCollection Sources => sources_;
/// <summary>
/// The list of attributes returned for each event category.
/// </summary>
public AttributeDictionary Attributes => attributes_;
#endregion
#region Public Methods
/// <summary>
/// Returns a writable copy of the current attributes.
/// </summary>
public TsCAeAttributeDictionary GetAttributes()
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
var attributes = new TsCAeAttributeDictionary();
var enumerator = attributes_.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Key != null)
{
var categoryId = (int)enumerator.Key;
var attributeIDs = (AttributeCollection)enumerator.Value;
attributes.Add(categoryId, attributeIDs.ToArray());
}
}
return attributes;
}
#endregion
#region ISerializable Members
/// <summary>
/// Constructs a server by de-serializing its OpcUrl from the stream.
/// </summary>
protected TsCAeSubscription(SerializationInfo info, StreamingContext context)
{
state_ = (TsCAeSubscriptionState)info.GetValue(Names.State, typeof(TsCAeSubscriptionState));
subscriptionFilters_ = (TsCAeSubscriptionFilters)info.GetValue(Names.Filters, typeof(TsCAeSubscriptionFilters));
attributes_ = (AttributeDictionary)info.GetValue(Names.Attributes, typeof(AttributeDictionary));
name_ = state_.Name;
categories_ = new CategoryCollection(subscriptionFilters_.Categories.ToArray());
areas_ = new StringCollection(subscriptionFilters_.Areas.ToArray());
sources_ = new StringCollection(subscriptionFilters_.Sources.ToArray());
}
/// <summary>
/// Serializes a server into a stream.
/// </summary>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(Names.State, state_);
info.AddValue(Names.Filters, subscriptionFilters_);
info.AddValue(Names.Attributes, attributes_);
}
#endregion
#region ICloneable Members
/// <summary>
/// Returns an unconnected copy of the subscription with the same items.
/// </summary>
public virtual object Clone()
{
// do a memberwise clone.
var clone = (TsCAeSubscription)MemberwiseClone();
/*
// place clone in disconnected state.
clone.server = null;
clone.subscription = null;
clone.state = (SubscriptionState)state.Clone();
// clear server handles.
clone.state.ServerHandle = null;
// always make cloned subscriptions inactive.
clone.state.Active = false;
// clone items.
if (clone.items != null)
{
ArrayList items = new ArrayList();
foreach (Item item in clone.items)
{
items.Add(item.Clone());
}
clone.items = (Item[])items.ToArray(typeof(Item));
}
*/
// return clone.
return clone;
}
#endregion
#region ISubscription Members
/// <summary>
/// An event to receive data change updates.
/// </summary>
public event TsCAeDataChangedEventHandler DataChangedEvent
{
add => subscription_.DataChangedEvent += value;
remove => subscription_.DataChangedEvent -= value;
}
/// <summary>
/// Returns the current state of the subscription.
/// </summary>
/// <returns>The current state of the subscription.</returns>
public TsCAeSubscriptionState GetState()
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (subscription_ == null) throw new NotConnectedException();
state_ = subscription_.GetState();
state_.Name = name_;
return (TsCAeSubscriptionState)state_.Clone();
}
/// <summary>
/// Changes the state of a subscription.
/// </summary>
/// <param name="masks">A bit mask that indicates which elements of the subscription state are changing.</param>
/// <param name="state">The new subscription state.</param>
/// <returns>The actual subscription state after applying the changes.</returns>
public TsCAeSubscriptionState ModifyState(int masks, TsCAeSubscriptionState state)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (subscription_ == null) throw new NotConnectedException();
state_ = subscription_.ModifyState(masks, state);
if ((masks & (int)TsCAeStateMask.Name) != 0)
{
state_.Name = name_ = state.Name;
}
else
{
state_.Name = name_;
}
return (TsCAeSubscriptionState)state_.Clone();
}
/// <summary>
/// Returns the current filters for the subscription.
/// </summary>
/// <returns>The current filters for the subscription.</returns>
public TsCAeSubscriptionFilters GetFilters()
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (subscription_ == null) throw new NotConnectedException();
subscriptionFilters_ = subscription_.GetFilters();
categories_ = new CategoryCollection(subscriptionFilters_.Categories.ToArray());
areas_ = new StringCollection(subscriptionFilters_.Areas.ToArray());
sources_ = new StringCollection(subscriptionFilters_.Sources.ToArray());
return (TsCAeSubscriptionFilters)subscriptionFilters_.Clone();
}
/// <summary>
/// Sets the current filters for the subscription.
/// </summary>
/// <param name="filters">The new filters to use for the subscription.</param>
public void SetFilters(TsCAeSubscriptionFilters filters)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (subscription_ == null) throw new NotConnectedException();
subscription_.SetFilters(filters);
GetFilters();
}
/// <summary>
/// Returns the set of attributes to return with event notifications.
/// </summary>
/// <returns>The set of attributes to returned with event notifications.</returns>
public int[] GetReturnedAttributes(int eventCategory)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (subscription_ == null) throw new NotConnectedException();
var attributeIDs = subscription_.GetReturnedAttributes(eventCategory);
attributes_.Update(eventCategory, (int[])OpcConvert.Clone(attributeIDs));
return attributeIDs;
}
/// <summary>
/// Selects the set of attributes to return with event notifications.
/// </summary>
/// <param name="eventCategory">The specific event category for which the attributes apply.</param>
/// <param name="attributeIDs">The list of attribute ids to return.</param>
public void SelectReturnedAttributes(int eventCategory, int[] attributeIDs)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (subscription_ == null) throw new NotConnectedException();
subscription_.SelectReturnedAttributes(eventCategory, attributeIDs);
attributes_.Update(eventCategory, (int[])OpcConvert.Clone(attributeIDs));
}
/// <summary>
/// Force a refresh for all active conditions and inactive, unacknowledged conditions whose event notifications match the filter of the event subscription.
/// </summary>
public void Refresh()
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (subscription_ == null) throw new NotConnectedException();
subscription_.Refresh();
}
/// <summary>
/// Cancels an outstanding refresh request.
/// </summary>
public void CancelRefresh()
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.AlarmsConditions);
if (subscription_ == null) throw new NotConnectedException();
subscription_.CancelRefresh();
}
#endregion
#region Internal Properties
/// <summary>
/// The current state.
/// </summary>
internal TsCAeSubscriptionState State => state_;
/// <summary>
/// The current filters.
/// </summary>
internal TsCAeSubscriptionFilters Filters => subscriptionFilters_;
#endregion
}
}

View File

@@ -0,0 +1,232 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Runtime.Serialization;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Describes the event filters for a subscription.
/// </summary>
[Serializable]
public class TsCAeSubscriptionFilters : ICloneable, ISerializable
{
#region CategoryCollection Class
/// <summary>
/// Contains a writable collection category ids.
/// </summary>
[Serializable]
public class CategoryCollection : OpcWriteableCollection
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Creates an empty collection.
/// </summary>
internal CategoryCollection() : base(null, typeof(int)) { }
#region ISerializable Members
/// <summary>
/// Constructs an object by deserializing it from a stream.
/// </summary>
protected CategoryCollection(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endregion
#endregion
#region Public Methods
/// <summary>
/// An indexer for the collection.
/// </summary>
public new int this[int index] => (int)Array[index];
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new int[] ToArray()
{
return (int[])Array.ToArray(typeof(int));
}
#endregion
}
#endregion
#region StringCollection Class
/// <summary>
/// Contains a writable collection of strings.
/// </summary>
[Serializable]
public class StringCollection : OpcWriteableCollection
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Creates an empty collection.
/// </summary>
internal StringCollection() : base(null, typeof(string)) { }
#endregion
#region Public Methods
/// <summary>
/// An indexer for the collection.
/// </summary>
public new string this[int index] => (string)Array[index];
/// <summary>
/// Returns a copy of the collection as an array.
/// </summary>
public new string[] ToArray()
{
return (string[])Array.ToArray(typeof(string));
}
#endregion
#region ISerializable Members
/// <summary>
/// Constructs an object by deserializing it from a stream.
/// </summary>
protected StringCollection(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endregion
}
#endregion
#region Names Class
/// <summary>
/// A set of names for fields used in serialization.
/// </summary>
private class Names
{
internal const string EventTypes = "ET";
internal const string Categories = "CT";
internal const string HighSeverity = "HS";
internal const string LowSeverity = "LS";
internal const string Areas = "AR";
internal const string Sources = "SR";
}
#endregion
#region Fields
private int eventTypes_ = (int)TsCAeEventType.All;
private CategoryCollection categories_ = new CategoryCollection();
private int highSeverity_ = 1000;
private int lowSeverity_ = 1;
private StringCollection areas_ = new StringCollection();
private StringCollection sources_ = new StringCollection();
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes object with default values.
/// </summary>
public TsCAeSubscriptionFilters() { }
/// <summary>
/// Constructs a server by de-serializing its OpcUrl from the stream.
/// </summary>
protected TsCAeSubscriptionFilters(SerializationInfo info, StreamingContext context)
{
eventTypes_ = (int)info.GetValue(Names.EventTypes, typeof(int));
categories_ = (CategoryCollection)info.GetValue(Names.Categories, typeof(CategoryCollection));
highSeverity_ = (int)info.GetValue(Names.HighSeverity, typeof(int));
lowSeverity_ = (int)info.GetValue(Names.LowSeverity, typeof(int));
areas_ = (StringCollection)info.GetValue(Names.Areas, typeof(StringCollection));
sources_ = (StringCollection)info.GetValue(Names.Sources, typeof(StringCollection));
}
#endregion
#region Properties
/// <summary>
/// A mask indicating which event types should be sent to the client.
/// </summary>
public int EventTypes
{
get => eventTypes_;
set => eventTypes_ = value;
}
/// <summary>
/// The highest severity for the events that should be sent to the client.
/// </summary>
public int HighSeverity
{
get => highSeverity_;
set => highSeverity_ = value;
}
/// <summary>
/// The lowest severity for the events that should be sent to the client.
/// </summary>
public int LowSeverity
{
get => lowSeverity_;
set => lowSeverity_ = value;
}
/// <summary>
/// The category ids for the events that should be sent to the client.
/// </summary>
public CategoryCollection Categories => categories_;
/// <summary>
/// A list of full-qualified ids for process areas of interest - only events or conditions in these areas will be reported.
/// </summary>
public StringCollection Areas => areas_;
/// <summary>
/// A list of full-qualified ids for sources of interest - only events or conditions from these sources will be reported.
/// </summary>
public StringCollection Sources => sources_;
#endregion
#region ISerializable Members
/// <summary>
/// Serializes a server into a stream.
/// </summary>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(Names.EventTypes, eventTypes_);
info.AddValue(Names.Categories, categories_);
info.AddValue(Names.HighSeverity, highSeverity_);
info.AddValue(Names.LowSeverity, lowSeverity_);
info.AddValue(Names.Areas, areas_);
info.AddValue(Names.Sources, sources_);
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
var filters = (TsCAeSubscriptionFilters)MemberwiseClone();
filters.categories_ = (CategoryCollection)categories_.Clone();
filters.areas_ = (StringCollection)areas_.Clone();
filters.sources_ = (StringCollection)sources_.Clone();
return filters;
}
#endregion
}
}

View File

@@ -0,0 +1,88 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Describes the state of a subscription.
/// </summary>
[Serializable]
public class TsCAeSubscriptionState : ICloneable
{
#region Fields
private bool active_ = true;
#endregion
#region Constructors, Destructor, Initialization
#endregion
#region Properties
/// <summary>
/// A descriptive name for the subscription.
/// </summary>
public string Name { get; set; }
/// <summary>
/// A unique identifier for the subscription assigned by the client.
/// </summary>
public object ClientHandle { get; set; }
/// <summary>
/// Whether the subscription is monitoring for events to send to the client.
/// </summary>
public bool Active
{
get => active_;
set => active_ = value;
}
/// <summary>
/// The maximum rate at which the server send event notifications.
/// </summary>
public int BufferTime { get; set; }
/// <summary>
/// The requested maximum number of events that will be sent in a single callback.
/// </summary>
public int MaxSize { get; set; }
/// <summary>
/// The maximum period between updates sent to the client.
/// </summary>
public int KeepAlive { get; set; }
#endregion
#region ICloneable Members
/// <summary>
/// Creates a shallow copy of the object.
/// </summary>
public virtual object Clone()
{
return MemberwiseClone();
}
#endregion
}
}

View File

@@ -0,0 +1,66 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using Technosoftware.DaAeHdaClient.Utilities;
#endregion
namespace Technosoftware.DaAeHdaClient
{
/// <summary>
/// Manages the license to enable the different product versions.
/// </summary>
public partial class ApplicationInstance
{
#region Properties
/// <summary>
/// This flag suppresses the conversion to local time done during marshalling.
/// </summary>
public static bool TimeAsUtc { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Gets the log file directory and ensures it is writable.
/// </summary>
public static string GetLogFileDirectory()
{
return ConfigUtils.GetLogFileDirectory();
}
/// <summary>
/// Enable the trace.
/// </summary>
/// <param name="path">The path to use.</param>
/// <param name="filename">The filename.</param>
public static void EnableTrace(string path, string filename)
{
ConfigUtils.EnableTrace(path, filename);
}
#endregion
#region Internal Fields
internal static bool InitializeSecurityCalled = false;
#endregion
}
}

View File

@@ -0,0 +1,715 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using System.Xml;
using System.IO;
using Technosoftware.DaAeHdaClient.Da;
#endregion
namespace Technosoftware.DaAeHdaClient.Cpx
{
/// <summary>
/// A class that contains complex data related properties for an item.
/// </summary>
public class TsCCpxComplexItem : OpcItem
{
///////////////////////////////////////////////////////////////////////
#region Constants
/// <summary>
/// The reserved name for complex data branch in the server namespace.
/// </summary>
public const string CPX_BRANCH = "CPX";
/// <summary>
/// The reserved name for the data filters branch in the CPX namespace.
/// </summary>
public const string CPX_DATA_FILTERS = "DataFilters";
/// <summary>
/// The set of all complex data item properties.
/// </summary>
public static readonly TsDaPropertyID[] CPX_PROPERTIES = new TsDaPropertyID[]
{
TsDaProperty.TYPE_SYSTEM_ID,
TsDaProperty.DICTIONARY_ID,
TsDaProperty.TYPE_ID,
TsDaProperty.UNCONVERTED_ITEM_ID,
TsDaProperty.UNFILTERED_ITEM_ID,
TsDaProperty.DATA_FILTER_VALUE
};
#endregion
///////////////////////////////////////////////////////////////////////
#region Fields
private string _typeSystemID;
private string _dictionaryID;
private string _typeID;
private OpcItem _dictionaryItemID;
private OpcItem _typeItemID;
private OpcItem _unconvertedItemID;
private OpcItem _unfilteredItemID;
private OpcItem _filterItem;
#endregion
///////////////////////////////////////////////////////////////////////
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with the default values.
/// </summary>
public TsCCpxComplexItem() { }
/// <summary>
/// Initializes the object from an item identifier.
/// </summary>
/// <param name="itemID">The item id.</param>
public TsCCpxComplexItem(OpcItem itemID)
{
ItemPath = itemID.ItemPath;
ItemName = itemID.ItemName;
}
#endregion
///////////////////////////////////////////////////////////////////////
#region Properties
/// <summary>
/// The name of the item in the server address space.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// The type system id for the complex item.
/// </summary>
public string TypeSystemID => _typeSystemID;
/// <summary>
/// The dictionary id for the complex item.
/// </summary>
public string DictionaryID => _dictionaryID;
/// <summary>
/// The type id for the complex item.
/// </summary>
public string TypeID => _typeID;
/// <summary>
/// The id of the item containing the dictionary for the item.
/// </summary>
public OpcItem DictionaryItemID => _dictionaryItemID;
/// <summary>
/// The id of the item containing the type description for the item.
/// </summary>
public OpcItem TypeItemID => _typeItemID;
/// <summary>
/// The id of the unconverted version of the item. Only valid for items which apply type conversions to the item.
/// </summary>
public OpcItem UnconvertedItemID => _unconvertedItemID;
/// <summary>
/// The id of the unfiltered version of the item. Only valid for items apply data filters to the item.
/// </summary>
public OpcItem UnfilteredItemID => _unfilteredItemID;
/// <summary>
/// The item used to create new data filters for the complex data item (null is item does not support it).
/// </summary>
public OpcItem DataFilterItem => _filterItem;
/// <summary>
/// The current data filter value. Only valid for items apply data filters to the item.
/// </summary>
public string DataFilterValue { get; set; }
#endregion
///////////////////////////////////////////////////////////////////////
#region Public Methods
/// <summary>
/// Returns an appropriate string representation of the object.
/// </summary>
public override string ToString()
{
if (Name != null || Name.Length != 0)
{
return Name;
}
return ItemName;
}
/// <summary>
/// Returns the root complex data item for the object.
/// </summary>
public TsCCpxComplexItem GetRootItem()
{
if (_unconvertedItemID != null)
{
return TsCCpxComplexTypeCache.GetComplexItem(_unconvertedItemID);
}
if (_unfilteredItemID != null)
{
return TsCCpxComplexTypeCache.GetComplexItem(_unfilteredItemID);
}
return this;
}
/// <summary>
/// Reads the current complex data item properties from the server.
/// </summary>
/// <param name="server">The server object</param>
public void Update(TsCDaServer server)
{
// clear the existing state.
Clear();
// check if the item supports any of the complex data properties.
var results = server.GetProperties(
new OpcItem[] { this },
CPX_PROPERTIES,
true);
// unexpected return value.
if (results == null || results.Length != 1)
{
throw new OpcResultException(new OpcResult((int)OpcResult.E_FAIL.Code, OpcResult.FuncCallType.SysFuncCall, null), "Unexpected results returned from server.");
}
// update object.
if (!Init((TsCDaItemProperty[])results[0].ToArray(typeof(TsCDaItemProperty))))
{
throw new OpcResultException(new OpcResult((int)OpcResult.E_INVALIDARG.Code, OpcResult.FuncCallType.SysFuncCall, null), "Not a valid complex item.");
}
// check if data filters are suppported for the item.
GetDataFilterItem(server);
}
/// <summary>
/// Fetches the set of type conversions from the server.
/// </summary>
/// <param name="server">The server object</param>
public TsCCpxComplexItem[] GetTypeConversions(TsCDaServer server)
{
// only the root item can have type conversions.
if (_unconvertedItemID != null || _unfilteredItemID != null)
{
return null;
}
TsCDaBrowsePosition position = null;
try
{
// look for the 'CPX' branch.
var filters = new TsCDaBrowseFilters { ElementNameFilter = CPX_BRANCH, BrowseFilter = TsCDaBrowseFilter.Branch, ReturnAllProperties = false, PropertyIDs = null, ReturnPropertyValues = false };
var elements = server.Browse(this, filters, out position);
// nothing found.
if (elements == null || elements.Length == 0)
{
return null;
}
// release the browse position object.
if (position != null)
{
position.Dispose();
position = null;
}
// browse for type conversions.
var itemID = new OpcItem(elements[0].ItemPath, elements[0].ItemName);
filters.ElementNameFilter = null;
filters.BrowseFilter = TsCDaBrowseFilter.Item;
filters.ReturnAllProperties = false;
filters.PropertyIDs = CPX_PROPERTIES;
filters.ReturnPropertyValues = true;
elements = server.Browse(itemID, filters, out position);
// nothing found.
if (elements == null || elements.Length == 0)
{
return new TsCCpxComplexItem[0];
}
// contruct an array of complex data items for each available conversion.
var conversions = new ArrayList(elements.Length);
Array.ForEach(elements, element =>
{
if (element.Name != CPX_DATA_FILTERS)
{
var item = new TsCCpxComplexItem();
if (item.Init(element))
{
// check if data filters supported for type conversion.
item.GetDataFilterItem(server);
conversions.Add(item);
}
}
});
// return the set of available conversions.
return (TsCCpxComplexItem[])conversions.ToArray(typeof(TsCCpxComplexItem));
}
finally
{
if (position != null)
{
position.Dispose();
position = null;
}
}
}
/// <summary>
/// Fetches the set of data filters from the server.
/// </summary>
/// <param name="server">The server object</param>
public TsCCpxComplexItem[] GetDataFilters(TsCDaServer server)
{
// not a valid operation for data filter items.
if (_unfilteredItemID != null)
{
return null;
}
// data filters not supported by the item.
if (_filterItem == null)
{
return null;
}
TsCDaBrowsePosition position = null;
try
{
// browse any existing filter instances.
var filters = new TsCDaBrowseFilters { ElementNameFilter = null, BrowseFilter = TsCDaBrowseFilter.Item, ReturnAllProperties = false, PropertyIDs = CPX_PROPERTIES, ReturnPropertyValues = true };
var elements = server.Browse(_filterItem, filters, out position);
// nothing found.
if (elements == null || elements.Length == 0)
{
return new TsCCpxComplexItem[0];
}
// contruct an array of complex data items for each available data filter.
var dataFilters = new ArrayList(elements.Length);
Array.ForEach(elements, element =>
{
var item = new TsCCpxComplexItem();
if (item.Init(element))
dataFilters.Add(item);
});
// return the set of available data filters.
return (TsCCpxComplexItem[])dataFilters.ToArray(typeof(TsCCpxComplexItem));
}
finally
{
if (position != null)
{
position.Dispose();
position = null;
}
}
}
/// <summary>
/// Creates a new data filter.
/// </summary>
/// <param name="server">The server object</param>
/// <param name="filterName">The name of the filter</param>
/// <param name="filterValue">The value of the filter</param>
public TsCCpxComplexItem CreateDataFilter(TsCDaServer server, string filterName, string filterValue)
{
// not a valid operation for data filter items.
if (_unfilteredItemID != null)
{
return null;
}
// data filters not supported by the item.
if (_filterItem == null)
{
return null;
}
TsCDaBrowsePosition position = null;
try
{
// write the desired filter to the server.
var item = new TsCDaItemValue(_filterItem);
// create the filter parameters document.
using (var ostrm = new StringWriter())
{
using (var writer = new XmlTextWriter(ostrm))
{
writer.WriteStartElement("DataFilters");
writer.WriteAttributeString("Name", filterName);
writer.WriteString(filterValue);
writer.WriteEndElement();
writer.Close();
}
// create the value to write.
item.Value = ostrm.ToString();
}
item.Quality = TsCDaQuality.Bad;
item.QualitySpecified = false;
item.Timestamp = DateTime.MinValue;
item.TimestampSpecified = false;
// write the value.
var result = server.Write(new TsCDaItemValue[] { item });
if (result == null || result.Length == 0)
{
throw new OpcResultException(new OpcResult((int)OpcResult.E_FAIL.Code, OpcResult.FuncCallType.SysFuncCall, null), "Unexpected results returned from server.");
}
if (result[0].Result.Failed())
{
throw new OpcResultException(new OpcResult((int)OpcResult.Cpx.E_FILTER_ERROR.Code, OpcResult.FuncCallType.SysFuncCall, null), "Could not create new data filter.");
}
// browse for new data filter item.
var filters = new TsCDaBrowseFilters { ElementNameFilter = filterName, BrowseFilter = TsCDaBrowseFilter.Item, ReturnAllProperties = false, PropertyIDs = CPX_PROPERTIES, ReturnPropertyValues = true };
var elements = server.Browse(_filterItem, filters, out position);
// nothing found.
if (elements == null || elements.Length == 0)
{
throw new OpcResultException(new OpcResult((int)OpcResult.Cpx.E_FILTER_ERROR.Code, OpcResult.FuncCallType.SysFuncCall, null), "Could not browse to new data filter.");
}
var filterItem = new TsCCpxComplexItem();
if (!filterItem.Init(elements[0]))
{
throw new OpcResultException(new OpcResult((int)OpcResult.Cpx.E_FILTER_ERROR.Code, OpcResult.FuncCallType.SysFuncCall, null), "Could not initialize to new data filter.");
}
// return the new data filter.
return filterItem;
}
finally
{
if (position != null)
{
position.Dispose();
}
}
}
/// <summary>
/// Updates a data filter.
/// </summary>
/// <param name="server">The server object</param>
/// <param name="filterValue">The value of the filter</param>
public void UpdateDataFilter(TsCDaServer server, string filterValue)
{
// not a valid operation for non data filter items.
if (_unfilteredItemID == null)
{
throw new OpcResultException(new OpcResult((int)OpcResult.Cpx.E_FILTER_ERROR.Code, OpcResult.FuncCallType.SysFuncCall, null), "Cannot update the data filter for this item.");
}
// create the value to write.
var item = new TsCDaItemValue(this) { Value = filterValue, Quality = TsCDaQuality.Bad, QualitySpecified = false, Timestamp = DateTime.MinValue, TimestampSpecified = false };
// write the value.
var result = server.Write(new TsCDaItemValue[] { item });
if (result == null || result.Length == 0)
{
throw new OpcResultException(new OpcResult((int)OpcResult.E_FAIL.Code, OpcResult.FuncCallType.SysFuncCall, null), "Unexpected results returned from server.");
}
if (result[0].Result.Failed())
{
throw new OpcResultException(new OpcResult((int)OpcResult.Cpx.E_FILTER_ERROR.Code, OpcResult.FuncCallType.SysFuncCall, null), "Could not update data filter.");
}
// update locale copy of the filter value.
DataFilterValue = filterValue;
}
/// <summary>
/// Fetches the type dictionary for the item.
/// </summary>
/// <param name="server">The server object</param>
public string GetTypeDictionary(TsCDaServer server)
{
var results = server.GetProperties(
new OpcItem[] { _dictionaryItemID },
new TsDaPropertyID[] { TsDaProperty.DICTIONARY },
true);
if (results == null || results.Length == 0 || results[0].Count == 0)
{
return null;
}
var property = results[0][0];
if (!property.Result.Succeeded())
{
return null;
}
return (string)property.Value;
}
/// <summary>
/// Fetches the type description for the item.
/// </summary>
/// <param name="server">The server object</param>
public string GetTypeDescription(TsCDaServer server)
{
var results = server.GetProperties(
new OpcItem[] { _typeItemID },
new TsDaPropertyID[] { TsDaProperty.TYPE_DESCRIPTION },
true);
if (results == null || results.Length == 0 || results[0].Count == 0)
{
return null;
}
var property = results[0][0];
if (!property.Result.Succeeded())
{
return null;
}
return (string)property.Value;
}
/// <summary>
/// Fetches the item id for the data filters items and stores it in the internal cache.
/// </summary>
/// <param name="server">The server object</param>
public void GetDataFilterItem(TsCDaServer server)
{
_filterItem = null;
// not a valid operation for data filter items.
if (_unfilteredItemID != null)
{
return;
}
TsCDaBrowsePosition position = null;
try
{
var itemID = new OpcItem(this);
// browse any existing filter instances.
var filters = new TsCDaBrowseFilters { ElementNameFilter = CPX_DATA_FILTERS, BrowseFilter = TsCDaBrowseFilter.All, ReturnAllProperties = false, PropertyIDs = null, ReturnPropertyValues = false };
TsCDaBrowseElement[] elements = null;
// browse for the 'CPX' branch first.
if (_unconvertedItemID == null)
{
filters.ElementNameFilter = CPX_BRANCH;
elements = server.Browse(itemID, filters, out position);
// nothing found.
if (elements == null || elements.Length == 0)
{
return;
}
// release the position object.
if (position != null)
{
position.Dispose();
position = null;
}
// update the item for the next browse operation.
itemID = new OpcItem(elements[0].ItemPath, elements[0].ItemName);
filters.ElementNameFilter = CPX_DATA_FILTERS;
}
// browse for the 'DataFilters' branch.
elements = server.Browse(itemID, filters, out position);
// nothing found.
if (elements == null || elements.Length == 0)
{
return;
}
_filterItem = new OpcItem(elements[0].ItemPath, elements[0].ItemName);
}
finally
{
if (position != null)
{
position.Dispose();
}
}
}
#endregion
///////////////////////////////////////////////////////////////////////
#region Private Methods
/// <summary>
/// Sets all object properties to their default values.
/// </summary>
private void Clear()
{
_typeSystemID = null;
_dictionaryID = null;
_typeID = null;
_dictionaryItemID = null;
_typeItemID = null;
_unconvertedItemID = null;
_unfilteredItemID = null;
_filterItem = null;
DataFilterValue = null;
}
/// <summary>
/// Initializes the object from a browse element.
/// </summary>
private bool Init(TsCDaBrowseElement element)
{
// update the item id.
ItemPath = element.ItemPath;
ItemName = element.ItemName;
Name = element.Name;
return Init(element.Properties);
}
/// <summary>
/// Initializes the object from a list of properties.
/// </summary>
private bool Init(TsCDaItemProperty[] properties)
{
// put the object into default state.
Clear();
// must have at least three properties defined.
if (properties == null || properties.Length < 3)
{
return false;
}
foreach (var property in properties)
{
// continue - ignore invalid properties.
if (!property.Result.Succeeded())
{
continue;
}
// type system id.
if (property.ID == TsDaProperty.TYPE_SYSTEM_ID)
{
_typeSystemID = (string)property.Value;
continue;
}
// dictionary id
if (property.ID == TsDaProperty.DICTIONARY_ID)
{
_dictionaryID = (string)property.Value;
_dictionaryItemID = new OpcItem(property.ItemPath, property.ItemName);
continue;
}
// type id
if (property.ID == TsDaProperty.TYPE_ID)
{
_typeID = (string)property.Value;
_typeItemID = new OpcItem(property.ItemPath, property.ItemName);
continue;
}
// unconverted item id
if (property.ID == TsDaProperty.UNCONVERTED_ITEM_ID)
{
_unconvertedItemID = new OpcItem(ItemPath, (string)property.Value);
continue;
}
// unfiltered item id
if (property.ID == TsDaProperty.UNFILTERED_ITEM_ID)
{
_unfilteredItemID = new OpcItem(ItemPath, (string)property.Value);
continue;
}
// data filter value.
if (property.ID == TsDaProperty.DATA_FILTER_VALUE)
{
DataFilterValue = (string)property.Value;
continue;
}
}
// validate object.
if (_typeSystemID == null || _dictionaryID == null || _typeID == null)
{
return false;
}
return true;
}
#endregion
}
}

View File

@@ -0,0 +1,207 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System.Collections;
using Technosoftware.DaAeHdaClient.Da;
#endregion
namespace Technosoftware.DaAeHdaClient.Cpx
{
/// <summary>
/// A class that caches properties of complex data items.
/// </summary>
public class TsCCpxComplexTypeCache
{
///////////////////////////////////////////////////////////////////////
#region Fields
/// <summary>
/// The active server for the application.
/// </summary>
private static TsCDaServer _server;
/// <summary>
/// A cache of item properties fetched from the active server.
/// </summary>
private static Hashtable _items = new Hashtable();
/// <summary>
/// A cache of type dictionaries fetched from the active server.
/// </summary>
private static Hashtable _dictionaries = new Hashtable();
/// <summary>
/// A cache of type descriptions fetched from the active server.
/// </summary>
private static Hashtable _descriptions = new Hashtable();
#endregion
///////////////////////////////////////////////////////////////////////
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the complex type cache with defaults.
/// </summary>
public TsCCpxComplexTypeCache() { }
#endregion
///////////////////////////////////////////////////////////////////////
#region Properties
/// <summary>
/// Get or sets the server to use for the cache.
/// </summary>
public static TsCDaServer Server
{
get
{
lock (typeof(TsCCpxComplexTypeCache))
{
return _server;
}
}
set
{
lock (typeof(TsCCpxComplexTypeCache))
{
_server = value;
_items.Clear();
_dictionaries.Clear();
_descriptions.Clear();
}
}
}
#endregion
///////////////////////////////////////////////////////////////////////
#region Public Methods
/// <summary>
/// Returns the complex item for the specified item id.
/// </summary>
/// <param name="itemID">The item id.</param>
public static TsCCpxComplexItem GetComplexItem(OpcItem itemID)
{
if (itemID == null) return null;
lock (typeof(TsCCpxComplexTypeCache))
{
var item = new TsCCpxComplexItem(itemID);
try
{
item.Update(_server);
}
catch
{
// item is not a valid complex data item.
item = null;
}
_items[itemID.Key] = item;
return item;
}
}
/// <summary>
/// Returns the complex item for the specified item browse element.
/// </summary>
/// <param name="element">The item browse element.</param>
public static TsCCpxComplexItem GetComplexItem(TsCDaBrowseElement element)
{
if (element == null) return null;
lock (typeof(TsCCpxComplexTypeCache))
{
return GetComplexItem(new OpcItem(element.ItemPath, element.ItemName));
}
}
/// <summary>
/// Fetches the type dictionary for the item.
/// </summary>
/// <param name="itemID">The item id.</param>
public static string GetTypeDictionary(OpcItem itemID)
{
if (itemID == null) return null;
lock (typeof(TsCCpxComplexTypeCache))
{
var dictionary = (string)_dictionaries[itemID.Key];
if (dictionary != null)
{
return dictionary;
}
var item = GetComplexItem(itemID);
if (item != null)
{
dictionary = item.GetTypeDictionary(_server);
}
return dictionary;
}
}
/// <summary>
/// Fetches the type description for the item.
/// </summary>
/// <param name="itemID">The item id.</param>
public static string GetTypeDescription(OpcItem itemID)
{
if (itemID == null) return null;
lock (typeof(TsCCpxComplexTypeCache))
{
string description = null;
var item = GetComplexItem(itemID);
if (item != null)
{
description = (string)_descriptions[item.TypeItemID.Key];
if (description != null)
{
return description;
}
_descriptions[item.TypeItemID.Key] = description = item.GetTypeDescription(_server);
}
return description;
}
}
#endregion
}
}

View File

@@ -0,0 +1,49 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Cpx
{
/// <summary>
/// Stores a value with an associated name and/or type.
/// </summary>
public class TsCCpxComplexValue
{
/// <summary>
/// The name of the value.
/// </summary>
public string Name;
/// <summary>
/// The complex or simple data type of the value.
/// </summary>
public string Type;
/// <summary>
/// The actual value.
/// </summary>
public object Value;
}
}

View File

@@ -0,0 +1,71 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Cpx
{
/// <summary>
/// Stores the current serialization context.
/// </summary>
internal struct TsCCpxContext
{
///////////////////////////////////////////////////////////////////////
#region Constructors, Destructor, Initialization
public TsCCpxContext(byte[] buffer)
{
Buffer = buffer;
Index = 0;
Dictionary = null;
Type = null;
BigEndian = false;
CharWidth = 2;
StringEncoding = STRING_ENCODING_UCS2;
FloatFormat = FLOAT_FORMAT_IEEE754;
}
#endregion
///////////////////////////////////////////////////////////////////////
#region Public Fields
public byte[] Buffer;
public int Index;
public TypeDictionary Dictionary;
public TypeDescription Type;
public bool BigEndian;
public int CharWidth;
public string StringEncoding;
public string FloatFormat;
public const string STRING_ENCODING_ACSII = "ASCII";
public const string STRING_ENCODING_UCS2 = "UCS-2";
public const string FLOAT_FORMAT_IEEE754 = "IEEE-754";
#endregion
}
}

View File

@@ -0,0 +1,48 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Runtime.Serialization;
#endregion
namespace Technosoftware.DaAeHdaClient.Cpx
{
/// <summary>
/// Raised if the data in buffer is not consistent with the schema.
/// </summary>
[Serializable]
public class TsCCpxInvalidDataInBufferException : ApplicationException
{
private const string Default = "The data in the buffer cannot be read because it is not consistent with the schema.";
/// <remarks/>
public TsCCpxInvalidDataInBufferException() : base(Default) { }
/// <remarks/>
public TsCCpxInvalidDataInBufferException(string message) : base(Default + Environment.NewLine + message) { }
/// <remarks/>
public TsCCpxInvalidDataInBufferException(Exception e) : base(Default, e) { }
/// <remarks/>
public TsCCpxInvalidDataInBufferException(string message, Exception innerException) : base(Default + Environment.NewLine + message, innerException) { }
/// <remarks/>
protected TsCCpxInvalidDataInBufferException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,48 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Runtime.Serialization;
#endregion
namespace Technosoftware.DaAeHdaClient.Cpx
{
/// <summary>
/// Raised if the data in buffer is not consistent with the schema.
/// </summary>
[Serializable]
public class TsCCpxInvalidDataToWriteException : ApplicationException
{
private const string Default = "The object cannot be written because it is not consistent with the schema.";
/// <remarks/>
public TsCCpxInvalidDataToWriteException() : base(Default) { }
/// <remarks/>
public TsCCpxInvalidDataToWriteException(string message) : base(Default + Environment.NewLine + message) { }
/// <remarks/>
public TsCCpxInvalidDataToWriteException(Exception e) : base(Default, e) { }
/// <remarks/>
public TsCCpxInvalidDataToWriteException(string message, Exception innerException) : base(Default + Environment.NewLine + message, innerException) { }
/// <remarks/>
protected TsCCpxInvalidDataToWriteException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,48 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Runtime.Serialization;
#endregion
namespace Technosoftware.DaAeHdaClient.Cpx
{
/// <summary>
/// Raised if the schema contains errors or inconsistencies.
/// </summary>
[Serializable]
public class TsCCpxInvalidSchemaException : ApplicationException
{
private const string Default = "The schema cannot be used because it contains errors or inconsitencies.";
/// <remarks/>
public TsCCpxInvalidSchemaException() : base(Default) { }
/// <remarks/>
public TsCCpxInvalidSchemaException(string message) : base(Default + Environment.NewLine + message) { }
/// <remarks/>
public TsCCpxInvalidSchemaException(Exception e) : base(Default, e) { }
/// <remarks/>
public TsCCpxInvalidSchemaException(string message, Exception innerException) : base(Default + Environment.NewLine + message, innerException) { }
/// <remarks/>
protected TsCCpxInvalidSchemaException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,269 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.573
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by xsd, Version=1.1.4322.573.
//
namespace Technosoftware.DaAeHdaClient.Cpx
{
using System.Xml.Serialization;
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
[XmlRootAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/", IsNullable=false)]
public class TypeDictionary {
/// <remarks/>
[XmlElementAttribute("TypeDescription")]
public TypeDescription[] TypeDescription;
/// <remarks/>
[XmlAttributeAttribute()]
public string DictionaryName;
/// <remarks/>
[XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(true)]
public bool DefaultBigEndian = true;
/// <remarks/>
[XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute("UCS-2")]
public string DefaultStringEncoding = "UCS-2";
/// <remarks/>
[XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(2)]
public int DefaultCharWidth = 2;
/// <remarks/>
[XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute("IEEE-754")]
public string DefaultFloatFormat = "IEEE-754";
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class TypeDescription {
/// <remarks/>
[XmlElementAttribute("Field")]
public FieldType[] Field;
/// <remarks/>
[XmlAttributeAttribute()]
public string TypeID;
/// <remarks/>
[XmlAttributeAttribute()]
public bool DefaultBigEndian;
/// <remarks/>
[XmlIgnoreAttribute()]
public bool DefaultBigEndianSpecified;
/// <remarks/>
[XmlAttributeAttribute()]
public string DefaultStringEncoding;
/// <remarks/>
[XmlAttributeAttribute()]
public int DefaultCharWidth;
/// <remarks/>
[XmlIgnoreAttribute()]
public bool DefaultCharWidthSpecified;
/// <remarks/>
[XmlAttributeAttribute()]
public string DefaultFloatFormat;
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
[XmlIncludeAttribute(typeof(TypeReference))]
[XmlIncludeAttribute(typeof(CharString))]
[XmlIncludeAttribute(typeof(Unicode))]
[XmlIncludeAttribute(typeof(Ascii))]
[XmlIncludeAttribute(typeof(FloatingPoint))]
[XmlIncludeAttribute(typeof(Double))]
[XmlIncludeAttribute(typeof(Single))]
[XmlIncludeAttribute(typeof(Integer))]
[XmlIncludeAttribute(typeof(UInt64))]
[XmlIncludeAttribute(typeof(UInt32))]
[XmlIncludeAttribute(typeof(UInt16))]
[XmlIncludeAttribute(typeof(UInt8))]
[XmlIncludeAttribute(typeof(Int64))]
[XmlIncludeAttribute(typeof(Int32))]
[XmlIncludeAttribute(typeof(Int16))]
[XmlIncludeAttribute(typeof(Int8))]
[XmlIncludeAttribute(typeof(BitString))]
public class FieldType {
/// <remarks/>
[XmlAttributeAttribute()]
public string Name;
/// <remarks/>
[XmlAttributeAttribute()]
public string Format;
/// <remarks/>
[XmlAttributeAttribute()]
public int Length;
/// <remarks/>
[XmlIgnoreAttribute()]
public bool LengthSpecified;
/// <remarks/>
[XmlAttributeAttribute()]
public int ElementCount;
/// <remarks/>
[XmlIgnoreAttribute()]
public bool ElementCountSpecified;
/// <remarks/>
[XmlAttributeAttribute()]
public string ElementCountRef;
/// <remarks/>
[XmlAttributeAttribute()]
public string FieldTerminator;
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class TypeReference : FieldType {
/// <remarks/>
[XmlAttributeAttribute()]
public string TypeID;
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
[XmlIncludeAttribute(typeof(Unicode))]
[XmlIncludeAttribute(typeof(Ascii))]
public class CharString : FieldType {
/// <remarks/>
[XmlAttributeAttribute()]
public int CharWidth;
/// <remarks/>
[XmlIgnoreAttribute()]
public bool CharWidthSpecified;
/// <remarks/>
[XmlAttributeAttribute()]
public string StringEncoding;
/// <remarks/>
[XmlAttributeAttribute()]
public string CharCountRef;
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class Unicode : CharString {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class Ascii : CharString {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
[XmlIncludeAttribute(typeof(Double))]
[XmlIncludeAttribute(typeof(Single))]
public class FloatingPoint : FieldType {
/// <remarks/>
[XmlAttributeAttribute()]
public string FloatFormat;
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class Double : FloatingPoint {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class Single : FloatingPoint {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
[XmlIncludeAttribute(typeof(UInt64))]
[XmlIncludeAttribute(typeof(UInt32))]
[XmlIncludeAttribute(typeof(UInt16))]
[XmlIncludeAttribute(typeof(UInt8))]
[XmlIncludeAttribute(typeof(Int64))]
[XmlIncludeAttribute(typeof(Int32))]
[XmlIncludeAttribute(typeof(Int16))]
[XmlIncludeAttribute(typeof(Int8))]
public class Integer : FieldType {
/// <remarks/>
[XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(true)]
public bool Signed = true;
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class UInt64 : Integer {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class UInt32 : Integer {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class UInt16 : Integer {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class UInt8 : Integer {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class Int64 : Integer {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class Int32 : Integer {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class Int16 : Integer {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class Int8 : Integer {
}
/// <remarks/>
[XmlTypeAttribute(Namespace="http://opcfoundation.org/OPCBinary/1.0/")]
public class BitString : FieldType {
}
}

View File

@@ -0,0 +1,165 @@
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="OPCBinary" targetNamespace="http://opcfoundation.org/OPCBinary/1.0/" elementFormDefault="qualified"
xmlns="http://opcfoundation.org/OPCBinary/1.0/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="TypeDictionary">
<xs:complexType>
<xs:sequence>
<xs:element name="TypeDescription" type="TypeDescription" minOccurs="1" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="DictionaryName" type="xs:string" use="required" />
<xs:attribute name="DefaultBigEndian" type="xs:boolean" default="true" />
<xs:attribute name="DefaultStringEncoding" type="xs:string" default="UCS-2" />
<xs:attribute name="DefaultCharWidth" type="xs:int" default="2" />
<xs:attribute name="DefaultFloatFormat" type="xs:string" default="IEEE-754" />
</xs:complexType>
</xs:element>
<xs:complexType name="TypeDescription">
<xs:sequence>
<xs:element name="Field" type="FieldType" minOccurs="1" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="TypeID" type="xs:string" use="required" />
<xs:attribute name="DefaultBigEndian" type="xs:boolean" use="optional" />
<xs:attribute name="DefaultStringEncoding" type="xs:string" use="optional" />
<xs:attribute name="DefaultCharWidth" type="xs:int" use="optional" />
<xs:attribute name="DefaultFloatFormat" type="xs:string" use="optional" />
</xs:complexType>
<xs:complexType name="FieldType">
<xs:attribute name="Name" type="xs:string" use="optional" />
<xs:attribute name="Format" type="xs:string" use="optional" />
<xs:attribute name="Length" type="xs:int" use="optional" />
<xs:attribute name="ElementCount" type="xs:int" use="optional" />
<xs:attribute name="ElementCountRef" type="xs:string" use="optional" />
<xs:attribute name="FieldTerminator" type="xs:string" use="optional" />
</xs:complexType>
<xs:complexType name="BitString">
<xs:complexContent>
<xs:extension base="FieldType"></xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Integer">
<xs:complexContent>
<xs:extension base="FieldType">
<xs:attribute name="Signed" type="xs:boolean" default="true" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="FloatingPoint">
<xs:complexContent>
<xs:extension base="FieldType">
<xs:attribute name="FloatFormat" type="xs:string" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="CharString">
<xs:complexContent>
<xs:extension base="FieldType">
<xs:attribute name="CharWidth" type="xs:int" />
<xs:attribute name="StringEncoding" type="xs:string" />
<xs:attribute name="CharCountRef" type="xs:string" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="TypeReference">
<xs:complexContent>
<xs:extension base="FieldType">
<xs:attribute name="TypeID" type="xs:string" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Int8">
<xs:complexContent>
<xs:restriction base="Integer">
<xs:attribute name="Length" type="xs:int" fixed="1" />
<xs:attribute name="Signed" type="xs:boolean" fixed="true" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Int16">
<xs:complexContent>
<xs:restriction base="Integer">
<xs:attribute name="Length" type="xs:int" fixed="2" />
<xs:attribute name="Signed" type="xs:boolean" fixed="true" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Int32">
<xs:complexContent>
<xs:restriction base="Integer">
<xs:attribute name="Length" type="xs:int" fixed="4" />
<xs:attribute name="Signed" type="xs:boolean" fixed="true" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Int64">
<xs:complexContent>
<xs:restriction base="Integer">
<xs:attribute name="Length" type="xs:int" fixed="8" />
<xs:attribute name="Signed" type="xs:boolean" fixed="true" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="UInt8">
<xs:complexContent>
<xs:restriction base="Integer">
<xs:attribute name="Length" type="xs:int" fixed="1" />
<xs:attribute name="Signed" type="xs:boolean" fixed="false" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="UInt16">
<xs:complexContent>
<xs:restriction base="Integer">
<xs:attribute name="Length" type="xs:int" fixed="2" />
<xs:attribute name="Signed" type="xs:boolean" fixed="false" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="UInt32">
<xs:complexContent>
<xs:restriction base="Integer">
<xs:attribute name="Length" type="xs:int" fixed="4" />
<xs:attribute name="Signed" type="xs:boolean" fixed="false" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="UInt64">
<xs:complexContent>
<xs:restriction base="Integer">
<xs:attribute name="Length" type="xs:int" fixed="8" />
<xs:attribute name="Signed" type="xs:boolean" fixed="false" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Single">
<xs:complexContent>
<xs:restriction base="FloatingPoint">
<xs:attribute name="Length" type="xs:int" fixed="4" />
<xs:attribute name="FloatFormat" type="xs:string" fixed="IEEE-754" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Double">
<xs:complexContent>
<xs:restriction base="FloatingPoint">
<xs:attribute name="Length" type="xs:int" fixed="8" />
<xs:attribute name="FloatFormat" type="xs:string" fixed="IEEE-754" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Ascii">
<xs:complexContent>
<xs:restriction base="CharString">
<xs:attribute name="CharWidth" type="xs:int" fixed="1" />
<xs:attribute name="StringEncoding" type="xs:string" fixed="ASCII" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Unicode">
<xs:complexContent>
<xs:restriction base="CharString">
<xs:attribute name="CharWidth" type="xs:int" fixed="2" />
<xs:attribute name="StringEncoding" type="xs:string" fixed="UCS-2" />
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:schema>

View File

@@ -0,0 +1,45 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// <para>Defines possible item access rights.</para>
/// <para align="left">Indicates if this item is read only, write only or read/write.
/// This is NOT related to security but rather to the nature of the underlying
/// hardware.</para>
/// </summary>
public enum TsDaAccessRights
{
/// <summary>The access rights for this item are server.</summary>
Unknown = 0x00,
/// <summary>The client can read the data item's value.</summary>
Readable = 0x01,
/// <summary>The client can change the data item's value.</summary>
Writable = 0x02,
/// <summary>The client can read and change the data item's value.</summary>
ReadWritable = 0x03
}
}

View File

@@ -0,0 +1,93 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Stores the state of a browse operation.
/// </summary>
[Serializable]
public class TsCDaBrowsePosition : IOpcBrowsePosition
{
#region Fields
private TsCDaBrowseFilters browseFilters_;
private OpcItem itemId_;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Saves the parameters for an incomplete browse information.
/// </summary>
public TsCDaBrowsePosition(OpcItem itemId, TsCDaBrowseFilters filters)
{
if (filters == null) throw new ArgumentNullException(nameof(filters));
itemId_ = (OpcItem)itemId?.Clone();
browseFilters_ = (TsCDaBrowseFilters)filters.Clone();
}
/// <summary>
/// Releases unmanaged resources held by the object.
/// </summary>
public virtual void Dispose()
{
// does nothing.
}
#endregion
#region Properties
/// <summary>
/// The item identifier of the branch being browsed.
/// </summary>
public OpcItem ItemID => itemId_;
/// <summary>
/// The filters applied during the browse operation.
/// </summary>
public TsCDaBrowseFilters Filters => (TsCDaBrowseFilters)browseFilters_.Clone();
/// <summary>
/// The maximum number of elements that may be returned in a single browse.
/// </summary>
// ReSharper disable once UnusedMember.Global
public int MaxElementsReturned
{
get => browseFilters_.MaxElementsReturned;
set => browseFilters_.MaxElementsReturned = value;
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
return (TsCDaBrowsePosition)MemberwiseClone();
}
#endregion
}
}

View File

@@ -0,0 +1,87 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Contains a description of an element in the server address space.
/// </summary>
[Serializable]
public class TsCDaBrowseElement : ICloneable
{
#region Fields
private TsCDaItemProperty[] itemProperties_ = new TsCDaItemProperty[0];
#endregion
#region Properties
/// <summary>
/// A descriptive name for element that is unique within a branch.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The primary identifier for the element within the server namespace.
/// </summary>
public string ItemName { get; set; }
/// <summary>
/// An secondary identifier for the element within the server namespace.
/// </summary>
public string ItemPath { get; set; }
/// <summary>
/// Whether the element refers to an item with data that can be accessed.
/// </summary>
public bool IsItem { get; set; }
/// <summary>
/// Whether the element has children.
/// </summary>
public bool HasChildren { get; set; }
/// <summary>
/// The set of properties for the element.
/// </summary>
public TsCDaItemProperty[] Properties
{
get => itemProperties_;
set => itemProperties_ = value;
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
var clone = (TsCDaBrowseElement)MemberwiseClone();
clone.itemProperties_ = (TsCDaItemProperty[])OpcConvert.Clone(itemProperties_);
return clone;
}
#endregion
};
}

View File

@@ -0,0 +1,48 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// The type of browse elements to return during a browse.
/// </summary>
public enum TsCDaBrowseFilter
{
/// <summary>
/// Return all types of browse elements.
/// </summary>
All,
/// <summary>
/// Return only elements that contain other elements.
/// </summary>
Branch,
/// <summary>
/// Return only elements that represent items.
/// </summary>
Item
}
}

View File

@@ -0,0 +1,97 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Defines a set of filters to apply when browsing.
/// </summary>
[Serializable]
public class TsCDaBrowseFilters : ICloneable
{
#region Fields
private TsCDaBrowseFilter browseFilter_ = TsCDaBrowseFilter.All;
private TsDaPropertyID[] propertyIds_;
#endregion
#region Properties
/// <summary>
/// The maximum number of elements to return. Zero means no limit.
/// </summary>
public int MaxElementsReturned { get; set; }
/// <summary>
/// The type of element to return.
/// </summary>
public TsCDaBrowseFilter BrowseFilter
{
get => browseFilter_;
set => browseFilter_ = value;
}
/// <summary>
/// An expression used to match the name of the element.
/// </summary>
public string ElementNameFilter { get; set; }
/// <summary>
/// A filter which has semantics that defined by the server.
/// </summary>
public string VendorFilter { get; set; }
/// <summary>
/// Whether all supported properties to return with each element.
/// </summary>
public bool ReturnAllProperties { get; set; }
/// <summary>
/// A list of names of the properties to return with each element.
/// </summary>
public TsDaPropertyID[] PropertyIDs
{
get => propertyIds_;
set => propertyIds_ = value;
}
/// <summary>
/// Whether property values should be returned with the properties.
/// </summary>
public bool ReturnPropertyValues { get; set; }
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
var clone = (TsCDaBrowseFilters)MemberwiseClone();
clone.PropertyIDs = (TsDaPropertyID[])PropertyIDs?.Clone();
return clone;
}
#endregion
}
}

View File

@@ -0,0 +1,45 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary><para>Defines possible item engineering unit types</para></summary>
public enum TsDaEuType
{
/// <summary>No engineering unit information available</summary>
NoEnum = 0x01,
/// <summary>
/// Analog engineering unit - will contain a SAFE ARRAY of exactly two doubles
/// (VT_ARRAY | VT_R8) corresponding to the LOW and HI EU range.
/// </summary>
Analog = 0x02,
/// <summary>
/// Enumerated engineering unit - will contain a SAFE ARRAY of strings (VT_ARRAY |
/// VT_BSTR) which contains a list of strings (Example: “OPEN”, “CLOSE”, “IN TRANSIT”,
/// etc.) corresponding to sequential numeric values (0, 1, 2, etc.)
/// </summary>
Enumerated = 0x03
}
}

View File

@@ -0,0 +1,109 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Defines functionality that is common to all OPC Data Access servers.
/// </summary>
public interface ITsDaServer : IOpcServer
{
/// <summary>
/// Returns the filters applied by the server to any item results returned to the client.
/// </summary>
/// <returns>A bit mask indicating which fields should be returned in any item results.</returns>
int GetResultFilters();
/// <summary>
/// Sets the filters applied by the server to any item results returned to the client.
/// </summary>
/// <param name="filters">A bit mask indicating which fields should be returned in any item results.</param>
void SetResultFilters(int filters);
/// <summary>
/// Returns the current server status.
/// </summary>
/// <returns>The current server status.</returns>
OpcServerStatus GetServerStatus();
/// <summary>
/// Reads the current values for a set of items.
/// </summary>
/// <param name="items">The set of items to read.</param>
/// <returns>The results of the read operation for each item.</returns>
TsCDaItemValueResult[] Read(TsCDaItem[] items);
/// <summary>
/// Writes the value, quality and timestamp for a set of items.
/// </summary>
/// <param name="values">The set of item values to write.</param>
/// <returns>The results of the write operation for each item.</returns>
OpcItemResult[] Write(TsCDaItemValue[] values);
/// <summary>
/// Creates a new subscription.
/// </summary>
/// <param name="state">The initial state of the subscription.</param>
/// <returns>The new subscription object.</returns>
ITsCDaSubscription CreateSubscription(TsCDaSubscriptionState state);
/// <summary>
/// Cancels a subscription and releases all resources allocated for it.
/// </summary>
/// <param name="subscription">The subscription to cancel.</param>
void CancelSubscription(ITsCDaSubscription subscription);
/// <summary>
/// Fetches the children of a branch that meet the filter criteria.
/// </summary>
/// <param name="itemId">The identifier of branch which is the target of the search.</param>
/// <param name="filters">The filters to use to limit the set of child elements returned.</param>
/// <param name="position">An object used to continue a browse that could not be completed.</param>
/// <returns>The set of elements found.</returns>
TsCDaBrowseElement[] Browse(
OpcItem itemId,
TsCDaBrowseFilters filters,
out TsCDaBrowsePosition position);
/// <summary>
/// Continues a browse operation with previously specified search criteria.
/// </summary>
/// <param name="position">An object containing the browse operation state information.</param>
/// <returns>The set of elements found.</returns>
TsCDaBrowseElement[] BrowseNext(ref TsCDaBrowsePosition position);
/// <summary>
/// Returns the item properties for a set of items.
/// </summary>
/// <param name="itemIds">A list of item identifiers.</param>
/// <param name="propertyIDs">A list of properties to fetch for each item.</param>
/// <param name="returnValues">Whether the property values should be returned with the properties.</param>
/// <returns>A list of properties for each item.</returns>
TsCDaItemPropertyCollection[] GetProperties(
OpcItem[] itemIds,
TsDaPropertyID[] propertyIDs,
bool returnValues);
}
}

View File

@@ -0,0 +1,226 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// A subscription for a set of items on a single OPC server.
/// </summary>
public interface ITsCDaSubscription : IDisposable
{
#region Events
/// <summary>
/// An event to receive data change updates.
/// </summary>
event TsCDaDataChangedEventHandler DataChangedEvent;
#endregion
#region Result Filters
/// <summary>
/// Returns the filters applied by the server to any item results returned to the client.
/// </summary>
/// <returns>A bit mask indicating which fields should be returned in any item results.</returns>
int GetResultFilters();
/// <summary>
/// Sets the filters applied by the server to any item results returned to the client.
/// </summary>
/// <param name="filters">A bit mask indicating which fields should be returned in any item results.</param>
void SetResultFilters(int filters);
#endregion
#region State Management
/// <summary>
/// Returns the current state of the subscription.
/// </summary>
/// <returns>The current state of the subscription.</returns>
TsCDaSubscriptionState GetState();
/// <summary>
/// Changes the state of a subscription.
/// </summary>
/// <param name="masks">A bit mask that indicates which elements of the subscription state are changing.</param>
/// <param name="state">The new subscription state.</param>
/// <returns>The actual subscription state after applying the changes.</returns>
TsCDaSubscriptionState ModifyState(int masks, TsCDaSubscriptionState state);
#endregion
#region Item Management
/// <summary>
/// Adds items to the subscription.
/// </summary>
/// <param name="items">The set of items to add to the subscription.</param>
/// <returns>The results of the add item operation for each item.</returns>
TsCDaItemResult[] AddItems(TsCDaItem[] items);
/// <summary>
/// Modifies the state of items in the subscription
/// </summary>
/// <param name="masks">Specifies which item state parameters are being modified.</param>
/// <param name="items">The new state for each item.</param>
/// <returns>The results of the modify item operation for each item.</returns>
TsCDaItemResult[] ModifyItems(int masks, TsCDaItem[] items);
/// <summary>
/// Removes items from the subscription.
/// </summary>
/// <param name="items">The identifiers (i.e. server handles) for the items being removed.</param>
/// <returns>The results of the remove item operation for each item.</returns>
OpcItemResult[] RemoveItems(OpcItem[] items);
#endregion
#region Synchronous I/O
/// <summary>
/// Reads the values for a set of items in the subscription.
/// </summary>
/// <param name="items">The identifiers (i.e. server handles) for the items being read.</param>
/// <returns>The value for each of items.</returns>
TsCDaItemValueResult[] Read(TsCDaItem[] items);
/// <summary>
/// Writes the value, quality and timestamp for a set of items in the subscription.
/// </summary>
/// <param name="items">The item values to write.</param>
/// <returns>The results of the write operation for each item.</returns>
OpcItemResult[] Write(TsCDaItemValue[] items);
#endregion
#region Asynchronous I/O
/// <summary>
/// Begins an asynchronous read operation for a set of items.
/// </summary>
/// <param name="items">The set of items to read (must include the item name).</param>
/// <param name="requestHandle">An identifier for the request assigned by the caller.</param>
/// <param name="callback">A delegate used to receive notifications when the request completes.</param>
/// <param name="request">An object that contains the state of the request (used to cancel the request).</param>
/// <returns>A set of results containing any errors encountered when the server validated the items.</returns>
OpcItemResult[] Read(
TsCDaItem[] items,
object requestHandle,
TsCDaReadCompleteEventHandler callback,
out IOpcRequest request);
/// <summary>
/// Begins an asynchronous write operation for a set of items.
/// </summary>
/// <param name="items">The set of item values to write (must include the item name).</param>
/// <param name="requestHandle">An identifier for the request assigned by the caller.</param>
/// <param name="callback">A delegate used to receive notifications when the request completes.</param>
/// <param name="request">An object that contains the state of the request (used to cancel the request).</param>
/// <returns>A set of results containing any errors encountered when the server validated the items.</returns>
OpcItemResult[] Write(
TsCDaItemValue[] items,
object requestHandle,
TsCDaWriteCompleteEventHandler callback,
out IOpcRequest request);
/// <summary>
/// Cancels an asynchronous read or write operation.
/// </summary>
/// <param name="request">The object returned from the BeginRead or BeginWrite request.</param>
/// <param name="callback">The function to invoke when the cancel completes.</param>
void Cancel(IOpcRequest request, TsCDaCancelCompleteEventHandler callback);
/// <summary>
/// Causes the server to send a data changed notification for all active items.
/// </summary>
void Refresh();
/// <summary>
/// Causes the server to send a data changed notification for all active items.
/// </summary>
/// <param name="requestHandle">An identifier for the request assigned by the caller.</param>
/// <param name="request">An object that contains the state of the request (used to cancel the request).</param>
/// <returns>A set of results containing any errors encountered when the server validated the items.</returns>
void Refresh(
object requestHandle,
out IOpcRequest request);
/// <summary>
/// Enables or disables data change notifications from the server.
/// </summary>
/// <param name="enabled">Whether data change notifications are enabled.</param>
void SetEnabled(bool enabled);
/// <summary>
/// Checks whether data change notifications from the server are enabled.
/// </summary>
/// <returns>Whether data change notifications are enabled.</returns>
bool GetEnabled();
#endregion
}
#region Delegate Declarations
/// <summary>
/// A delegate to receive data change updates from the server.
/// </summary>
/// <param name="subscriptionHandle">
/// A unique identifier for the subscription assigned by the client. If the parameter
/// <see cref="TsCDaSubscriptionState.ClientHandle">ClientHandle</see> is not defined this
/// parameter is empty.
/// </param>
/// <param name="requestHandle">
/// An identifier for the request assigned by the caller. This parameter is empty if
/// the corresponding parameter in the calls Read(), Write() or Refresh() is not defined.
/// Can be used to Cancel an outstanding operation.
/// </param>
/// <param name="values">
/// <para class="MsoBodyText" style="MARGIN: 1pt 0in">The set of changed values.</para>
/// <para class="MsoBodyText" style="MARGIN: 1pt 0in">Each value will always have
/// items ClientHandle field specified.</para>
/// </param>
public delegate void TsCDaDataChangedEventHandler(object subscriptionHandle, object requestHandle, TsCDaItemValueResult[] values);
/// <summary>
/// A delegate to receive asynchronous read completed notifications.
/// </summary>
/// <param name="requestHandle">
/// An identifier for the request assigned by the caller. This parameter is empty if
/// the corresponding parameter in the calls Read(), Write() or Refresh() is not defined.
/// Can be used to Cancel an outstanding operation.
/// </param>
/// <param name="results">The results of the last asynchronous read operation.</param>
public delegate void TsCDaReadCompleteEventHandler(object requestHandle, TsCDaItemValueResult[] results);
/// <summary>
/// A delegate to receive asynchronous write completed notifications.
/// </summary>
/// <param name="requestHandle">
/// An identifier for the request assigned by the caller. This parameter is empty if
/// the corresponding parameter in the calls Read(), Write() or Refresh() is not defined.
/// Can be used to Cancel an outstanding operation.
/// </param>
/// <param name="results">The results of the last asynchronous write operation.</param>
public delegate void TsCDaWriteCompleteEventHandler(object requestHandle, OpcItemResult[] results);
/// <summary>
/// A delegate to receive asynchronous cancel completed notifications.
/// </summary>
/// <param name="requestHandle">An identifier for the request assigned by the caller.</param>
public delegate void TsCDaCancelCompleteEventHandler(object requestHandle);
#endregion
}

View File

@@ -0,0 +1,150 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Describes how an item in the server address space should be accessed.
/// </summary>
[Serializable]
public class TsCDaItem : OpcItem
{
#region Fields
private bool active_ = true;
private float deadband_;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with default values.
/// </summary>
public TsCDaItem() { }
/// <summary>
/// Initializes object with the specified ItemIdentifier object.
/// </summary>
public TsCDaItem(OpcItem item)
{
if (item == null)
{
return;
}
ItemName = item.ItemName;
ItemPath = item.ItemPath;
ClientHandle = item.ClientHandle;
ServerHandle = item.ServerHandle;
}
/// <summary>
/// Initializes object with the specified Item object.
/// </summary>
public TsCDaItem(TsCDaItem item)
: base(item)
{
if (item == null)
{
return;
}
ReqType = item.ReqType;
MaxAge = item.MaxAge;
MaxAgeSpecified = item.MaxAgeSpecified;
Active = item.Active;
ActiveSpecified = item.ActiveSpecified;
Deadband = item.Deadband;
DeadbandSpecified = item.DeadbandSpecified;
SamplingRate = item.SamplingRate;
SamplingRateSpecified = item.SamplingRateSpecified;
EnableBuffering = item.EnableBuffering;
EnableBufferingSpecified = item.EnableBufferingSpecified;
}
#endregion
#region Properties
/// <summary>
/// The data type to use when returning the item value.
/// </summary>
public Type ReqType { get; set; }
/// <summary>
/// The oldest (in milliseconds) acceptable cached value when reading an item.
/// </summary>
public int MaxAge { get; set; }
/// <summary>
/// Whether the Max Age is specified.
/// </summary>
public bool MaxAgeSpecified { get; set; }
/// <summary>
/// Whether the server should send data change updates.
/// </summary>
public bool Active
{
get => active_;
set => active_ = value;
}
/// <summary>
/// Whether the Active state is specified.
/// </summary>
public bool ActiveSpecified { get; set; }
/// <summary>
/// The minimum percentage change required to trigger a data update for an item.
/// </summary>
public float Deadband
{
get => deadband_;
set => deadband_ = value;
}
/// <summary>
/// Whether the Deadband is specified.
/// </summary>
public bool DeadbandSpecified { get; set; }
/// <summary>
/// How frequently the server should sample the item value.
/// </summary>
public int SamplingRate { get; set; }
/// <summary>
/// Whether the Sampling Rate is specified.
/// </summary>
public bool SamplingRateSpecified { get; set; }
/// <summary>
/// Whether the server should buffer multiple data changes between data updates.
/// </summary>
public bool EnableBuffering { get; set; }
/// <summary>
/// Whether the Enable Buffering is specified.
/// </summary>
public bool EnableBufferingSpecified { get; set; }
#endregion
}
}

View File

@@ -0,0 +1,313 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// A collection of items.
/// </summary>
[Serializable]
public class TsCDaItemCollection : ICloneable, IList
{
#region Fields
private ArrayList items_ = new ArrayList();
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes object with the default values.
/// </summary>
public TsCDaItemCollection() { }
/// <summary>
/// Initializes object with the specified ResultCollection object.
/// </summary>
public TsCDaItemCollection(TsCDaItemCollection items)
{
if (items == null)
{
return;
}
foreach (TsCDaItem item in items)
{
Add(item);
}
}
#endregion
#region Properties
/// <summary>
/// Gets the item at the specified index.
/// </summary>
public TsCDaItem this[int index]
{
get => (TsCDaItem)items_[index];
set => items_[index] = value;
}
/// <summary>
/// Gets the first item with the specified item id.
/// </summary>
public TsCDaItem this[OpcItem itemId]
{
get
{
foreach (TsCDaItem item in items_)
{
if (itemId.Key == item.Key)
{
return item;
}
}
return null;
}
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
var clone = (TsCDaItemCollection)MemberwiseClone();
clone.items_ = new ArrayList();
foreach (TsCDaItem item in items_)
{
clone.items_.Add(item.Clone());
}
return clone;
}
#endregion
#region ICollection Members
/// <summary>
/// Indicates whether access to the ICollection is synchronized (thread-safe).
/// </summary>
public bool IsSynchronized => false;
/// <summary>
/// Gets the number of objects in the collection.
/// </summary>
public int Count => items_?.Count ?? 0;
/// <summary>
/// Copies the objects to an Array, starting at a the specified index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination for the objects.</param>
/// <param name="index">The zero-based index in the Array at which copying begins.</param>
public void CopyTo(Array array, int index)
{
items_?.CopyTo(array, index);
}
/// <summary>
/// Copies the objects to an Array, starting at a the specified index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination for the objects.</param>
/// <param name="index">The zero-based index in the Array at which copying begins.</param>
public void CopyTo(TsCDaItem[] array, int index)
{
CopyTo((Array)array, index);
}
/// <summary>
/// Indicates whether access to the ICollection is synchronized (thread-safe).
/// </summary>
public object SyncRoot => this;
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that can iterate through a collection.
/// </summary>
/// <returns>An IEnumerator that can be used to iterate through the collection.</returns>
public IEnumerator GetEnumerator()
{
return items_.GetEnumerator();
}
#endregion
#region IList Members
/// <summary>
/// Gets a value indicating whether the IList is read-only.
/// </summary>
public bool IsReadOnly => false;
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
object IList.this[int index]
{
get => items_[index];
set
{
if (!typeof(TsCDaItem).IsInstanceOfType(value))
{
throw new ArgumentException("May only add Item objects into the collection.");
}
items_[index] = value;
}
}
/// <summary>
/// Removes the IList item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
items_.RemoveAt(index);
}
/// <summary>
/// Inserts an item to the IList at the specified position.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The Object to insert into the IList. </param>
public void Insert(int index, object value)
{
if (!typeof(TsCDaItem).IsInstanceOfType(value))
{
throw new ArgumentException("May only add Item objects into the collection.");
}
items_.Insert(index, value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the IList.
/// </summary>
/// <param name="value">The Object to remove from the IList.</param>
public void Remove(object value)
{
items_.Remove(value);
}
/// <summary>
/// Determines whether the IList contains a specific value.
/// </summary>
/// <param name="value">The Object to locate in the IList.</param>
/// <returns>true if the Object is found in the IList; otherwise, false.</returns>
public bool Contains(object value)
{
return items_.Contains(value);
}
/// <summary>
/// Removes all items from the IList.
/// </summary>
public void Clear()
{
items_.Clear();
}
/// <summary>
/// Determines the index of a specific item in the IList.
/// </summary>
/// <param name="value">The Object to locate in the IList.</param>
/// <returns>The index of value if found in the list; otherwise, -1.</returns>
public int IndexOf(object value)
{
return items_.IndexOf(value);
}
/// <summary>
/// Adds an item to the IList.
/// </summary>
/// <param name="value">The Object to add to the IList. </param>
/// <returns>The position into which the new element was inserted.</returns>
public int Add(object value)
{
if (!typeof(TsCDaItem).IsInstanceOfType(value))
{
throw new ArgumentException("May only add Item objects into the collection.");
}
return items_.Add(value);
}
/// <summary>
/// Indicates whether the IList has a fixed size.
/// </summary>
public bool IsFixedSize => false;
/// <summary>
/// Inserts an item to the IList at the specified position.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The Object to insert into the IList. </param>
public void Insert(int index, TsCDaItem value)
{
Insert(index, (object)value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the IList.
/// </summary>
/// <param name="value">The Object to remove from the IList.</param>
public void Remove(TsCDaItem value)
{
Remove((object)value);
}
/// <summary>
/// Determines whether the IList contains a specific value.
/// </summary>
/// <param name="value">The Object to locate in the IList.</param>
/// <returns>true if the Object is found in the IList; otherwise, false.</returns>
public bool Contains(TsCDaItem value)
{
return Contains((object)value);
}
/// <summary>
/// Determines the index of a specific item in the IList.
/// </summary>
/// <param name="value">The Object to locate in the IList.</param>
/// <returns>The index of value if found in the list; otherwise, -1.</returns>
public int IndexOf(TsCDaItem value)
{
return IndexOf((object)value);
}
/// <summary>
/// Adds an item to the IList.
/// </summary>
/// <param name="value">The Object to add to the IList. </param>
/// <returns>The position into which the new element was inserted.</returns>
public int Add(TsCDaItem value)
{
return Add((object)value);
}
#endregion
}
}

View File

@@ -0,0 +1,100 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Contains a description of a single item property.
/// </summary>
[Serializable]
public class TsCDaItemProperty : ICloneable, IOpcResult
{
#region Fields
private OpcResult result_ = OpcResult.S_OK;
#endregion
#region Properties
/// <summary>
/// The property identifier.
/// </summary>
public TsDaPropertyID ID { get; set; }
/// <summary>
/// A short description of the property.
/// </summary>
public string Description { get; set; }
/// <summary>
/// The data type of the property.
/// </summary>
public Type DataType { get; set; }
/// <summary>
/// The value of the property.
/// </summary>
public object Value { get; set; }
/// <summary>
/// The primary identifier for the property if it is directly accessible as an item.
/// </summary>
public string ItemName { get; set; }
/// <summary>
/// The secondary identifier for the property if it is directly accessible as an item.
/// </summary>
public string ItemPath { get; set; }
#endregion
#region IOpcResult Members
/// <summary>
/// The <see cref="OpcResult" /> object with the result of an operation on an property.
/// </summary>
public OpcResult Result
{
get => result_;
set => result_ = value;
}
/// <summary>
/// Vendor specific diagnostic information (not the localized error text).
/// </summary>
public string DiagnosticInfo { get; set; }
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public virtual object Clone()
{
var clone = (TsCDaItemProperty)MemberwiseClone();
clone.Value = OpcConvert.Clone(Value);
return clone;
}
#endregion
}
}

View File

@@ -0,0 +1,175 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// A list of properties for a single item.
/// </summary>
[Serializable]
public class TsCDaItemPropertyCollection : ArrayList, IOpcResult
{
#region Fields
private OpcResult result_ = OpcResult.S_OK;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with its default values.
/// </summary>
public TsCDaItemPropertyCollection()
{
}
/// <summary>
/// Initializes the object with the specified item identifier.
/// </summary>
public TsCDaItemPropertyCollection(OpcItem itemId)
{
if (itemId != null)
{
ItemName = itemId.ItemName;
ItemPath = itemId.ItemPath;
}
}
/// <summary>
/// Initializes the object with the specified item identifier and result.
/// </summary>
public TsCDaItemPropertyCollection(OpcItem itemId, OpcResult result)
{
if (itemId != null)
{
ItemName = itemId.ItemName;
ItemPath = itemId.ItemPath;
}
result_ = result;
}
#endregion
#region Properties
/// <summary>
/// The primary identifier for the item within the server namespace.
/// </summary>
public string ItemName { get; set; }
/// <summary>
/// An secondary identifier for the item within the server namespace.
/// </summary>
public string ItemPath { get; set; }
/// <summary>
/// Accesses the items at the specified index.
/// </summary>
public new TsCDaItemProperty this[int index]
{
get => (TsCDaItemProperty)base[index];
set => base[index] = value;
}
#endregion
#region IOpcResult Members
/// <summary>
/// The error id for the result of an operation on an item.
/// </summary>
public OpcResult Result
{
get => result_;
set => result_ = value;
}
/// <summary>
/// Vendor specific diagnostic information (not the localized error text).
/// </summary>
public string DiagnosticInfo { get; set; }
#endregion
#region ICollection Members
/// <summary>
/// Copies the objects to an Array, starting at a the specified index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination for the objects.</param>
/// <param name="index">The zero-based index in the Array at which copying begins.</param>
public void CopyTo(TsCDaItemProperty[] array, int index)
{
CopyTo((Array)array, index);
}
#endregion
#region IList Members
/// <summary>
/// Inserts an item to the IList at the specified position.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The Object to insert into the IList. </param>
public void Insert(int index, TsCDaItemProperty value)
{
Insert(index, (object)value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the IList.
/// </summary>
/// <param name="value">The Object to remove from the IList.</param>
public void Remove(TsCDaItemProperty value)
{
Remove((object)value);
}
/// <summary>
/// Determines whether the IList contains a specific value.
/// </summary>
/// <param name="value">The Object to locate in the IList.</param>
/// <returns>true if the Object is found in the IList; otherwise, false.</returns>
public bool Contains(TsCDaItemProperty value)
{
return Contains((object)value);
}
/// <summary>
/// Determines the index of a specific item in the IList.
/// </summary>
/// <param name="value">The Object to locate in the IList.</param>
/// <returns>The index of value if found in the list; otherwise, -1.</returns>
public int IndexOf(TsCDaItemProperty value)
{
return IndexOf((object)value);
}
/// <summary>
/// Adds an item to the IList.
/// </summary>
/// <param name="value">The Object to add to the IList. </param>
/// <returns>The position into which the new element was inserted.</returns>
public int Add(TsCDaItemProperty value)
{
return Add((object)value);
}
#endregion
}
}

View File

@@ -0,0 +1,104 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// The results of an operation on a uniquely identifiable item.
/// </summary>
[Serializable]
public class TsCDaItemResult : TsCDaItem, IOpcResult
{
#region Fields
private OpcResult result_ = OpcResult.S_OK;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with default values.
/// </summary>
public TsCDaItemResult() { }
/// <summary>
/// Initializes the object with an ItemIdentifier object.
/// </summary>
public TsCDaItemResult(OpcItem item) : base(item) { }
/// <summary>
/// Initializes the object with an ItemIdentifier object and Result.
/// </summary>
public TsCDaItemResult(OpcItem item, OpcResult resultId)
: base(item)
{
Result = resultId;
}
/// <summary>
/// Initializes the object with an Item object.
/// </summary>
public TsCDaItemResult(TsCDaItem item) : base(item) { }
/// <summary>
/// Initializes the object with an Item object and Result.
/// </summary>
public TsCDaItemResult(TsCDaItem item, OpcResult resultId)
: base(item)
{
Result = resultId;
}
/// <summary>
/// Initializes object with the specified ItemResult object.
/// </summary>
public TsCDaItemResult(TsCDaItemResult item)
: base(item)
{
if (item != null)
{
Result = item.Result;
DiagnosticInfo = item.DiagnosticInfo;
}
}
#endregion
#region IOpcResult Members
/// <summary>
/// The error id for the result of an operation on an property.
/// </summary>
public OpcResult Result
{
get => result_;
set => result_ = value;
}
/// <summary>
/// Vendor specific diagnostic information (not the localized error text).
/// </summary>
public string DiagnosticInfo { get; set; }
#endregion
}
}

View File

@@ -0,0 +1,137 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Contains the value for a single item.
/// </summary>
[Serializable]
public class TsCDaItemValue : OpcItem
{
#region Fields
private TsCDaQuality daQuality_ = TsCDaQuality.Bad;
private DateTime timestamp_ = DateTime.MinValue;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with default values.
/// </summary>
public TsCDaItemValue() { }
/// <summary>
/// Initializes the object with and ItemIdentifier object.
/// </summary>
public TsCDaItemValue(OpcItem item)
{
if (item == null)
{
return;
}
ItemName = item.ItemName;
ItemPath = item.ItemPath;
ClientHandle = item.ClientHandle;
ServerHandle = item.ServerHandle;
}
/// <summary>
/// Initializes the object with the specified item name.
/// </summary>
public TsCDaItemValue(string itemName)
: base(itemName)
{
}
/// <summary>
/// Initializes object with the specified ItemValue object.
/// </summary>
public TsCDaItemValue(TsCDaItemValue item)
: base(item)
{
if (item == null)
{
return;
}
Value = OpcConvert.Clone(item.Value);
Quality = item.Quality;
QualitySpecified = item.QualitySpecified;
Timestamp = item.Timestamp;
TimestampSpecified = item.TimestampSpecified;
}
#endregion
#region Properties
/// <summary>
/// The item value.
/// </summary>
public object Value { get; set; }
/// <summary>
/// The quality of the item value.
/// </summary>
public TsCDaQuality Quality
{
get => daQuality_;
set => daQuality_ = value;
}
/// <summary>
/// Whether the quality is specified.
/// </summary>
public bool QualitySpecified { get; set; }
/// <summary>
/// The timestamp for the item value.
/// The <see cref="ApplicationInstance.TimeAsUtc">ApplicationInstance.TimeAsUtc</see> property defines
/// the time format (UTC or local time).
/// </summary>
public DateTime Timestamp
{
get => timestamp_;
set => timestamp_ = value;
}
/// <summary>
/// Whether the timestamp is specified.
/// </summary>
public bool TimestampSpecified { get; set; }
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public override object Clone()
{
var clone = (TsCDaItemValue)MemberwiseClone();
clone.Value = OpcConvert.Clone(Value);
return clone;
}
#endregion
}
}

View File

@@ -0,0 +1,123 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// The results of an operation on a uniquely identifiable item value.
/// </summary>
[Serializable]
public class TsCDaItemValueResult : TsCDaItemValue, IOpcResult
{
#region Fields
private OpcResult result_ = OpcResult.S_OK;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with default values.
/// </summary>
public TsCDaItemValueResult() { }
/// <summary>
/// Initializes the object with an ItemIdentifier object.
/// </summary>
public TsCDaItemValueResult(OpcItem item) : base(item) { }
/// <summary>
/// Initializes the object with an ItemValue object.
/// </summary>
public TsCDaItemValueResult(TsCDaItemValue item) : base(item) { }
/// <summary>
/// Initializes object with the specified ItemValueResult object.
/// </summary>
public TsCDaItemValueResult(TsCDaItemValueResult item)
: base(item)
{
if (item != null)
{
Result = item.Result;
DiagnosticInfo = item.DiagnosticInfo;
}
}
/// <summary>
/// Initializes the object with the specified item name and result code.
/// </summary>
public TsCDaItemValueResult(string itemName, OpcResult resultId)
: base(itemName)
{
Result = resultId;
}
/// <summary>
/// Initializes the object with the specified item name, result code and diagnostic info.
/// </summary>
public TsCDaItemValueResult(string itemName, OpcResult resultId, string diagnosticInfo)
: base(itemName)
{
Result = resultId;
DiagnosticInfo = diagnosticInfo;
}
/// <summary>
/// Initialize object with the specified ItemIdentifier and result code.
/// </summary>
public TsCDaItemValueResult(OpcItem item, OpcResult resultId)
: base(item)
{
Result = resultId;
}
/// <summary>
/// Initializes the object with the specified ItemIdentifier, result code and diagnostic info.
/// </summary>
public TsCDaItemValueResult(OpcItem item, OpcResult resultId, string diagnosticInfo)
: base(item)
{
Result = resultId;
DiagnosticInfo = diagnosticInfo;
}
#endregion
#region IOpcResult Members
/// <summary>
/// The error id for the result of an operation on an property.
/// </summary>
public OpcResult Result
{
get => result_;
set => result_ = value;
}
/// <summary>
/// Vendor specific diagnostic information (not the localized error text).
/// </summary>
public string DiagnosticInfo { get; set; }
#endregion
}
}

View File

@@ -0,0 +1,44 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// <para>Defines the possible limit status bits.</para>
/// <para>The Limit Field is valid regardless of the Quality and Substatus. In some
/// cases such as Sensor Failure it can provide useful diagnostic information.</para>
/// </summary>
public enum TsDaLimitBits
{
/// <summary>The value is free to move up or down</summary>
None = 0x0,
/// <summary>The value has pegged at some lower limit</summary>
Low = 0x1,
/// <summary>The value has pegged at some high limit</summary>
High = 0x2,
/// <summary>The value is a constant and cannot move</summary>
Constant = 0x3
}
}

View File

@@ -0,0 +1,328 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Defines identifiers for well-known properties.
/// </summary>
public class TsDaProperty
{
#region Data Access Properties
/// <summary><para>Item Canonical DataType</para></summary>
public static readonly TsDaPropertyID DATATYPE = new TsDaPropertyID("dataType", 1, OpcNamespace.OPC_DATA_ACCESS);
/// <summary><para>Item Value</para></summary>
/// <remarks>
/// Note the type of value returned is as indicated by the "Item Canonical DataType"
/// and depends on the item. This will behave like a read from DEVICE.
/// </remarks>
public static readonly TsDaPropertyID VALUE = new TsDaPropertyID("value", 2, OpcNamespace.OPC_DATA_ACCESS);
/// <summary><para>Item Quality</para></summary>
/// <remarks>(OPCQUALITY stored in an I2). This will behave like a read from DEVICE.</remarks>
public static readonly TsDaPropertyID QUALITY = new TsDaPropertyID("quality", 3, OpcNamespace.OPC_DATA_ACCESS);
/// <summary><para>Item Timestamp</para></summary>
/// <remarks>
/// (will be converted from FILETIME). This will behave like a read from
/// DEVICE.
/// </remarks>
public static readonly TsDaPropertyID TIMESTAMP = new TsDaPropertyID("timestamp", 4, OpcNamespace.OPC_DATA_ACCESS);
/// <summary><para>Item Access Rights</para></summary>
/// <remarks>(OPCACCESSRIGHTS stored in an I4)</remarks>
public static readonly TsDaPropertyID ACCESSRIGHTS = new TsDaPropertyID("accessRights", 5, OpcNamespace.OPC_DATA_ACCESS);
/// <summary><para>Server Scan Rate</para></summary>
/// <remarks>
/// In Milliseconds. This represents the fastest rate at which the server could
/// obtain data from the underlying data source. The nature of this source is not defined
/// but is typically a DCS system, a SCADA system, a PLC via a COMM port or network, a
/// Device Network, etc. This value generally represents the best case fastest
/// RequestedUpdateRate which could be used if this item were added to an OPCGroup.<br/>
/// The accuracy of this value (the ability of the server to attain best case
/// performance) can be greatly affected by system load and other factors.
/// </remarks>
public static readonly TsDaPropertyID SCANRATE = new TsDaPropertyID("scanRate", 6, OpcNamespace.OPC_DATA_ACCESS);
/// <remarks>
/// <para>Indicate the type of Engineering Units (EU) information (if any) contained in
/// EUINFO.</para>
/// <list type="bullet">
/// <item>
/// 0 - No EU information available (EUINFO will be VT_EMPTY).
/// </item>
/// <item>
/// 1 - Analog - EUINFO will contain a SAFEARRAY of exactly two doubles
/// (VT_ARRAY | VT_R8) corresponding to the LOW and HI EU range.
/// </item>
/// <item>2 - Enumerated - EUINFO will contain a SAFEARRAY of strings (VT_ARRAY |
/// VT_BSTR) which contains a list of strings (Example: “OPEN”, “CLOSE”, “IN
/// TRANSIT”, etc.) corresponding to sequential numeric values (0, 1, 2,
/// etc.)</item>
/// </list>
/// </remarks>
/// <summary><para>Item EU Type</para></summary>
public static readonly TsDaPropertyID EUTYPE = new TsDaPropertyID("euType", 7, OpcNamespace.OPC_DATA_ACCESS);
/// <summary><para>Item EUInfo</para></summary>
/// <value>
/// <para>
/// If EUTYPE is “Analog” EUINFO will contain a SAFEARRAY of exactly two doubles
/// (VT_ARRAY | VT_R8) corresponding to the LOW and HI EU range.
/// </para>
/// <para>If EUTYPE is “Enumerated” - EUINFO will contain a SAFEARRAY of strings
/// (VT_ARRAY | VT_BSTR) which contains a list of strings (Example: “OPEN”, “CLOSE”,
/// “IN TRANSIT”, etc.) corresponding to sequential numeric values (0, 1, 2,
/// etc.)</para>
/// </value>
public static readonly TsDaPropertyID EUINFO = new TsDaPropertyID("euInfo", 8, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>EU Units</para>
/// <para>e.g. "DEGC" or "GALLONS"</para>
/// </summary>
public static readonly TsDaPropertyID ENGINEERINGUINTS = new TsDaPropertyID("engineeringUnits", 100, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Item Description</para>
/// <para>e.g. "Evaporator 6 Coolant Temp"</para>
/// </summary>
public static readonly TsDaPropertyID DESCRIPTION = new TsDaPropertyID("description", 101, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>High EU</para>
/// <para>Present only for 'analog' data. This represents the highest value likely to
/// be obtained in normal operation and is intended for such use as automatically
/// scaling a bargraph display.</para>
/// <para>e.g. 1400.0</para>
/// </summary>
public static readonly TsDaPropertyID HIGHEU = new TsDaPropertyID("highEU", 102, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Low EU</para>
/// <para>Present only for 'analog' data. This represents the lowest value likely to be
/// obtained in normal operation and is intended for such use as automatically scaling
/// a bargraph display.</para>
/// <para>e.g. -200.0</para>
/// </summary>
public static readonly TsDaPropertyID LOWEU = new TsDaPropertyID("lowEU", 103, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>High Instrument Range</para>
/// <para>Present only for analog data. This represents the highest value that can be
/// returned by the instrument.</para>
/// <para>e.g. 9999.9</para>
/// </summary>
public static readonly TsDaPropertyID HIGHIR = new TsDaPropertyID("highIR", 104, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Low Instrument Range</para>
/// <para>Present only for analog data. This represents the lowest value that can be
/// returned by the instrument.</para>
/// <para>e.g. -9999.9</para>
/// </summary>
public static readonly TsDaPropertyID LOWIR = new TsDaPropertyID("lowIR", 105, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Contact Close Label</para>
/// <para>Present only for discrete' data. This represents a string to be associated
/// with this contact when it is in the closed (non-zero) state</para>
/// <para>e.g. "RUN", "CLOSE", "ENABLE", "SAFE" ,etc.</para>
/// </summary>
public static readonly TsDaPropertyID CLOSELABEL = new TsDaPropertyID("closeLabel", 106, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Contact Open Label</para>
/// <para>Present only for discrete' data. This represents a string to be associated
/// with this contact when it is in the open (zero) state</para>
/// <para>e.g. "STOP", "OPEN", "DISABLE", "UNSAFE" ,etc.</para>
/// </summary>
public static readonly TsDaPropertyID OPENLABEL = new TsDaPropertyID("openLabel", 107, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Item Timezone</para>
/// <para>The difference in minutes between the items UTC Timestamp and the local time
/// in which the item value was obtained.</para>
/// </summary>
/// <remarks>
/// See the OPCGroup TimeBias property. Also see the WIN32 TIME_ZONE_INFORMATION
/// structure.
/// </remarks>
public static readonly TsDaPropertyID TIMEZONE = new TsDaPropertyID("timeZone", 108, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Condition Status</para>
/// <para>The current alarm or condition status associated with the Item<br/>
/// e.g. "NORMAL", "ACTIVE", "HI ALARM", etc</para>
/// </summary>
public static readonly TsDaPropertyID CONDITION_STATUS = new TsDaPropertyID("conditionStatus", 300, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Alarm Quick Help</para>
/// <para>A short text string providing a brief set of instructions for the operator to
/// follow when this alarm occurs.</para>
/// </summary>
public static readonly TsDaPropertyID ALARM_QUICK_HELP = new TsDaPropertyID("alarmQuickHelp", 301, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Alarm Area List</para>
/// <para>An array of stings indicating the plant or alarm areas which include this
/// ItemID.</para>
/// </summary>
public static readonly TsDaPropertyID ALARM_AREA_LIST = new TsDaPropertyID("alarmAreaList", 302, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Primary Alarm Area</para>
/// <para>A string indicating the primary plant or alarm area including this
/// ItemID</para>
/// </summary>
public static readonly TsDaPropertyID PRIMARY_ALARM_AREA = new TsDaPropertyID("primaryAlarmArea", 303, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Condition Logic</para>
/// <para>An arbitrary string describing the test being performed.</para>
/// <para>e.g. "High Limit Exceeded" or "TAG.PV &gt;= TAG.HILIM"</para>
/// </summary>
public static readonly TsDaPropertyID CONDITION_LOGIC = new TsDaPropertyID("conditionLogic", 304, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Limit Exceeded</para>
/// <para>For multistate alarms, the condition exceeded</para>
/// <para>e.g. HIHI, HI, LO, LOLO</para>
/// </summary>
public static readonly TsDaPropertyID LIMIT_EXCEEDED = new TsDaPropertyID("limitExceeded", 305, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>Deadband</summary>
public static readonly TsDaPropertyID DEADBAND = new TsDaPropertyID("deadband", 306, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>HiHi limit</summary>
public static readonly TsDaPropertyID HIHI_LIMIT = new TsDaPropertyID("hihiLimit", 307, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>Hi Limit</summary>
public static readonly TsDaPropertyID HI_LIMIT = new TsDaPropertyID("hiLimit", 308, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>Lo Limit</summary>
public static readonly TsDaPropertyID LO_LIMIT = new TsDaPropertyID("loLimit", 309, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>LoLo Limit</summary>
public static readonly TsDaPropertyID LOLO_LIMIT = new TsDaPropertyID("loloLimit", 310, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>Rate of Change Limit</summary>
public static readonly TsDaPropertyID RATE_CHANGE_LIMIT = new TsDaPropertyID("rangeOfChangeLimit", 311, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>Deviation Limit</summary>
public static readonly TsDaPropertyID DEVIATION_LIMIT = new TsDaPropertyID("deviationLimit", 312, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Sound File</para>
/// <para>e.g. C:\MEDIA\FIC101.WAV, or .MID</para>
/// </summary>
public static readonly TsDaPropertyID SOUNDFILE = new TsDaPropertyID("soundFile", 313, OpcNamespace.OPC_DATA_ACCESS);
#endregion
#region Complex Data Properties
/// <summary>
/// <para>Type System ID</para>
/// <para>Complex Data Property</para>
/// </summary>
public static readonly TsDaPropertyID TYPE_SYSTEM_ID = new TsDaPropertyID("typeSystemID", 600, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Dictionary ID</para>
/// <para>Complex Data Property</para>
/// </summary>
public static readonly TsDaPropertyID DICTIONARY_ID = new TsDaPropertyID("dictionaryID", 601, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Type ID</para>
/// <para>Complex Data Property</para>
/// </summary>
public static readonly TsDaPropertyID TYPE_ID = new TsDaPropertyID("typeID", 602, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Dictionary</para>
/// <para>Complex Data Property</para>
/// </summary>
public static readonly TsDaPropertyID DICTIONARY = new TsDaPropertyID("dictionary", 603, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Type description</para>
/// <para>Complex Data Property</para>
/// </summary>
public static readonly TsDaPropertyID TYPE_DESCRIPTION = new TsDaPropertyID("typeDescription", 604, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Consistency Window</para>
/// <para>Complex Data Property</para>
/// </summary>
public static readonly TsDaPropertyID CONSISTENCY_WINDOW = new TsDaPropertyID("consistencyWindow", 605, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Write Behaviour</para>
/// <para>Complex Data Property, defaults to “All or Nothing” if the complex data item
/// is writable. Not used for Read-Only items.</para>
/// </summary>
public static readonly TsDaPropertyID WRITE_BEHAVIOR = new TsDaPropertyID("writeBehavior", 606, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Unconverted Item ID</para>
/// <para>Complex Data Property, the ID of the item that exposes the same complex data
/// value in its native format. This property is mandatory for items that implement
/// complex data type conversions.</para>
/// </summary>
public static readonly TsDaPropertyID UNCONVERTED_ITEM_ID = new TsDaPropertyID("unconvertedItemID", 607, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Unfiltered Item ID</para>
/// <para>Complex Data Property, the ID the item that exposes the same complex data
/// value without any data filter or with the default query applied to it. It is
/// mandatory for items that implement complex data filters or queries.</para>
/// </summary>
public static readonly TsDaPropertyID UNFILTERED_ITEM_ID = new TsDaPropertyID("unfilteredItemID", 608, OpcNamespace.OPC_DATA_ACCESS);
/// <summary>
/// <para>Data Filter Value</para>
/// <para>Complex Data Property, the value of the filter that is currently applied to
/// the item. It is mandatory for items that implement complex data filters or
/// queries.</para>
/// </summary>
public static readonly TsDaPropertyID DATA_FILTER_VALUE = new TsDaPropertyID("dataFilterValue", 609, OpcNamespace.OPC_DATA_ACCESS);
#endregion
#region XML Data Access Properties
/// <remarks/>
public static readonly TsDaPropertyID MINIMUM_VALUE = new TsDaPropertyID("minimumValue", 109, OpcNamespace.OPC_DATA_ACCESS);
/// <remarks/>
public static readonly TsDaPropertyID MAXIMUM_VALUE = new TsDaPropertyID("maximumValue", 110, OpcNamespace.OPC_DATA_ACCESS);
/// <remarks/>
public static readonly TsDaPropertyID VALUE_PRECISION = new TsDaPropertyID("valuePrecision", 111, OpcNamespace.OPC_DATA_ACCESS);
#endregion
}
}

View File

@@ -0,0 +1,200 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
using System.Reflection;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Describes an item property.
/// </summary>
[Serializable]
public class TsDaPropertyDescription
{
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with the specified values.
/// </summary>
public TsDaPropertyDescription(TsDaPropertyID id, Type type, string name)
{
ID = id;
Type = type;
Name = name;
}
#endregion
#region Properties
/// <summary>
/// The unique identifier for the property.
/// </summary>
public TsDaPropertyID ID { get; set; }
/// <summary>
/// The .NET data type for the property.
/// </summary>
public Type Type { get; set; }
/// <summary>
/// The short description defined in the OPC specifications.
/// </summary>
public string Name { get; set; }
#endregion
#region Data Access Properties
/// <remarks/>
public static readonly TsDaPropertyDescription DATATYPE = new TsDaPropertyDescription(TsDaProperty.DATATYPE, typeof(Type), "Item Canonical DataType");
/// <remarks/>
public static readonly TsDaPropertyDescription VALUE = new TsDaPropertyDescription(TsDaProperty.VALUE, typeof(object), "Item Value");
/// <remarks/>
public static readonly TsDaPropertyDescription QUALITY = new TsDaPropertyDescription(TsDaProperty.QUALITY, typeof(TsCDaQuality), "Item Quality");
/// <remarks/>
public static readonly TsDaPropertyDescription TIMESTAMP = new TsDaPropertyDescription(TsDaProperty.TIMESTAMP, typeof(DateTime), "Item Timestamp");
/// <remarks/>
public static readonly TsDaPropertyDescription ACCESSRIGHTS = new TsDaPropertyDescription(TsDaProperty.ACCESSRIGHTS, typeof(TsDaAccessRights), "Item Access Rights");
/// <remarks/>
public static readonly TsDaPropertyDescription SCANRATE = new TsDaPropertyDescription(TsDaProperty.SCANRATE, typeof(float), "Server Scan Rate");
/// <remarks/>
public static readonly TsDaPropertyDescription EUTYPE = new TsDaPropertyDescription(TsDaProperty.EUTYPE, typeof(TsDaEuType), "Item EU Type");
/// <remarks/>
public static readonly TsDaPropertyDescription EUINFO = new TsDaPropertyDescription(TsDaProperty.EUINFO, typeof(string[]), "Item EU Info");
/// <remarks/>
public static readonly TsDaPropertyDescription ENGINEERINGUINTS = new TsDaPropertyDescription(TsDaProperty.ENGINEERINGUINTS, typeof(string), "EU Units");
/// <remarks/>
public static readonly TsDaPropertyDescription DESCRIPTION = new TsDaPropertyDescription(TsDaProperty.DESCRIPTION, typeof(string), "Item Description");
/// <remarks/>
public static readonly TsDaPropertyDescription HIGHEU = new TsDaPropertyDescription(TsDaProperty.HIGHEU, typeof(double), "High EU");
/// <remarks/>
public static readonly TsDaPropertyDescription LOWEU = new TsDaPropertyDescription(TsDaProperty.LOWEU, typeof(double), "Low EU");
/// <remarks/>
public static readonly TsDaPropertyDescription HIGHIR = new TsDaPropertyDescription(TsDaProperty.HIGHIR, typeof(double), "High Instrument Range");
/// <remarks/>
public static readonly TsDaPropertyDescription LOWIR = new TsDaPropertyDescription(TsDaProperty.LOWIR, typeof(double), "Low Instrument Range");
/// <remarks/>
public static readonly TsDaPropertyDescription CLOSELABEL = new TsDaPropertyDescription(TsDaProperty.CLOSELABEL, typeof(string), "Contact Close Label");
/// <remarks/>
public static readonly TsDaPropertyDescription OPENLABEL = new TsDaPropertyDescription(TsDaProperty.OPENLABEL, typeof(string), "Contact Open Label");
/// <remarks/>
public static readonly TsDaPropertyDescription TIMEZONE = new TsDaPropertyDescription(TsDaProperty.TIMEZONE, typeof(int), "Timezone");
/// <remarks/>
public static readonly TsDaPropertyDescription CONDITION_STATUS = new TsDaPropertyDescription(TsDaProperty.CONDITION_STATUS, typeof(string), "Condition Status");
/// <remarks/>
public static readonly TsDaPropertyDescription ALARM_QUICK_HELP = new TsDaPropertyDescription(TsDaProperty.ALARM_QUICK_HELP, typeof(string), "Alarm Quick Help");
/// <remarks/>
public static readonly TsDaPropertyDescription ALARM_AREA_LIST = new TsDaPropertyDescription(TsDaProperty.ALARM_AREA_LIST, typeof(string), "Alarm Area List");
/// <remarks/>
public static readonly TsDaPropertyDescription PRIMARY_ALARM_AREA = new TsDaPropertyDescription(TsDaProperty.PRIMARY_ALARM_AREA, typeof(string), "Primary Alarm Area");
/// <remarks/>
public static readonly TsDaPropertyDescription CONDITION_LOGIC = new TsDaPropertyDescription(TsDaProperty.CONDITION_LOGIC, typeof(string), "Condition Logic");
/// <remarks/>
public static readonly TsDaPropertyDescription LIMIT_EXCEEDED = new TsDaPropertyDescription(TsDaProperty.LIMIT_EXCEEDED, typeof(string), "Limit Exceeded");
/// <remarks/>
public static readonly TsDaPropertyDescription DEADBAND = new TsDaPropertyDescription(TsDaProperty.DEADBAND, typeof(double), "Deadband");
/// <remarks/>
public static readonly TsDaPropertyDescription HIHI_LIMIT = new TsDaPropertyDescription(TsDaProperty.HIHI_LIMIT, typeof(double), "HiHi Limit");
/// <remarks/>
public static readonly TsDaPropertyDescription HI_LIMIT = new TsDaPropertyDescription(TsDaProperty.HI_LIMIT, typeof(double), "Hi Limit");
/// <remarks/>
public static readonly TsDaPropertyDescription LO_LIMIT = new TsDaPropertyDescription(TsDaProperty.LO_LIMIT, typeof(double), "Lo Limit");
/// <remarks/>
public static readonly TsDaPropertyDescription LOLO_LIMIT = new TsDaPropertyDescription(TsDaProperty.LOLO_LIMIT, typeof(double), "LoLo Limit");
/// <remarks/>
public static readonly TsDaPropertyDescription RATE_CHANGE_LIMIT = new TsDaPropertyDescription(TsDaProperty.RATE_CHANGE_LIMIT, typeof(double), "Rate of Change Limit");
/// <remarks/>
public static readonly TsDaPropertyDescription DEVIATION_LIMIT = new TsDaPropertyDescription(TsDaProperty.DEVIATION_LIMIT, typeof(double), "Deviation Limit");
/// <remarks/>
public static readonly TsDaPropertyDescription SOUNDFILE = new TsDaPropertyDescription(TsDaProperty.SOUNDFILE, typeof(string), "Sound File");
#endregion
#region Complex Data Properties
/// <remarks/>
public static readonly TsDaPropertyDescription TYPE_SYSTEM_ID = new TsDaPropertyDescription(TsDaProperty.TYPE_SYSTEM_ID, typeof(string), "Type System ID");
/// <remarks/>
public static readonly TsDaPropertyDescription DICTIONARY_ID = new TsDaPropertyDescription(TsDaProperty.DICTIONARY_ID, typeof(string), "Dictionary ID");
/// <remarks/>
public static readonly TsDaPropertyDescription TYPE_ID = new TsDaPropertyDescription(TsDaProperty.TYPE_ID, typeof(string), "Type ID");
/// <remarks/>
public static readonly TsDaPropertyDescription DICTIONARY = new TsDaPropertyDescription(TsDaProperty.DICTIONARY, typeof(object), "Dictionary");
/// <remarks/>
public static readonly TsDaPropertyDescription TYPE_DESCRIPTION = new TsDaPropertyDescription(TsDaProperty.TYPE_DESCRIPTION, typeof(string), "Type Description");
/// <remarks/>
public static readonly TsDaPropertyDescription CONSISTENCY_WINDOW = new TsDaPropertyDescription(TsDaProperty.CONSISTENCY_WINDOW, typeof(string), "Consistency Window");
/// <remarks/>
public static readonly TsDaPropertyDescription WRITE_BEHAVIOR = new TsDaPropertyDescription(TsDaProperty.WRITE_BEHAVIOR, typeof(string), "Write Behavior");
/// <remarks/>
public static readonly TsDaPropertyDescription UNCONVERTED_ITEM_ID = new TsDaPropertyDescription(TsDaProperty.UNCONVERTED_ITEM_ID, typeof(string), "Unconverted Item ID");
/// <remarks/>
public static readonly TsDaPropertyDescription UNFILTERED_ITEM_ID = new TsDaPropertyDescription(TsDaProperty.UNFILTERED_ITEM_ID, typeof(string), "Unfiltered Item ID");
/// <remarks/>
public static readonly TsDaPropertyDescription DATA_FILTER_VALUE = new TsDaPropertyDescription(TsDaProperty.DATA_FILTER_VALUE, typeof(string), "Data Filter Value");
#endregion
#region Object Member Overrides
/// <summary>
/// Converts the description to a string.
/// </summary>
public override string ToString()
{
return Name;
}
#endregion
#region Public Methods
/// <summary>
/// Returns the description for the specified property.
/// </summary>
public static TsDaPropertyDescription Find(TsDaPropertyID id)
{
var fields = typeof(TsDaPropertyDescription).GetFields(BindingFlags.Static | BindingFlags.Public);
foreach (var field in fields)
{
var property = (TsDaPropertyDescription)field.GetValue(typeof(TsDaPropertyDescription));
if (property.ID == id)
{
return property;
}
}
return null;
}
/// <summary>
/// Returns an array of all well-known property descriptions.
/// </summary>
public static TsDaPropertyDescription[] Enumerate()
{
var values = new ArrayList();
var fields = typeof(TsDaPropertyDescription).GetFields(BindingFlags.Static | BindingFlags.Public);
Array.ForEach(fields, field => values.Add(field.GetValue(typeof(TsDaPropertyDescription))));
return (TsDaPropertyDescription[])values.ToArray(typeof(TsDaPropertyDescription));
}
#endregion
}
}

View File

@@ -0,0 +1,198 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Xml;
using System.Runtime.Serialization;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Contains a unique identifier for a property.
/// </summary>
[Serializable]
public struct TsDaPropertyID : ISerializable
{
#region Names Class
/// <summary>
/// A set of names for fields used in serialization.
/// </summary>
private class Names
{
internal const string Name = "NA";
internal const string Namespace = "NS";
internal const string Code = "CO";
}
#endregion
#region Fields
private int code_;
private XmlQualifiedName qualifiedName_;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes a property identified by a qualified name.
/// </summary>
public TsDaPropertyID(XmlQualifiedName name) { qualifiedName_ = name; code_ = 0; }
/// <summary>
/// Initializes a property identified by an integer.
/// </summary>
public TsDaPropertyID(int code) { qualifiedName_ = null; code_ = code; }
/// <summary>
/// Initializes a property identified by a property description.
/// </summary>
public TsDaPropertyID(string name, int code, string ns) { qualifiedName_ = new XmlQualifiedName(name, ns); code_ = code; }
///<remarks>
/// During deserialization, SerializationInfo is passed to the class using the constructor provided for this purpose. Any visibility
/// constraints placed on the constructor are ignored when the object is deserialized; so you can mark the class as public,
/// protected, internal, or private. However, it is best practice to make the constructor protected unless the class is sealed, in which case
/// the constructor should be marked private. The constructor should also perform thorough input validation. To avoid misuse by malicious code,
/// the constructor should enforce the same security checks and permissions required to obtain an instance of the class using any other
/// constructor.
/// </remarks>
/// <summary>
/// Constructs a server by de-serializing its OpcUrl from the stream.
/// </summary>
private TsDaPropertyID(SerializationInfo info, StreamingContext context)
{
var enumerator = info.GetEnumerator();
var name = "";
var ns = "";
enumerator.Reset();
while (enumerator.MoveNext())
{
if (enumerator.Current.Name.Equals(Names.Name))
{
name = (string)enumerator.Current.Value;
continue;
}
if (enumerator.Current.Name.Equals(Names.Namespace))
{
ns = (string)enumerator.Current.Value;
}
}
qualifiedName_ = new XmlQualifiedName(name, ns);
code_ = (int)info.GetValue(Names.Code, typeof(int));
}
#endregion
#region Properties
/// <summary>
/// Used for properties identified by a qualified name.
/// </summary>
public XmlQualifiedName Name => qualifiedName_;
/// <summary>
/// Used for properties identified by a integer.
/// </summary>
public int Code => code_;
#endregion
#region Public Methods
/// <summary>
/// Returns true if the objects are equal.
/// </summary>
public static bool operator ==(TsDaPropertyID a, TsDaPropertyID b)
{
return a.Equals(b);
}
/// <summary>
/// Returns true if the objects are not equal.
/// </summary>
public static bool operator !=(TsDaPropertyID a, TsDaPropertyID b)
{
return !a.Equals(b);
}
#endregion
#region Serialization Functions
/// <summary>
/// Serializes a server into a stream.
/// </summary>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (qualifiedName_ != null)
{
info.AddValue(Names.Name, qualifiedName_.Name);
info.AddValue(Names.Namespace, qualifiedName_.Namespace);
}
info.AddValue(Names.Code, code_);
}
#endregion
#region Object Member Overrides
/// <summary>
/// Returns true if the target object is equal to the object.
/// </summary>
public override bool Equals(object target)
{
if (target != null && target.GetType() == typeof(TsDaPropertyID))
{
var propertyId = (TsDaPropertyID)target;
// compare by integer if both specify valid integers.
if (propertyId.Code != 0 && Code != 0)
{
return (propertyId.Code == Code);
}
// compare by name if both specify valid names.
if (propertyId.Name != null && Name != null)
{
return (propertyId.Name == Name);
}
}
return false;
}
/// <summary>
/// Returns a useful hash code for the object.
/// </summary>
public override int GetHashCode()
{
if (Code != 0) return Code.GetHashCode();
if (Name != null) return Name.GetHashCode();
return base.GetHashCode();
}
/// <summary>
/// Converts the property id to a string.
/// </summary>
public override string ToString()
{
if (Name != null && Code != 0) return $"{Name.Name} ({Code})";
if (Name != null) return Name.Name;
if (Code != 0) return $"{Code}";
return "";
}
#endregion
}
}

View File

@@ -0,0 +1,251 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Contains the quality field for an item value.
/// </summary>
[Serializable]
public struct TsCDaQuality
{
#region Fields
private TsDaQualityBits qualityBits_;
private TsDaLimitBits limitBits_;
private byte vendorBits_;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with the specified quality.
/// </summary>
public TsCDaQuality(TsDaQualityBits quality)
{
qualityBits_ = quality;
limitBits_ = TsDaLimitBits.None;
vendorBits_ = 0;
}
/// <summary>
/// Initializes the object from the contents of a 16 bit integer.
/// </summary>
public TsCDaQuality(short code)
{
qualityBits_ = (TsDaQualityBits)(code & (short)TsDaQualityMasks.QualityMask);
limitBits_ = (TsDaLimitBits)(code & (short)TsDaQualityMasks.LimitMask);
vendorBits_ = (byte)((code & (short)TsDaQualityMasks.VendorMask) >> 8);
}
#endregion
#region Properties
/// <summary>
/// The value in the quality bits field.
/// </summary>
public TsDaQualityBits QualityBits
{
get => qualityBits_;
set => qualityBits_ = value;
}
/// <summary>
/// The value in the limit bits field.
/// </summary>
public TsDaLimitBits LimitBits
{
get => limitBits_;
set => limitBits_ = value;
}
/// <summary>
/// The value in the quality bits field.
/// </summary>
public byte VendorBits
{
get => vendorBits_;
set => vendorBits_ = value;
}
/// <summary>
/// A 'good' quality value.
/// </summary>
public static readonly TsCDaQuality Good = new TsCDaQuality(TsDaQualityBits.Good);
/// <summary>
/// An 'bad' quality value.
/// </summary>
public static readonly TsCDaQuality Bad = new TsCDaQuality(TsDaQualityBits.Bad);
#endregion
#region Public Methods
/// <summary>
/// Returns the quality as a 16 bit integer.
/// </summary>
public short GetCode()
{
ushort code = 0;
code |= (ushort)QualityBits;
code |= (ushort)LimitBits;
code |= (ushort)(VendorBits << 8);
return (code <= short.MaxValue) ? (short)code : (short)-((ushort.MaxValue + 1 - code));
}
/// <summary>
/// Initializes the quality from a 16 bit integer.
/// </summary>
public void SetCode(short code)
{
qualityBits_ = (TsDaQualityBits)(code & (short)TsDaQualityMasks.QualityMask);
limitBits_ = (TsDaLimitBits)(code & (short)TsDaQualityMasks.LimitMask);
vendorBits_ = (byte)((code & (short)TsDaQualityMasks.VendorMask) >> 8);
}
/// <summary>
/// Returns true if the objects are equal.
/// </summary>
public static bool operator ==(TsCDaQuality a, TsCDaQuality b)
{
return a.Equals(b);
}
/// <summary>
/// Returns true if the objects are not equal.
/// </summary>
public static bool operator !=(TsCDaQuality a, TsCDaQuality b)
{
return !a.Equals(b);
}
#endregion
#region Object Member Overrides
/// <summary>
/// Converts a quality to a string with the format: 'quality[limit]:vendor'.
/// </summary>
public override string ToString()
{
string text = null;
switch (QualityBits)
{
case TsDaQualityBits.Good:
text += "(Good";
break;
case TsDaQualityBits.GoodLocalOverride:
text += "(Good:Local Override";
break;
case TsDaQualityBits.Bad:
text += "(Bad";
break;
case TsDaQualityBits.BadConfigurationError:
text += "(Bad:Configuration Error";
break;
case TsDaQualityBits.BadNotConnected:
text += "(Bad:Not Connected";
break;
case TsDaQualityBits.BadDeviceFailure:
text += "(Bad:Device Failure";
break;
case TsDaQualityBits.BadSensorFailure:
text += "(Bad:Sensor Failure";
break;
case TsDaQualityBits.BadLastKnownValue:
text += "(Bad:Last Known Value";
break;
case TsDaQualityBits.BadCommFailure:
text += "(Bad:Communication Failure";
break;
case TsDaQualityBits.BadOutOfService:
text += "(Bad:Out of Service";
break;
case TsDaQualityBits.BadWaitingForInitialData:
text += "(Bad:Waiting for Initial Data";
break;
case TsDaQualityBits.Uncertain:
text += "(Uncertain";
break;
case TsDaQualityBits.UncertainLastUsableValue:
text += "(Uncertain:Last Usable Value";
break;
case TsDaQualityBits.UncertainSensorNotAccurate:
text += "(Uncertain:Sensor not Accurate";
break;
case TsDaQualityBits.UncertainEUExceeded:
text += "(Uncertain:Engineering Unit exceeded";
break;
case TsDaQualityBits.UncertainSubNormal:
text += "(Uncertain:Sub Normal";
break;
}
if (LimitBits != TsDaLimitBits.None)
{
text += $":[{LimitBits.ToString()}]";
}
else
{
text += ":Not Limited";
}
if (VendorBits != 0)
{
text += $":{VendorBits,0:X})";
}
else
{
text += ")";
}
return text;
}
/// <summary>
/// Determines whether the specified Object is equal to the current Quality
/// </summary>
public override bool Equals(object target)
{
if (target == null || target.GetType() != typeof(TsCDaQuality)) return false;
var quality = (TsCDaQuality)target;
if (QualityBits != quality.QualityBits) return false;
if (LimitBits != quality.LimitBits) return false;
if (VendorBits != quality.VendorBits) return false;
return true;
}
/// <summary>
/// Returns hash code for the current Quality.
/// </summary>
public override int GetHashCode()
{
return GetCode();
}
#endregion
}
}

View File

@@ -0,0 +1,114 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// <para>Defines the possible quality status bits.</para>
/// <para>These flags represent the quality state for an item's data value. This is
/// intended to be similar to but slightly simpler than the Field-bus Data Quality
/// Specification (section 4.4.1 in the H1 Final Specifications). This design makes it
/// fairly easy for both servers and client applications to determine how much
/// functionality they want to implement.</para>
/// </summary>
public enum TsDaQualityBits
{
/// <summary>The Quality of the value is Good.</summary>
Good = 0x000000C0,
/// <summary>The value has been Overridden. Typically this means the input has been disconnected and a manually entered value has been 'forced'.</summary>
GoodLocalOverride = 0x000000D8,
/// <summary>The value is bad but no specific reason is known.</summary>
Bad = 0x00000000,
/// <summary>
/// There is some server specific problem with the configuration. For example the
/// item in question has been deleted from the configuration.
/// </summary>
BadConfigurationError = 0x00000004,
/// <summary>
/// The input is required to be logically connected to something but is not. This
/// quality may reflect that no value is available at this time, for reasons like the value
/// may have not been provided by the data source.
/// </summary>
BadNotConnected = 0x00000008,
/// <summary>A device failure has been detected.</summary>
BadDeviceFailure = 0x0000000c,
/// <summary>
/// A sensor failure had been detected (the Limits field can provide additional
/// diagnostic information in some situations).
/// </summary>
BadSensorFailure = 0x00000010,
/// <summary>
/// Communications have failed. However, the last known value is available. Note that
/// the age of the value may be determined from the time stamp in the item state.
/// </summary>
BadLastKnownValue = 0x00000014,
/// <summary>Communications have failed. There is no last known value is available.</summary>
BadCommFailure = 0x00000018,
/// <summary>
/// The block is off scan or otherwise locked. This quality is also used when the
/// active state of the item or the subscription containing the item is InActive.
/// </summary>
BadOutOfService = 0x0000001C,
/// <summary>
/// After Items are added to a subscription, it may take some time for the server to
/// actually obtain values for these items. In such cases the client might perform a read
/// (from cache), or establish a ConnectionPoint based subscription and/or execute a
/// Refresh on such a subscription before the values are available. This sub-status is only
/// available from OPC DA 3.0 or newer servers.
/// </summary>
BadWaitingForInitialData = 0x00000020,
/// <summary>There is no specific reason why the value is uncertain.</summary>
Uncertain = 0x00000040,
/// <summary>
/// Whatever was writing this value has stopped doing so. The returned value should
/// be regarded as stale. Note that this differs from a BAD value with sub-status
/// badLastKnownValue (Last Known Value). That status is associated specifically with a
/// detectable communications error on a fetched value. This error is associated with the
/// failure of some external source to put something into the value within an acceptable
/// period of time. Note that the age of the value can be determined from the time stamp
/// in the item state.
/// </summary>
UncertainLastUsableValue = 0x00000044,
/// <summary>
/// Either the value has pegged at one of the sensor limits (in which case the
/// limit field should be set to low or high) or the sensor is otherwise known to be out of
/// calibration via some form of internal diagnostics (in which case the limit field should
/// be none).
/// </summary>
UncertainSensorNotAccurate = 0x00000050,
/// <summary>
/// The returned value is outside the limits defined for this parameter. Note that in
/// this case (per the Field-bus Specification) the Limits field indicates which limit has
/// been exceeded but does NOT necessarily imply that the value cannot move farther out of
/// range.
/// </summary>
UncertainEUExceeded = 0x00000054,
/// <summary>
/// The value is derived from multiple sources and has less than the required number
/// of Good sources.
/// </summary>
UncertainSubNormal = 0x00000058
}
}

View File

@@ -0,0 +1,40 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Defines bit masks for the quality.
/// </summary>
public enum TsDaQualityMasks : int
{
/// <summary>Quality related bits</summary>
QualityMask = +0x00FC,
/// <summary>Limit related bits</summary>
LimitMask = +0x0003,
/// <summary>Vendor specific bits</summary>
VendorMask = -0x00FD
}
}

View File

@@ -0,0 +1,70 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Describes the state of a subscription.
/// </summary>
[Serializable]
public class TsCDaRequest : IOpcRequest
{
#region Fields
private ITsCDaSubscription subscription_;
private object handle_;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object with a subscription and a unique id.
/// </summary>
public TsCDaRequest(ITsCDaSubscription subscription, object handle)
{
subscription_ = subscription;
handle_ = handle;
}
#endregion
#region Properties
/// <summary>
/// The subscription processing the request.
/// </summary>
public ITsCDaSubscription Subscription => subscription_;
/// <summary>
/// An unique identifier, assigned by the client, for the request.
/// </summary>
public object Handle => handle_;
#endregion
#region Public Methods
/// <summary>
/// Cancels the request, if possible.
/// </summary>
public void Cancel(TsCDaCancelCompleteEventHandler callback) { subscription_.Cancel(this, callback); }
#endregion
}
}

View File

@@ -0,0 +1,75 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// Filters applied by the server before returning item results.
/// </summary>
[Flags]
public enum TsCDaResultFilter
{
/// <summary>
/// Include the ItemName in the ItemIdentifier if bit is set.
/// </summary>
ItemName = 0x01,
/// <summary>
/// Include the ItemPath in the ItemIdentifier if bit is set.
/// </summary>
ItemPath = 0x02,
/// <summary>
/// Include the ClientHandle in the ItemIdentifier if bit is set.
/// </summary>
ClientHandle = 0x04,
/// <summary>
/// Include the Timestamp in the ItemValue if bit is set.
/// </summary>
ItemTime = 0x08,
/// <summary>
/// Include verbose, localized error text with result if bit is set.
/// </summary>
ErrorText = 0x10,
/// <summary>
/// Include additional diagnostic information with result if bit is set.
/// </summary>
DiagnosticInfo = 0x20,
/// <summary>
/// Include the ItemName and Timestamp if bit is set.
/// </summary>
Minimal = ItemName | ItemTime,
/// <summary>
/// Include all information in the results if bit is set.
/// </summary>
All = 0x3F
}
}

View File

@@ -0,0 +1,500 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Runtime.Serialization;
using System.Collections.Generic;
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// This class is the main interface to access an OPC Data Access server.
/// </summary>
[Serializable]
public class TsCDaServer : OpcServer, ITsDaServer
{
#region Names Class
/// <summary>A set of names for fields used in serialization.</summary>
private class Names
{
internal const string Filters = "Filters";
internal const string Subscriptions = "Subscription";
}
#endregion
#region Fields
/// <summary>
/// A list of subscriptions for the server.
/// </summary>
private TsCDaSubscriptionCollection subscriptions_ = new TsCDaSubscriptionCollection();
/// <summary>
/// The local copy of the result filters.
/// </summary>
private int filters_ = (int)TsCDaResultFilter.All | (int)TsCDaResultFilter.ClientHandle;
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Initializes the object.
/// </summary>
public TsCDaServer()
{
}
/// <summary>
/// Initializes the object with a factory and a default OpcUrl.
/// </summary>
/// <param name="factory">The OpcFactory used to connect to remote servers.</param>
/// <param name="url">The network address of a remote server.</param>
public TsCDaServer(OpcFactory factory, OpcUrl url)
:
base(factory, url)
{
}
/// <summary>
/// Constructs a server by de-serializing its OpcUrl from the stream.
/// </summary>
protected TsCDaServer(SerializationInfo info, StreamingContext context)
:
base(info, context)
{
filters_ = (int)info.GetValue(Names.Filters, typeof(int));
var subscriptions = (TsCDaSubscription[])info.GetValue(Names.Subscriptions, typeof(TsCDaSubscription[]));
if (subscriptions != null)
{
Array.ForEach(subscriptions, subscription => subscriptions_.Add(subscription));
}
}
#endregion
#region Properties
/// <summary>
/// Returns an array of all subscriptions for the server.
/// </summary>
public TsCDaSubscriptionCollection Subscriptions => subscriptions_;
/// <summary>
/// The current result filters applied by the server.
/// </summary>
public int Filters => filters_;
#endregion
#region Class properties serialization helpers
/// <summary>Serializes a server into a stream.</summary>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(Names.Filters, filters_);
TsCDaSubscription[] subscriptions = null;
if (subscriptions_.Count > 0)
{
subscriptions = new TsCDaSubscription[subscriptions_.Count];
for (var ii = 0; ii < subscriptions.Length; ii++)
{
subscriptions[ii] = subscriptions_[ii];
}
}
info.AddValue(Names.Subscriptions, subscriptions);
}
#endregion
#region Public Methods
/// <summary>Returns an unconnected copy of the server with the same OpcUrl.</summary>
public override object Clone()
{
// clone the base object.
var clone = (TsCDaServer)base.Clone();
// clone subscriptions.
if (clone.subscriptions_ != null)
{
var subscriptions = new TsCDaSubscriptionCollection();
foreach (TsCDaSubscription subscription in clone.subscriptions_)
{
subscriptions.Add(subscription.Clone());
}
clone.subscriptions_ = subscriptions;
}
// return clone.
return clone;
}
/// <summary>Connects to the server with the specified OpcUrl and credentials.</summary>
/// <exception caption="OpcResultException Class" cref="OpcResultException">If an OPC specific error occur this exception is raised. The Result field includes then the OPC specific code.</exception>
/// <param name="url">The network address of the remote server.</param>
/// <param name="connectData">Any protocol configuration or user authentication information.</param>
public override void Connect(OpcUrl url, OpcConnectData connectData)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
// connect to server.
base.Connect(url, connectData);
// all done if no subscriptions.
if (subscriptions_ == null)
{
return;
}
// create subscriptions (should only happen if server has been deserialized).
var subscriptions = new TsCDaSubscriptionCollection();
foreach (TsCDaSubscription template in subscriptions_)
{
// create subscription for template.
try
{
subscriptions.Add(EstablishSubscription(template));
}
catch
{
// Ignore exceptions here
}
}
// save new set of subscriptions.
subscriptions_ = subscriptions;
}
/// <summary>Disconnects from the server and releases all network resources.</summary>
public override void Disconnect()
{
if (Server == null) throw new NotConnectedException();
// dispose of all subscriptions first.
if (subscriptions_ != null)
{
foreach (TsCDaSubscription subscription in subscriptions_)
{
subscription.Dispose();
}
subscriptions_ = null;
}
// disconnect from server.
base.Disconnect();
}
/// <summary>Returns the filters applied by the server to any item results returned to the client.</summary>
/// <returns>A bit mask indicating which fields should be returned in any item results.</returns>
public int GetResultFilters()
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (Server == null) throw new NotConnectedException();
// update local cache.
filters_ = ((ITsDaServer)Server).GetResultFilters();
// return filters.
return filters_;
}
/// <summary>Sets the filters applied by the server to any item results returned to the client.</summary>
/// <param name="filters">A bit mask indicating which fields should be returned in any item results.</param>
public void SetResultFilters(int filters)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (Server == null) throw new NotConnectedException();
// set filters on server.
((ITsDaServer)Server).SetResultFilters(filters);
// cache updated filters.
filters_ = filters;
}
/// <summary>Returns the current server status.</summary>
/// <returns>The current server status.</returns>
public OpcServerStatus GetServerStatus()
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (Server == null) throw new NotConnectedException();
var status = ((ITsDaServer)Server).GetServerStatus();
if (status != null)
{
if (status.StatusInfo == null)
{
status.StatusInfo = GetString($"serverState.{status.ServerState}");
}
}
else
{
throw new NotConnectedException();
}
return status;
}
/// <summary>Reads the current values for a set of items.</summary>
/// <returns>The results of the read operation for each item.</returns>
/// <requirements>OPC XML-DA Server or OPC Data Access Server V3.x</requirements>
/// <param name="items">The set of items to read.</param>
public TsCDaItemValueResult[] Read(TsCDaItem[] items)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (Server == null) throw new NotConnectedException();
return ((ITsDaServer)Server).Read(items);
}
/// <summary>Writes the value, quality and timestamp for a set of items.</summary>
/// <returns>The results of the write operation for each item.</returns>
/// <requirements>OPC XML-DA Server or OPC Data Access Server V3.x</requirements>
/// <param name="items">The set of item values to write.</param>
public OpcItemResult[] Write(TsCDaItemValue[] items)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (Server == null) throw new NotConnectedException();
return ((ITsDaServer)Server).Write(items);
}
/// <summary>
/// Creates a new subscription.
/// </summary>
/// <returns>The new subscription object.</returns>
/// <requirements>OPC XML-DA Server or OPC Data Access Server V2.x / V3.x</requirements>
/// <param name="state">The initial state of the subscription.</param>
public virtual ITsCDaSubscription CreateSubscription(TsCDaSubscriptionState state)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (state == null) throw new ArgumentNullException(nameof(state));
if (Server == null) throw new NotConnectedException();
// create subscription on server.
var subscription = ((ITsDaServer)Server).CreateSubscription(state);
// set filters.
subscription.SetResultFilters(filters_);
// append new subscription to existing list.
var subscriptions = new TsCDaSubscriptionCollection();
if (subscriptions_ != null)
{
foreach (TsCDaSubscription value in subscriptions_)
{
subscriptions.Add(value);
}
}
subscriptions.Add(CreateSubscription(subscription));
// save new subscription list.
subscriptions_ = subscriptions;
// return new subscription.
return subscriptions_[subscriptions_.Count - 1];
}
/// <summary>
/// Creates a new instance of the appropriate subscription object.
/// </summary>
/// <param name="subscription">The remote subscription object.</param>
protected virtual TsCDaSubscription CreateSubscription(ITsCDaSubscription subscription)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
return new TsCDaSubscription(this, subscription);
}
/// <summary>Cancels a subscription and releases all resources allocated for it.</summary>
/// <requirements>OPC XML-DA Server or OPC Data Access Server V2.x / V3.x</requirements>
/// <param name="subscription">The subscription to cancel.</param>
public virtual void CancelSubscription(ITsCDaSubscription subscription)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (subscription == null) throw new ArgumentNullException(nameof(subscription));
if (Server == null) throw new NotConnectedException();
// validate argument.
if (!typeof(TsCDaSubscription).IsInstanceOfType(subscription))
{
throw new ArgumentException(@"Incorrect object type.", nameof(subscription));
}
if (!Equals(((TsCDaSubscription)subscription).Server))
{
throw new ArgumentException(@"Server subscription.", nameof(subscription));
}
// search for subscription in list of subscriptions.
var subscriptions = new TsCDaSubscriptionCollection();
foreach (TsCDaSubscription current in subscriptions_)
{
if (!subscription.Equals(current))
{
subscriptions.Add(current);
}
}
// check if subscription was not found.
if (subscriptions.Count == subscriptions_.Count)
{
throw new ArgumentException(@"Subscription not found.", nameof(subscription));
}
// remove subscription from list of subscriptions.
subscriptions_ = subscriptions;
// cancel subscription on server.
((ITsDaServer)Server).CancelSubscription(((TsCDaSubscription)subscription).Subscription);
}
/// <summary>Fetches all the children of the root branch that meet the filter criteria.</summary>
/// <returns>The set of elements found.</returns>
/// <requirements>OPC Data Access Server V2.x / V3.x</requirements>
/// <param name="filters">The filters to use to limit the set of child elements returned.</param>
private TsCDaBrowseElement[] Browse(
TsCDaBrowseFilters filters)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (Server == null) throw new NotConnectedException();
TsCDaBrowsePosition position;
var elementsList = new List<TsCDaBrowseElement>();
var elements = ((ITsDaServer)Server).Browse(null, filters, out position);
if (elements != null)
{
Browse(elements, filters, ref elementsList);
}
return elementsList.ToArray();
}
private void Browse(TsCDaBrowseElement[] elements, TsCDaBrowseFilters filters, ref List<TsCDaBrowseElement> elementsList)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
TsCDaBrowsePosition position;
foreach (var element in elements)
{
if (element.HasChildren)
{
var itemId = new OpcItem(element.ItemPath, element.ItemName);
var childElements = ((ITsDaServer)Server).Browse(itemId, filters, out position);
if (childElements != null)
{
Browse(childElements, filters, ref elementsList);
}
}
else
{
elementsList.Add(element);
}
}
}
/// <summary>Fetches the children of a branch that meet the filter criteria.</summary>
/// <returns>The set of elements found.</returns>
/// <requirements>OPC XML-DA Server or OPC Data Access Server V2.x / V3.x</requirements>
/// <param name="itemId">The identifier of branch which is the target of the search.</param>
/// <param name="filters">The filters to use to limit the set of child elements returned.</param>
/// <param name="position">An object used to continue a browse that could not be completed.</param>
public TsCDaBrowseElement[] Browse(
OpcItem itemId,
TsCDaBrowseFilters filters,
out TsCDaBrowsePosition position)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (Server == null) throw new NotConnectedException();
return ((ITsDaServer)Server).Browse(itemId, filters, out position);
}
/// <summary>Continues a browse operation with previously specified search criteria.</summary>
/// <returns>The set of elements found.</returns>
/// <requirements>OPC XML-DA Server or OPC Data Access Server V2.x / V3.x</requirements>
/// <param name="position">An object containing the browse operation state information.</param>
public TsCDaBrowseElement[] BrowseNext(ref TsCDaBrowsePosition position)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (Server == null) throw new NotConnectedException();
return ((ITsDaServer)Server).BrowseNext(ref position);
}
/// <summary>Returns the item properties for a set of items.</summary>
/// <param name="itemIds">A list of item identifiers.</param>
/// <param name="propertyIDs">A list of properties to fetch for each item.</param>
/// <param name="returnValues">Whether the property values should be returned with the properties.</param>
/// <returns>A list of properties for each item.</returns>
public TsCDaItemPropertyCollection[] GetProperties(
OpcItem[] itemIds,
TsDaPropertyID[] propertyIDs,
bool returnValues)
{
LicenseHandler.ValidateFeatures(LicenseHandler.ProductFeature.DataAccess);
if (Server == null) throw new NotConnectedException();
return ((ITsDaServer)Server).GetProperties(itemIds, propertyIDs, returnValues);
}
#endregion
#region Private Methods
/// <summary>
/// Establishes a subscription based on the template provided.
/// </summary>
private TsCDaSubscription EstablishSubscription(TsCDaSubscription template)
{
// create subscription.
var subscription = new TsCDaSubscription(this, ((ITsDaServer)Server).CreateSubscription(template.State));
// set filters.
subscription.SetResultFilters(template.Filters);
// add items.
try
{
subscription.AddItems(template.Items);
}
catch
{
subscription.Dispose();
subscription = null;
}
// return new subscription.
return subscription;
}
#endregion
}
}

View File

@@ -0,0 +1,68 @@
#region Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0: https://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2023 Technosoftware GmbH. All rights reserved
#region Using Directives
#endregion
namespace Technosoftware.DaAeHdaClient.Da
{
/// <summary>
/// The set of possible server states.
/// </summary>
public enum TsCDaServerState
{
/// <summary>
/// The server state is not known.
/// </summary>
Unknown,
/// <summary>
/// The server is running normally.
/// </summary>
Running,
/// <summary>
/// The server is not functioning due to a fatal error.
/// </summary>
Failed,
/// <summary>
/// The server cannot load its configuration information.
/// </summary>
NoConfig,
/// <summary>
/// The server has halted all communication with the underlying hardware.
/// </summary>
Suspended,
/// <summary>
/// The server is disconnected from the underlying hardware.
/// </summary>
Test,
/// <summary>
/// The server cannot communicate with the underlying hardware.
/// </summary>
CommFault
}
}

Some files were not shown because too many files have changed in this diff Show More