Aggiunta cli test applications x remote debug

This commit is contained in:
Samuele Locatelli
2024-12-23 15:41:12 +01:00
parent 10dad6681a
commit 99e9238ce8
32 changed files with 1503 additions and 1076 deletions
@@ -37,6 +37,7 @@ using System.Windows.Forms;
using Opc.Ua;
using Opc.Ua.Client;
using System.IO;
using System.Text.RegularExpressions;
namespace Opc.Ua.Client.Controls
{
@@ -108,11 +109,24 @@ namespace Opc.Ua.Client.Controls
public void ReadAttributes(NodeId nodeId, bool showProperties)
{
AttributesLV.Items.Clear();
// effettua check preliminarei folder out...
string outPath = Path.Combine(Directory.GetCurrentDirectory(), "trace");
string expFile = Path.Combine(outPath, $"{nodeId}.txt".Replace("=", "_").Replace(";", "_"));
string nodePath = $"{nodeId}.txt".Replace("=", "_")
.Replace(";", "_")
.Replace("|", "_")
.Replace("/", "_")
.Replace("\\", "_")
.Replace("(", "_")
.Replace(")", "_");
// 2023.11.25 fix caratteri invalidi
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
nodePath = r.Replace(nodePath, "");
string expFile = Path.Combine(outPath, nodePath);
Directory.CreateDirectory(outPath);
StringBuilder sb = new StringBuilder();
@@ -210,7 +224,12 @@ namespace Opc.Ua.Client.Controls
// export finale su file proprietà...
string nodeData = sb.ToString();
File.WriteAllText(expFile, nodeData);
try
{
File.WriteAllText(expFile, nodeData);
}
catch
{ }
}
#endregion
@@ -38,6 +38,7 @@ using System.Text;
using System.Windows.Forms;
using Opc.Ua;
using Opc.Ua.Client;
using System.Threading;
namespace Opc.Ua.Client.Controls
{
@@ -332,6 +333,9 @@ namespace Opc.Ua.Client.Controls
/// </summary>
private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e)
{
// metto una pausa casuale 50-150 ms...
Random rnd = new Random();
Thread.Sleep(rnd.Next(50, 150));
try
{
m_selectedNodeId = null;
@@ -1,23 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(AppTargetFrameWorks)</TargetFrameworks>
<AssemblyName>ConsoleReferenceSubscriber</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>ConsoleReferenceSubscriber</PackageId>
<Company>OPC Foundation</Company>
<Description>.NET Console Reference Subscriber</Description>
<Copyright>Copyright © 2004-2020 OPC Foundation, Inc</Copyright>
<RootNamespace>Quickstarts.ConsoleReferenceSubscriber</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Mono.Options" Version="6.12.0.148" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Stack\Opc.Ua.Core\Opc.Ua.Core.csproj" />
<ProjectReference Include="..\..\Libraries\Opc.Ua.PubSub\Opc.Ua.PubSub.csproj" />
</ItemGroup>
</Project>
@@ -1,952 +0,0 @@
/* ========================================================================
* Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.Threading;
using Mono.Options;
using Opc.Ua;
using Opc.Ua.PubSub;
using Opc.Ua.PubSub.Configuration;
using Opc.Ua.PubSub.Encoding;
using Opc.Ua.PubSub.PublishedData;
using Opc.Ua.PubSub.Transport;
namespace Quickstarts.ConsoleReferenceSubscriber
{
public static class Program
{
public const ushort NamespaceIndexSimple = 2;
public const ushort NamespaceIndexAllTypes = 3;
// constant DateTime that represents the initial time when the metadata for the configuration was created
private static DateTime kTimeOfConfiguration = new DateTime(2021, 5, 1, 0, 0, 0, DateTimeKind.Utc);
private const string kDisplaySeparator = "------------------------------------------------";
private static object m_lock = new object();
public static void Main(string[] args)
{
Console.WriteLine("OPC UA Console Reference Subscriber");
// command line options
bool showHelp = false;
bool useMqttJson = true;
bool useMqttUadp = false;
bool useUdpUadp = false;
string subscriberUrl = null;
Mono.Options.OptionSet options = new Mono.Options.OptionSet {
{ "h|help", "Show usage information", v => showHelp = v != null },
{ "m|mqtt_json", "Use MQTT with Json encoding Profile. This is the default option.", v => useMqttJson = v != null },
{ "p|mqtt_uadp", "Use MQTT with UADP encoding Profile.", v => useMqttUadp = v != null },
{ "u|udp_uadp", "Use UDP with UADP encoding Profile", v => useUdpUadp = v != null },
{ "url|subscriber_url=", "Subscriber Url Address", v => subscriberUrl = v},
};
IList<string> extraArgs = null;
try
{
extraArgs = options.Parse(args);
if (extraArgs.Count > 0)
{
foreach (string extraArg in extraArgs)
{
Console.WriteLine("Error: Unknown option: {0}", extraArg);
showHelp = true;
}
}
}
catch (OptionException e)
{
Console.WriteLine(e.Message);
showHelp = true;
}
if (showHelp)
{
Console.WriteLine("Usage: dotnet ConsoleReferenceSubscriber.dll [OPTIONS]");
Console.WriteLine();
Console.WriteLine("Options:");
options.WriteOptionDescriptions(Console.Out);
return;
}
try
{
InitializeLog();
PubSubConfigurationDataType pubSubConfiguration = null;
if (useUdpUadp)
{
// set default UDP Subscriber Url to local multicast if not sent in args.
if (string.IsNullOrEmpty(subscriberUrl))
{
subscriberUrl = "opc.udp://239.0.0.1:4840";
}
// Create configuration using UDP protocol and UADP Encoding
pubSubConfiguration = CreateSubscriberConfiguration_UdpUadp(subscriberUrl);
Console.WriteLine("The Pubsub Connection was initialized using UDP & UADP Profile.");
}
else
{
// set default MQTT Broker Url to localhost if not sent in args.
if (string.IsNullOrEmpty(subscriberUrl))
{
subscriberUrl = "mqtt://localhost:1883";
}
if (useMqttUadp)
{
// Create configuration using MQTT protocol and UADP Encoding
pubSubConfiguration = CreateSubscriberConfiguration_MqttUadp(subscriberUrl);
Console.WriteLine("The PubSub Connection was initialized using MQTT & UADP Profile.");
}
else
{
// Create configuration using MQTT protocol and JSON Encoding
pubSubConfiguration = CreateSubscriberConfiguration_MqttJson(subscriberUrl);
Console.WriteLine("The PubSub Connection was initialized using MQTT & JSON Profile.");
}
}
// Create the UA Publisher application
using (UaPubSubApplication uaPubSubApplication = UaPubSubApplication.Create(pubSubConfiguration))
{
// Subscribte to RawDataReceived event
uaPubSubApplication.RawDataReceived += UaPubSubApplication_RawDataReceived;
// Subscribte to DataReceived event
uaPubSubApplication.DataReceived += UaPubSubApplication_DataReceived;
// Subscribte to MetaDataReceived event
uaPubSubApplication.MetaDataReceived += UaPubSubApplication_MetaDataDataReceived;
uaPubSubApplication.ConfigurationUpdating += UaPubSubApplication_ConfigurationUpdating;
// Start the publisher
uaPubSubApplication.Start();
Console.WriteLine("Subscriber Started. Press Ctrl-C to exit...");
ManualResetEvent quitEvent = new ManualResetEvent(false);
try
{
Console.CancelKeyPress += (sender, eArgs) => {
quitEvent.Set();
eArgs.Cancel = true;
};
}
catch
{
}
// wait for timeout or Ctrl-C
quitEvent.WaitOne();
}
Console.WriteLine("Program ended.");
Console.WriteLine("Press any key to finish...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
#region Private Methods
/// <summary>
/// Handler for <see cref="UaPubSubApplication.RawDataReceived" /> event.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void UaPubSubApplication_RawDataReceived(object sender, RawDataReceivedEventArgs e)
{
lock (m_lock)
{
Console.WriteLine("RawDataReceived bytes:{0}, Source:{1}, TransportProtocol:{2}, MessageMapping:{3}",
e.Message.Length, e.Source, e.TransportProtocol, e.MessageMapping);
Console.WriteLine(kDisplaySeparator);
}
}
/// <summary>
/// Handler for <see cref="UaPubSubApplication.DataReceived" /> event.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void UaPubSubApplication_DataReceived(object sender, SubscribedDataEventArgs e)
{
lock (m_lock)
{
Console.WriteLine("DataReceived event:");
if (e.NetworkMessage is UadpNetworkMessage)
{
Console.WriteLine("UADP Network DataSetMessage ({0} DataSets): Source={1}, SequenceNumber={2}",
e.NetworkMessage.DataSetMessages.Count, e.Source, ((UadpNetworkMessage)e.NetworkMessage).SequenceNumber);
}
else if (e.NetworkMessage is JsonNetworkMessage)
{
Console.WriteLine("JSON Network DataSetMessage ({0} DataSets): Source={1}, MessageId={2}",
e.NetworkMessage.DataSetMessages.Count, e.Source, ((JsonNetworkMessage)e.NetworkMessage).MessageId);
}
foreach (UaDataSetMessage dataSetMessage in e.NetworkMessage.DataSetMessages)
{
DataSet dataSet = dataSetMessage.DataSet;
Console.WriteLine("\tDataSet.Name={0}, DataSetWriterId={1}, SequenceNumber={2}", dataSet.Name, dataSet.DataSetWriterId, dataSetMessage.SequenceNumber);
for (int i = 0; i < dataSet.Fields.Length; i++)
{
Console.WriteLine("\t\tTargetNodeId:{0}, Attribute:{1}, Value:{2}",
dataSet.Fields[i].TargetNodeId, dataSet.Fields[i].TargetAttribute, dataSetMessage.DataSet.Fields[i].Value);
}
}
Console.WriteLine(kDisplaySeparator);
}
}
/// <summary>
/// Handler for <see cref="UaPubSubApplication.MetaDataDataReceived" /> event.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void UaPubSubApplication_MetaDataDataReceived(object sender, SubscribedDataEventArgs e)
{
lock (m_lock)
{
Console.WriteLine("MetaDataDataReceived event:");
if (e.NetworkMessage is JsonNetworkMessage)
{
Console.WriteLine("JSON Network MetaData Message: Source={0}, PublisherId={1}, DataSetWriterId={2} Fields count={3}\n",
e.Source,
((JsonNetworkMessage)e.NetworkMessage).PublisherId,
((JsonNetworkMessage)e.NetworkMessage).DataSetWriterId,
e.NetworkMessage.DataSetMetaData.Fields.Count);
}
if (e.NetworkMessage is UadpNetworkMessage)
{
Console.WriteLine("UADP Network MetaData Message: Source={0}, PublisherId={1}, DataSetWriterId={2} Fields count={3}\n",
e.Source,
((UadpNetworkMessage)e.NetworkMessage).PublisherId,
((UadpNetworkMessage)e.NetworkMessage).DataSetWriterId,
e.NetworkMessage.DataSetMetaData.Fields.Count);
}
Console.WriteLine("\tMetaData.Name={0}, MajorVersion={1} MinorVersion={2}",
e.NetworkMessage.DataSetMetaData.Name,
e.NetworkMessage.DataSetMetaData.ConfigurationVersion.MajorVersion,
e.NetworkMessage.DataSetMetaData.ConfigurationVersion.MinorVersion);
foreach (FieldMetaData metaDataField in e.NetworkMessage.DataSetMetaData.Fields)
{
Console.WriteLine("\t\t{0, -20} DataType:{1, 10}, ValueRank:{2, 5}", metaDataField.Name, metaDataField.DataType, metaDataField.ValueRank);
}
Console.WriteLine(kDisplaySeparator);
}
}
/// <summary>
/// Handler for <see cref="UaPubSubApplication.ConfigurationUpdating"/>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void UaPubSubApplication_ConfigurationUpdating(object sender, ConfigurationUpdatingEventArgs e)
{
Console.WriteLine("The UaPubSubApplication.ConfigurationUpdating event was triggered for part: {0} for {1}, With new value: {2}",
e.ChangedProperty, e.Parent.GetType().Name, e.NewValue.GetType().Name);
Console.WriteLine(kDisplaySeparator);
}
/// <summary>
/// Creates a Subscriber PubSubConfiguration object for UDP & UADP programmatically.
/// </summary>
/// <returns></returns>
private static PubSubConfigurationDataType CreateSubscriberConfiguration_UdpUadp(string urlAddress)
{
// Define a PubSub connection with PublisherId 1
PubSubConnectionDataType pubSubConnection1 = new PubSubConnectionDataType();
pubSubConnection1.Name = "Subscriber Connection UDP UADP";
pubSubConnection1.Enabled = true;
pubSubConnection1.PublisherId = (UInt16)1;
pubSubConnection1.TransportProfileUri = Profiles.PubSubUdpUadpTransport;
NetworkAddressUrlDataType address = new NetworkAddressUrlDataType();
// Specify the local Network interface name to be used
// e.g. address.NetworkInterface = "Ethernet";
// Leave empty to subscribe on all available local interfaces.
address.NetworkInterface = String.Empty;
address.Url = urlAddress;
pubSubConnection1.Address = new ExtensionObject(address);
// configure custoom DicoveryAddress for Dicovery messages
pubSubConnection1.TransportSettings = new ExtensionObject() {
Body = new DatagramConnectionTransportDataType() {
DiscoveryAddress = new ExtensionObject() {
Body = new NetworkAddressUrlDataType() {
Url = "opc.udp://224.0.2.15:4840"
}
}
}
};
#region Define ReaderGroup1
ReaderGroupDataType readerGroup1 = new ReaderGroupDataType();
readerGroup1.Name = "ReaderGroup 1";
readerGroup1.Enabled = true;
readerGroup1.MaxNetworkMessageSize = 1500;
readerGroup1.MessageSettings = new ExtensionObject(new ReaderGroupMessageDataType());
readerGroup1.TransportSettings = new ExtensionObject(new ReaderGroupTransportDataType());
#region Define DataSetReader 'Simple' for PublisherId = (UInt16)1, DataSetWriterId = 1
DataSetReaderDataType dataSetReaderSimple = new DataSetReaderDataType();
dataSetReaderSimple.Name = "Reader 1 UDP UADP";
dataSetReaderSimple.PublisherId = (UInt16)1;
dataSetReaderSimple.WriterGroupId = 0;
dataSetReaderSimple.DataSetWriterId = 1;
dataSetReaderSimple.Enabled = true;
dataSetReaderSimple.DataSetFieldContentMask = (uint)DataSetFieldContentMask.RawData;
dataSetReaderSimple.KeyFrameCount = 1;
dataSetReaderSimple.TransportSettings = new ExtensionObject(new DataSetReaderTransportDataType());
UadpDataSetReaderMessageDataType uadpDataSetReaderMessage = new UadpDataSetReaderMessageDataType() {
GroupVersion = 0,
NetworkMessageNumber = 0,
NetworkMessageContentMask = (uint)(uint)(UadpNetworkMessageContentMask.PublisherId
| UadpNetworkMessageContentMask.GroupHeader
| UadpNetworkMessageContentMask.WriterGroupId
| UadpNetworkMessageContentMask.GroupVersion
| UadpNetworkMessageContentMask.NetworkMessageNumber
| UadpNetworkMessageContentMask.SequenceNumber),
DataSetMessageContentMask = (uint)(UadpDataSetMessageContentMask.Status | UadpDataSetMessageContentMask.SequenceNumber),
};
dataSetReaderSimple.MessageSettings = new ExtensionObject(uadpDataSetReaderMessage);
// Create and set DataSetMetaData for DataSet Simple
DataSetMetaDataType simpleMetaData = CreateDataSetMetaDataSimple();
dataSetReaderSimple.DataSetMetaData = simpleMetaData;
// Create and set SubscribedDataSet
TargetVariablesDataType subscribedDataSet = new TargetVariablesDataType();
subscribedDataSet.TargetVariables = new FieldTargetDataTypeCollection();
foreach (var fieldMetaData in simpleMetaData.Fields)
{
subscribedDataSet.TargetVariables.Add(new FieldTargetDataType() {
DataSetFieldId = fieldMetaData.DataSetFieldId,
TargetNodeId = new NodeId(fieldMetaData.Name, NamespaceIndexSimple),
AttributeId = Attributes.Value,
OverrideValueHandling = OverrideValueHandling.OverrideValue,
OverrideValue = new Variant(TypeInfo.GetDefaultValue(fieldMetaData.DataType, (int)ValueRanks.Scalar))
});
}
dataSetReaderSimple.SubscribedDataSet = new ExtensionObject(subscribedDataSet);
#endregion
readerGroup1.DataSetReaders.Add(dataSetReaderSimple);
#region Define DataSetReader 'AllTypes' for PublisherId = (UInt16)1, DataSetWriterId = 2
DataSetReaderDataType dataSetReaderAllTypes = new DataSetReaderDataType();
dataSetReaderAllTypes.Name = "Reader 2 UDP UADP";
dataSetReaderAllTypes.PublisherId = (UInt16)1;
dataSetReaderAllTypes.WriterGroupId = 0;
dataSetReaderAllTypes.DataSetWriterId = 2;
dataSetReaderAllTypes.Enabled = true;
dataSetReaderAllTypes.DataSetFieldContentMask = (uint)DataSetFieldContentMask.RawData;
dataSetReaderAllTypes.KeyFrameCount = 1;
dataSetReaderAllTypes.TransportSettings = new ExtensionObject(new DataSetReaderTransportDataType());
uadpDataSetReaderMessage = new UadpDataSetReaderMessageDataType() {
GroupVersion = 0,
NetworkMessageNumber = 0,
NetworkMessageContentMask = (uint)(uint)(UadpNetworkMessageContentMask.PublisherId
| UadpNetworkMessageContentMask.GroupHeader
| UadpNetworkMessageContentMask.WriterGroupId
| UadpNetworkMessageContentMask.GroupVersion
| UadpNetworkMessageContentMask.NetworkMessageNumber
| UadpNetworkMessageContentMask.SequenceNumber),
DataSetMessageContentMask = (uint)(UadpDataSetMessageContentMask.Status | UadpDataSetMessageContentMask.SequenceNumber),
};
dataSetReaderAllTypes.MessageSettings = new ExtensionObject(uadpDataSetReaderMessage);
// Create and set DataSetMetaData for DataSet AllTypes
DataSetMetaDataType allTypesMetaData = CreateDataSetMetaDataAllTypes();
dataSetReaderAllTypes.DataSetMetaData = allTypesMetaData;
// Create and set SubscribedDataSet
subscribedDataSet = new TargetVariablesDataType();
subscribedDataSet.TargetVariables = new FieldTargetDataTypeCollection();
foreach (var fieldMetaData in allTypesMetaData.Fields)
{
subscribedDataSet.TargetVariables.Add(new FieldTargetDataType() {
DataSetFieldId = fieldMetaData.DataSetFieldId,
TargetNodeId = new NodeId(fieldMetaData.Name, NamespaceIndexAllTypes),
AttributeId = Attributes.Value,
OverrideValueHandling = OverrideValueHandling.OverrideValue,
OverrideValue = new Variant(TypeInfo.GetDefaultValue(fieldMetaData.DataType, (int)ValueRanks.Scalar))
});
}
dataSetReaderAllTypes.SubscribedDataSet = new ExtensionObject(subscribedDataSet);
#endregion
readerGroup1.DataSetReaders.Add(dataSetReaderAllTypes);
#endregion
pubSubConnection1.ReaderGroups.Add(readerGroup1);
//create pub sub configuration root object
PubSubConfigurationDataType pubSubConfiguration = new PubSubConfigurationDataType();
pubSubConfiguration.Connections = new PubSubConnectionDataTypeCollection()
{
pubSubConnection1
};
return pubSubConfiguration;
}
/// <summary>
/// Creates a Subscriber PubSubConfiguration object for MQTT & Json programmatically.
/// </summary>
/// <returns></returns>
private static PubSubConfigurationDataType CreateSubscriberConfiguration_MqttJson(string urlAddress)
{
// Define a PubSub connection with PublisherId 2
PubSubConnectionDataType pubSubConnection1 = new PubSubConnectionDataType();
pubSubConnection1.Name = "Subscriber Connection MQTT Json";
pubSubConnection1.Enabled = true;
pubSubConnection1.PublisherId = (UInt16)2;
pubSubConnection1.TransportProfileUri = Profiles.PubSubMqttJsonTransport;
NetworkAddressUrlDataType address = new NetworkAddressUrlDataType();
// Specify the local Network interface name to be used
// e.g. address.NetworkInterface = "Ethernet";
// Leave empty to subscribe on all available local interfaces.
address.NetworkInterface = String.Empty;
address.Url = urlAddress;
pubSubConnection1.Address = new ExtensionObject(address);
// Configure the mqtt specific configuration with the MQTTbroker
ITransportProtocolConfiguration mqttConfiguration = new MqttClientProtocolConfiguration(version: EnumMqttProtocolVersion.V500);
pubSubConnection1.ConnectionProperties = mqttConfiguration.ConnectionProperties;
string brokerQueueName = "Json_WriterGroup_1";
string brokerMetaData = "$Metadata";
#region Define ReaderGroup1
ReaderGroupDataType readerGroup1 = new ReaderGroupDataType();
readerGroup1.Name = "ReaderGroup 1";
readerGroup1.Enabled = true;
readerGroup1.MaxNetworkMessageSize = 1500;
readerGroup1.MessageSettings = new ExtensionObject(new ReaderGroupMessageDataType());
readerGroup1.TransportSettings = new ExtensionObject(new ReaderGroupTransportDataType());
#region Define DataSetReader1 'Simple' for PublisherId = (UInt16)2, DataSetWriterId = 1
DataSetReaderDataType dataSetReaderSimple = new DataSetReaderDataType();
dataSetReaderSimple.Name = "Reader 1 MQTT JSON Variant Encoding";
dataSetReaderSimple.PublisherId = (UInt16)2;
dataSetReaderSimple.WriterGroupId = 1;
dataSetReaderSimple.DataSetWriterId = 1;
dataSetReaderSimple.Enabled = true;
dataSetReaderSimple.DataSetFieldContentMask = (uint)DataSetFieldContentMask.None;// Variant encoding;
dataSetReaderSimple.KeyFrameCount = 3;
JsonDataSetReaderMessageDataType jsonDataSetReaderMessage = new JsonDataSetReaderMessageDataType() {
NetworkMessageContentMask = (uint)(uint)(JsonNetworkMessageContentMask.NetworkMessageHeader
| JsonNetworkMessageContentMask.DataSetMessageHeader
| JsonNetworkMessageContentMask.PublisherId
| JsonNetworkMessageContentMask.DataSetClassId
| JsonNetworkMessageContentMask.ReplyTo),
DataSetMessageContentMask = (uint)(JsonDataSetMessageContentMask.DataSetWriterId
| JsonDataSetMessageContentMask.MetaDataVersion
| JsonDataSetMessageContentMask.SequenceNumber
| JsonDataSetMessageContentMask.Status
| JsonDataSetMessageContentMask.Timestamp),
};
dataSetReaderSimple.MessageSettings = new ExtensionObject(jsonDataSetReaderMessage);
BrokerDataSetReaderTransportDataType brokerTransportSettings = new BrokerDataSetReaderTransportDataType() {
QueueName = brokerQueueName,
RequestedDeliveryGuarantee = BrokerTransportQualityOfService.BestEffort,
MetaDataQueueName = $"{brokerQueueName}/{brokerMetaData}",
};
dataSetReaderSimple.TransportSettings = new ExtensionObject(brokerTransportSettings);
// Create and set DataSetMetaData for DataSet Simple
DataSetMetaDataType simpleMetaData = CreateDataSetMetaDataSimple();
dataSetReaderSimple.DataSetMetaData = simpleMetaData;
// Create and set SubscribedDataSet
TargetVariablesDataType subscribedDataSet = new TargetVariablesDataType();
subscribedDataSet.TargetVariables = new FieldTargetDataTypeCollection();
foreach (var fieldMetaData in simpleMetaData.Fields)
{
subscribedDataSet.TargetVariables.Add(new FieldTargetDataType() {
DataSetFieldId = fieldMetaData.DataSetFieldId,
TargetNodeId = new NodeId(fieldMetaData.Name, NamespaceIndexSimple),
AttributeId = Attributes.Value,
OverrideValueHandling = OverrideValueHandling.OverrideValue,
OverrideValue = new Variant(TypeInfo.GetDefaultValue(fieldMetaData.DataType, (int)ValueRanks.Scalar))
});
}
dataSetReaderSimple.SubscribedDataSet = new ExtensionObject(subscribedDataSet);
#endregion
readerGroup1.DataSetReaders.Add(dataSetReaderSimple);
#region Define DataSetReader2 'AllTypes' for PublisherId = (UInt16)2, DataSetWriterId = 2
DataSetReaderDataType dataSetReaderAllTypes = new DataSetReaderDataType();
dataSetReaderAllTypes.Name = "Reader 2 MQTT JSON RawData Encoding";
dataSetReaderAllTypes.PublisherId = (UInt16)2;
dataSetReaderAllTypes.WriterGroupId = 1;
dataSetReaderAllTypes.DataSetWriterId = 2;
dataSetReaderAllTypes.Enabled = true;
dataSetReaderAllTypes.DataSetFieldContentMask = (uint)DataSetFieldContentMask.RawData;// RawData encoding;
dataSetReaderAllTypes.KeyFrameCount = 1;
jsonDataSetReaderMessage = new JsonDataSetReaderMessageDataType() {
NetworkMessageContentMask = (uint)(JsonNetworkMessageContentMask.NetworkMessageHeader
| JsonNetworkMessageContentMask.DataSetMessageHeader
| JsonNetworkMessageContentMask.PublisherId
| JsonNetworkMessageContentMask.DataSetClassId
| JsonNetworkMessageContentMask.ReplyTo),
DataSetMessageContentMask = (uint)(JsonDataSetMessageContentMask.DataSetWriterId
| JsonDataSetMessageContentMask.MetaDataVersion
| JsonDataSetMessageContentMask.SequenceNumber
| JsonDataSetMessageContentMask.Status
| JsonDataSetMessageContentMask.Timestamp),
};
dataSetReaderAllTypes.MessageSettings = new ExtensionObject(jsonDataSetReaderMessage);
brokerTransportSettings = new BrokerDataSetReaderTransportDataType() {
QueueName = brokerQueueName,
RequestedDeliveryGuarantee = BrokerTransportQualityOfService.BestEffort,
MetaDataQueueName = $"{brokerQueueName}/{brokerMetaData}",
};
dataSetReaderAllTypes.TransportSettings = new ExtensionObject(brokerTransportSettings);
// Create and set DataSetMetaData for DataSet AllTypes
DataSetMetaDataType allTypesMetaData = CreateDataSetMetaDataAllTypes();
dataSetReaderAllTypes.DataSetMetaData = allTypesMetaData;
// Create and set SubscribedDataSet
subscribedDataSet = new TargetVariablesDataType();
subscribedDataSet.TargetVariables = new FieldTargetDataTypeCollection();
foreach (var fieldMetaData in allTypesMetaData.Fields)
{
subscribedDataSet.TargetVariables.Add(new FieldTargetDataType() {
DataSetFieldId = fieldMetaData.DataSetFieldId,
TargetNodeId = new NodeId(fieldMetaData.Name, NamespaceIndexAllTypes),
AttributeId = Attributes.Value,
OverrideValueHandling = OverrideValueHandling.OverrideValue,
OverrideValue = new Variant(TypeInfo.GetDefaultValue(fieldMetaData.DataType, (int)ValueRanks.Scalar))
});
}
dataSetReaderAllTypes.SubscribedDataSet = new ExtensionObject(subscribedDataSet);
#endregion
readerGroup1.DataSetReaders.Add(dataSetReaderAllTypes);
#endregion
pubSubConnection1.ReaderGroups.Add(readerGroup1);
//create pub sub configuration root object
PubSubConfigurationDataType pubSubConfiguration = new PubSubConfigurationDataType();
pubSubConfiguration.Connections = new PubSubConnectionDataTypeCollection()
{
pubSubConnection1
};
return pubSubConfiguration;
}
/// <summary>
/// Creates a Subscriber PubSubConfiguration object for UDP & UADP programmatically.
/// </summary>
/// <returns></returns>
private static PubSubConfigurationDataType CreateSubscriberConfiguration_MqttUadp(string urlAddress)
{
// Define a PubSub connection with PublisherId 3
PubSubConnectionDataType pubSubConnection1 = new PubSubConnectionDataType();
pubSubConnection1.Name = "Subscriber Connection MQTT UADP";
pubSubConnection1.Enabled = true;
pubSubConnection1.PublisherId = (UInt16)3;
pubSubConnection1.TransportProfileUri = Profiles.PubSubMqttUadpTransport;
NetworkAddressUrlDataType address = new NetworkAddressUrlDataType();
// Specify the local Network interface name to be used
// e.g. address.NetworkInterface = "Ethernet";
// Leave empty to subscribe on all available local interfaces.
address.NetworkInterface = String.Empty;
address.Url = urlAddress;
pubSubConnection1.Address = new ExtensionObject(address);
// Configure the mqtt specific configuration with the MQTTbroker
ITransportProtocolConfiguration mqttConfiguration = new MqttClientProtocolConfiguration(version: EnumMqttProtocolVersion.V500);
pubSubConnection1.ConnectionProperties = mqttConfiguration.ConnectionProperties;
string brokerQueueName = "Uadp_WriterGroup_1";
string brokerMetaData = "$Metadata";
#region Define ReaderGroup1
ReaderGroupDataType readerGroup1 = new ReaderGroupDataType();
readerGroup1.Name = "ReaderGroup 1";
readerGroup1.Enabled = true;
readerGroup1.MaxNetworkMessageSize = 1500;
readerGroup1.MessageSettings = new ExtensionObject(new ReaderGroupMessageDataType());
readerGroup1.TransportSettings = new ExtensionObject(new ReaderGroupTransportDataType());
#region Define DataSetReader 'Simple' for PublisherId = (UInt16)1, DataSetWriterId = 1
DataSetReaderDataType dataSetReaderSimple = new DataSetReaderDataType();
dataSetReaderSimple.Name = "Reader 1 MQTT UADP";
dataSetReaderSimple.PublisherId = (UInt16)3;
dataSetReaderSimple.WriterGroupId = 0;
dataSetReaderSimple.DataSetWriterId = 1;
dataSetReaderSimple.Enabled = true;
dataSetReaderSimple.DataSetFieldContentMask = (uint)DataSetFieldContentMask.RawData;
dataSetReaderSimple.KeyFrameCount = 1;
BrokerDataSetReaderTransportDataType brokerTransportSettings = new BrokerDataSetReaderTransportDataType() {
QueueName = brokerQueueName,
MetaDataQueueName = $"{brokerQueueName}/{brokerMetaData}",
};
dataSetReaderSimple.TransportSettings = new ExtensionObject(brokerTransportSettings);
UadpDataSetReaderMessageDataType uadpDataSetReaderMessage = new UadpDataSetReaderMessageDataType() {
GroupVersion = 0,
NetworkMessageNumber = 0,
NetworkMessageContentMask = (uint)(uint)(UadpNetworkMessageContentMask.PublisherId
| UadpNetworkMessageContentMask.GroupHeader
| UadpNetworkMessageContentMask.WriterGroupId
| UadpNetworkMessageContentMask.PayloadHeader
| UadpNetworkMessageContentMask.GroupVersion
| UadpNetworkMessageContentMask.NetworkMessageNumber
| UadpNetworkMessageContentMask.SequenceNumber),
DataSetMessageContentMask = (uint)(UadpDataSetMessageContentMask.Status | UadpDataSetMessageContentMask.SequenceNumber),
};
dataSetReaderSimple.MessageSettings = new ExtensionObject(uadpDataSetReaderMessage);
// Create and set DataSetMetaData for DataSet Simple
DataSetMetaDataType simpleMetaData = CreateDataSetMetaDataSimple();
dataSetReaderSimple.DataSetMetaData = simpleMetaData;
// Create and set SubscribedDataSet
TargetVariablesDataType subscribedDataSet = new TargetVariablesDataType();
subscribedDataSet.TargetVariables = new FieldTargetDataTypeCollection();
foreach (var fieldMetaData in simpleMetaData.Fields)
{
subscribedDataSet.TargetVariables.Add(new FieldTargetDataType() {
DataSetFieldId = fieldMetaData.DataSetFieldId,
TargetNodeId = new NodeId(fieldMetaData.Name, NamespaceIndexSimple),
AttributeId = Attributes.Value,
OverrideValueHandling = OverrideValueHandling.OverrideValue,
OverrideValue = new Variant(TypeInfo.GetDefaultValue(fieldMetaData.DataType, (int)ValueRanks.Scalar))
});
}
dataSetReaderSimple.SubscribedDataSet = new ExtensionObject(subscribedDataSet);
#endregion
readerGroup1.DataSetReaders.Add(dataSetReaderSimple);
#region Define DataSetReader 'AllTypes' for PublisherId = (UInt16)1, DataSetWriterId = 2
DataSetReaderDataType dataSetReaderAllTypes = new DataSetReaderDataType();
dataSetReaderAllTypes.Name = "Reader 2 MQTT UADP";
dataSetReaderAllTypes.PublisherId = (UInt16)3;
dataSetReaderAllTypes.WriterGroupId = 0;
dataSetReaderAllTypes.DataSetWriterId = 2;
dataSetReaderAllTypes.Enabled = true;
dataSetReaderAllTypes.DataSetFieldContentMask = (uint)DataSetFieldContentMask.RawData;
dataSetReaderAllTypes.KeyFrameCount = 1;
dataSetReaderAllTypes.TransportSettings = new ExtensionObject(brokerTransportSettings);
uadpDataSetReaderMessage = new UadpDataSetReaderMessageDataType() {
GroupVersion = 0,
NetworkMessageNumber = 0,
NetworkMessageContentMask = (uint)(uint)(UadpNetworkMessageContentMask.PublisherId
| UadpNetworkMessageContentMask.GroupHeader
| UadpNetworkMessageContentMask.WriterGroupId
| UadpNetworkMessageContentMask.PayloadHeader
| UadpNetworkMessageContentMask.GroupVersion
| UadpNetworkMessageContentMask.NetworkMessageNumber
| UadpNetworkMessageContentMask.SequenceNumber),
DataSetMessageContentMask = (uint)(UadpDataSetMessageContentMask.Status | UadpDataSetMessageContentMask.SequenceNumber),
};
dataSetReaderAllTypes.MessageSettings = new ExtensionObject(uadpDataSetReaderMessage);
// Create and set DataSetMetaData for DataSet AllTypes
DataSetMetaDataType allTypesMetaData = CreateDataSetMetaDataAllTypes();
dataSetReaderAllTypes.DataSetMetaData = allTypesMetaData;
// Create and set SubscribedDataSet
subscribedDataSet = new TargetVariablesDataType();
subscribedDataSet.TargetVariables = new FieldTargetDataTypeCollection();
foreach (var fieldMetaData in allTypesMetaData.Fields)
{
subscribedDataSet.TargetVariables.Add(new FieldTargetDataType() {
DataSetFieldId = fieldMetaData.DataSetFieldId,
TargetNodeId = new NodeId(fieldMetaData.Name, NamespaceIndexAllTypes),
AttributeId = Attributes.Value,
OverrideValueHandling = OverrideValueHandling.OverrideValue,
OverrideValue = new Variant(TypeInfo.GetDefaultValue(fieldMetaData.DataType, (int)ValueRanks.Scalar))
});
}
dataSetReaderAllTypes.SubscribedDataSet = new ExtensionObject(subscribedDataSet);
#endregion
readerGroup1.DataSetReaders.Add(dataSetReaderAllTypes);
#endregion
pubSubConnection1.ReaderGroups.Add(readerGroup1);
//create pub sub configuration root object
PubSubConfigurationDataType pubSubConfiguration = new PubSubConfigurationDataType();
pubSubConfiguration.Connections = new PubSubConnectionDataTypeCollection()
{
pubSubConnection1
};
return pubSubConfiguration;
}
/// <summary>
/// Creates the "Simple" DataSetMetaData
/// </summary>
/// <returns></returns>
private static DataSetMetaDataType CreateDataSetMetaDataSimple()
{
DataSetMetaDataType simpleMetaData = new DataSetMetaDataType();
simpleMetaData.DataSetClassId = new Uuid(Guid.Empty);
simpleMetaData.Name = "Simple";
simpleMetaData.Fields = new FieldMetaDataCollection()
{
new FieldMetaData()
{
Name = "BoolToggle",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte) DataTypes.Boolean,
DataType = DataTypeIds.Boolean,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "Int32",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte) DataTypes.Int32,
DataType = DataTypeIds.Int32,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "Int32Fast",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte) DataTypes.Int32,
DataType = DataTypeIds.Int32,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "DateTime",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte) DataTypes.DateTime,
DataType = DataTypeIds.DateTime,
ValueRank = ValueRanks.Scalar
},
};
// set the ConfigurationVersion relative to kTimeOfConfiguration constant
simpleMetaData.ConfigurationVersion = new ConfigurationVersionDataType() {
MinorVersion = ConfigurationVersionUtils.CalculateVersionTime(kTimeOfConfiguration),
MajorVersion = ConfigurationVersionUtils.CalculateVersionTime(kTimeOfConfiguration)
};
return simpleMetaData;
}
/// <summary>
/// Creates the "AllTypes" DataSetMetaData
/// </summary>
/// <returns></returns>
private static DataSetMetaDataType CreateDataSetMetaDataAllTypes()
{
DataSetMetaDataType allTypesMetaData = new DataSetMetaDataType();
allTypesMetaData.DataSetClassId = new Uuid(Guid.Empty);
allTypesMetaData.Name = "AllTypes";
allTypesMetaData.Fields = new FieldMetaDataCollection()
{
new FieldMetaData()
{
Name = "BoolToggle",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.Boolean,
DataType = DataTypeIds.Boolean,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "Byte",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.Byte,
DataType = DataTypeIds.Byte,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "Int16",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.Int16,
DataType = DataTypeIds.Int16,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "Int32",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.Int32,
DataType = DataTypeIds.Int32,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "SByte",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.SByte,
DataType = DataTypeIds.SByte,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "UInt16",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.UInt16,
DataType = DataTypeIds.UInt16,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "UInt32",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.UInt32,
DataType = DataTypeIds.UInt32,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "UInt64",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.UInt64,
DataType = DataTypeIds.UInt64,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "Float",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.Float,
DataType = DataTypeIds.Float,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "Double",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.Double,
DataType = DataTypeIds.Double,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "String",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.String,
DataType = DataTypeIds.String,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "ByteString",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.ByteString,
DataType = DataTypeIds.ByteString,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "Guid",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.Guid,
DataType = DataTypeIds.Guid,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "DateTime",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.DateTime,
DataType = DataTypeIds.DateTime,
ValueRank = ValueRanks.Scalar
},
new FieldMetaData()
{
Name = "UInt32Array",
DataSetFieldId = new Uuid(Guid.NewGuid()),
BuiltInType = (byte)DataTypes.UInt32,
DataType = DataTypeIds.UInt32,
ValueRank = ValueRanks.OneDimension
},
};
// set the ConfigurationVersion relative to kTimeOfConfiguration constant
allTypesMetaData.ConfigurationVersion = new ConfigurationVersionDataType() {
MinorVersion = ConfigurationVersionUtils.CalculateVersionTime(kTimeOfConfiguration),
MajorVersion = ConfigurationVersionUtils.CalculateVersionTime(kTimeOfConfiguration)
};
return allTypesMetaData;
}
/// <summary>
/// Initialize logging
/// </summary>
private static void InitializeLog()
{
// Initialize logger
Utils.SetTraceLog("%CommonApplicationData%\\OPC Foundation\\Logs\\Quickstarts.ConsoleReferenceSubscriber.log.txt", true);
Utils.SetTraceMask(Utils.TraceMasks.Error);
Utils.SetTraceOutput(Utils.TraceOutput.DebugAndFile);
}
#endregion
}
}
@@ -1,92 +0,0 @@
# OPC Foundation UA .NET Standard Library - Console Reference Subscriber
## Introduction
This OPC application was created to provide the sample code for creating Subscriber applications using the OPC Foundation UA .NET Standard PubSub Library. There is a .NET Core 3.1 (2.1) console version of the Subscriber which runs on any OS supporting [.NET Standard](https://docs.microsoft.com/en-us/dotnet/articles/standard).
The Reference Subscriber is configured to run in parallel with the [Console Reference Publisher](../ConsoleReferencePublisher/README.md)
## How to build and run the Windows OPC UA Reference Server from Visual Studio
1. Open the solution **UA Reference.sln** with Visual Studio 2019.
2. Choose the project `ConsoleReferenceSubscriber` in the Solution Explorer and set it with a right click as `Startup Project`.
3. Hit `F5` to build and execute the sample.
## How to build and run the console OPC UA Reference Subscriber on Windows, Linux and iOS
This section describes how to run the **ConsoleReferenceSubscriber**.
Please follow instructions in this [article](https://aka.ms/dotnetcoregs) to setup the dotnet command line environment for your platform.
## Start the Subscriber
1. Open a command prompt.
2. Navigate to the folder **Applications/ConsoleReferenceSubscriber**.
3. To run the Subscriber sample type
`dotnet run --project ConsoleReferenceSubscriber.csproj --framework netcoreapp3.1.`
The Subscriber will start and listen for network messages sent by the Reference Publisher.
## Command Line Arguments for *ConsoleReferenceSubscriber*
**ConsoleReferenceSubscriber** can be executed using the following command line arguments:
- -h|help - Shows usage information
- -m|mqtt_json - Creates a connection using there MQTT with Json encoding Profile. This is the default option.
- -u|udp_uadp - Creates a connection using there UDP with UADP encoding Profile.
To run the Subscriber sample using a connection with MQTT with Json encoding execute:
dotnet run --project ConsoleReferenceSubscriber.csproj --framework netcoreapp3.1
or
dotnet run --project ConsoleReferenceSubscriber.csproj --framework netcoreapp3.1 -m
To run the Subscriber sample using a connection with the UDP with UADP encoding execute:
dotnet run --project ConsoleReferenceSubscriber.csproj --framework netcoreapp3.1 -u
# Programmer's Guide
To create a new OPC UA Subscriber application:
- Open Microsoft Visual Studio 2019 environment,
- Create a new project and give it a name,
- Add a reference to the [OPCFoundation.NetStandard.Opc.Ua.PubSub NuGet package](https://www.nuget.org/packages/OPCFoundation.NetStandard.Opc.Ua.PubSub/),
- Initialize Subscriber application (see [Subscriber Initialization](#subscriber-initialization)).
## Subscriber Initialization
The following four steps are required to implement a functional Subscriber:
1. Create [Subscriber Configuration](#subscriber-configuration).
// Create configuration using UDP protocol and UADP Encoding
PubSubConfigurationDataType pubSubConfiguration = CreateSubscriberConfiguration_UdpUadp();
Or use the alternative configuration object for MQTT with JSON encoding
// Create configuration using MQTT protocol and JSON Encoding
PubSubConfigurationDataType pubSubConfiguration = CreateSubscriberConfiguration_MqttJson();
The CreateSubscriberConfiguration methods can be found in [ConsoleReferenceSubscriber/Program.cs](./Program.cs) file.
2. Create an instance of the [UaPubSubApplication Class](../../Docs/PubSub.md#uapubsubapplication-class) using the configuration data from step 1.
// Subscribe to data events
UaPubSubApplication uaPubSubApplication = UaPubSubApplication.Create(pubSubConfiguration);
3. Provide the event handler for the *DataReceived* event. This event will be raised when data sets matching the subscriber configuration arrive over the network. See the DataReceived Event section for more details.
// Create an instance of UaPubSubApplication
uaPubSubApplication.DataReceived += PubSubApplication_DataReceived;
4. Start PubSub application
// Start the publisher
uaPubSubApplication.Start();
After this step the *Subscriber* will listen for *NetworkMessages* as configured.
## Subscriber Configuration
The Subscriber configuration is a subset of the [PubSub Configuration](../../Docs/PubSub.md#pubsub-configuration). A functional *Subscriber* application needs to have a configuration (*PubSubConfgurationDataType* instance) that contains at least one connection (*PubSubConnectionDataType* instance) with at least one reader group configuration (*ReaderGroupDataType* instance). The reader group contains at least one data set reader (*DataSetReaderDataType* instance) that describes a published data set that can be processed and retrieved by the *Subscriber* application.
The diagram shows the subset of classes involved in an *OPC UA Publisher* configuration.
![SubscriberConfigClasses](../../Docs/Images/SubscriberConfigClasses.png)
@@ -27,11 +27,11 @@
</When>
<Otherwise>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Core" Version="2.1.25" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets" Version="2.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="2.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.1.22" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Core" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets" Version="2.2.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="System.Io.Pipelines" Version="6.0.2" />
<PackageReference Include="System.Text.Encodings.Web" Version="6.0.0" />
</ItemGroup>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
+225
View File
@@ -0,0 +1,225 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C33D677A-DDAB-41EF-831F-DC9401BC573E}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>MTConnect</RootNamespace>
<AssemblyName>MTConnect</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Remote_DEBUG|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Remote_DEBUG\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.7.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.7.0.0\lib\net462\Microsoft.Extensions.Configuration.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Binder, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Binder.7.0.0\lib\net462\Microsoft.Extensions.Configuration.Binder.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.CommandLine, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.CommandLine.7.0.0\lib\net462\Microsoft.Extensions.Configuration.CommandLine.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.EnvironmentVariables, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.EnvironmentVariables.7.0.0\lib\net462\Microsoft.Extensions.Configuration.EnvironmentVariables.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.FileExtensions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.FileExtensions.7.0.0\lib\net462\Microsoft.Extensions.Configuration.FileExtensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Json.7.0.0\lib\net462\Microsoft.Extensions.Configuration.Json.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.UserSecrets, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.UserSecrets.7.0.0\lib\net462\Microsoft.Extensions.Configuration.UserSecrets.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.FileProviders.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.FileProviders.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.FileProviders.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.FileProviders.Physical, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.FileProviders.Physical.7.0.0\lib\net462\Microsoft.Extensions.FileProviders.Physical.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.FileSystemGlobbing, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.FileSystemGlobbing.7.0.0\lib\net462\Microsoft.Extensions.FileSystemGlobbing.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Hosting, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Hosting.7.0.0\lib\net462\Microsoft.Extensions.Hosting.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Hosting.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Hosting.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.Hosting.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.7.0.0\lib\net462\Microsoft.Extensions.Logging.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Configuration, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Configuration.7.0.0\lib\net462\Microsoft.Extensions.Logging.Configuration.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Console, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Console.7.0.0\lib\net462\Microsoft.Extensions.Logging.Console.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Debug, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Debug.7.0.0\lib\net462\Microsoft.Extensions.Logging.Debug.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.EventLog, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.EventLog.7.0.0\lib\net462\Microsoft.Extensions.Logging.EventLog.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.EventSource, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.EventSource.7.0.0\lib\net462\Microsoft.Extensions.Logging.EventSource.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Options, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Options.7.0.0\lib\net462\Microsoft.Extensions.Options.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Options.ConfigurationExtensions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Options.ConfigurationExtensions.7.0.0\lib\net462\Microsoft.Extensions.Options.ConfigurationExtensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Primitives, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Primitives.7.0.0\lib\net462\Microsoft.Extensions.Primitives.dll</HintPath>
</Reference>
<Reference Include="MQTTnet, Version=4.3.3.952, Culture=neutral, PublicKeyToken=fdb7629f2e364a63, processorArchitecture=MSIL">
<HintPath>..\packages\MQTTnet.4.3.3.952\lib\net461\MQTTnet.dll</HintPath>
</Reference>
<Reference Include="MQTTnet.Extensions.ManagedClient, Version=4.3.3.952, Culture=neutral, PublicKeyToken=fdb7629f2e364a63, processorArchitecture=MSIL">
<HintPath>..\packages\MQTTnet.Extensions.ManagedClient.4.3.3.952\lib\net461\MQTTnet.Extensions.ManagedClient.dll</HintPath>
</Reference>
<Reference Include="MTConnect.NET, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MTConnect.NET.6.5.1\lib\net462\MTConnect.NET.dll</HintPath>
</Reference>
<Reference Include="MTConnect.NET-Common, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MTConnect.NET-Common.6.5.1\lib\net462\MTConnect.NET-Common.dll</HintPath>
</Reference>
<Reference Include="MTConnect.NET-HTTP, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MTConnect.NET-HTTP.6.5.1\lib\net462\MTConnect.NET-HTTP.dll</HintPath>
</Reference>
<Reference Include="MTConnect.NET-JSON, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MTConnect.NET-JSON.6.5.1\lib\net462\MTConnect.NET-JSON.dll</HintPath>
</Reference>
<Reference Include="MTConnect.NET-JSON-cppagent, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MTConnect.NET-JSON-cppagent.6.5.1\lib\net462\MTConnect.NET-JSON-cppagent.dll</HintPath>
</Reference>
<Reference Include="MTConnect.NET-MQTT, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MTConnect.NET-MQTT.6.5.1\lib\net462\MTConnect.NET-MQTT.dll</HintPath>
</Reference>
<Reference Include="MTConnect.NET-SHDR, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MTConnect.NET-SHDR.6.5.1\lib\net462\MTConnect.NET-SHDR.dll</HintPath>
</Reference>
<Reference Include="MTConnect.NET-TLS, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MTConnect.NET-TLS.6.5.1\lib\net462\MTConnect.NET-TLS.dll</HintPath>
</Reference>
<Reference Include="MTConnect.NET-XML, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MTConnect.NET-XML.6.5.1\lib\net462\MTConnect.NET-XML.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Diagnostics.DiagnosticSource, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Diagnostics.DiagnosticSource.7.0.0\lib\net462\System.Diagnostics.DiagnosticSource.dll</HintPath>
</Reference>
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime" />
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
</Reference>
<Reference Include="System.Security.Cryptography.Algorithms, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Cryptography.Algorithms.4.3.1\lib\net461\System.Security.Cryptography.Algorithms.dll</HintPath>
</Reference>
<Reference Include="System.Security.Cryptography.Primitives, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll</HintPath>
</Reference>
<Reference Include="System.Text.Encodings.Web, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Encodings.Web.7.0.0\lib\net462\System.Text.Encodings.Web.dll</HintPath>
</Reference>
<Reference Include="System.Text.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Json.7.0.0\lib\net462\System.Text.Json.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="YamlDotNet, Version=13.0.0.0, Culture=neutral, PublicKeyToken=ec19458f3c15af5e, processorArchitecture=MSIL">
<HintPath>..\packages\YamlDotNet.13.7.1\lib\net45\YamlDotNet.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="file.log">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
<None Include="postBuildTgt.bat" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>"$(ProjectDir)postBuildTgt.bat" "$(ConfigurationName)" "$(TargetDir)"</PostBuildEvent>
</PropertyGroup>
</Project>
+311
View File
@@ -0,0 +1,311 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Remoting;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using MTConnect.Clients;
using MTConnect.Observations;
using MTConnect.Streams;
using YamlDotNet.Serialization.ObjectGraphVisitors;
namespace MTConnect
{
internal class Program
{
#region Private Fields
private static MTConnectHttpClient client;
// Get the current directory
private static string currentDirectory = Directory.GetCurrentDirectory();
private static string filePath = Path.Combine(currentDirectory, "file.log");
private static string sep = "------------------------";
private static Stopwatch sw = new Stopwatch();
#endregion Private Fields
#region Private Methods
private static void Client_AssetsReceived(object sender, Assets.IAssetsResponseDocument document)
{
doLog(sep);
doLog("ASSET");
doLog(sep);
foreach (var asset in document.Assets)
{
// Print AssetId to the Console
doLog($"Asset: {asset.AssetId}");
}
doLog(sep);
doLog();
}
private static void Client_ClientStarted(object sender, EventArgs e)
{
doLog(sep);
doLog($"Client Started! | {e}");
doLog(sep);
doLog("Press ESC to exit");
}
private static void Client_ClientStopped(object sender, EventArgs e)
{
doLog(sep);
doLog($"Client Stopped! | {e}");
doLog(sep);
doLog("Press ESC to exit");
}
private static void Client_ConnectionError(object sender, Exception exc)
{
doLog(sep);
doLog($"CONNECTION ERROR returned!");
doLog($"{exc}");
doLog(sep);
doLog("Press ESC to exit");
}
private static void Client_CurrentReceived(object sender, Streams.IStreamsResponseDocument document)
{
doLog(sep);
doLog("CURRENT");
doLog(sep);
foreach (var deviceStream in document.Streams)
{
// DeviceStream
doLog($"Stream: {deviceStream.Name}");
// Component Streams
foreach (var componentStream in deviceStream.ComponentStreams)
{
processData(componentStream);
}
}
doLog(sep);
doLog();
}
private static void Client_ObservationReceived(object sender, IObservation observ)
{
doLog(sep);
doLog("OBSERVATION");
doLog(sep);
processObservation(observ);
}
private static void Client_ProbeReceived(object sender, Devices.IDevicesResponseDocument document)
{
doLog(sep);
doLog("PROBE returned");
doLog(sep);
foreach (var device in document.Devices)
{
// Device
doLog($"DEV: {device.Id}");
// All DataItems (traverse the entire Device model)
if (device.DataItems.Count() > 0)
{
foreach (var dataItem in device.GetDataItems())
{
doLog($" DItm | {dataItem.IdPath}");
}
}
// All Components (traverse the entire Device model)
if (device.Components.Count() > 0)
{
foreach (var component in device.GetComponents())
{
doLog($" Comp | {component.IdPath}");
}
}
// All Compositions (traverse the entire Device model)
if (device.Compositions.Count() > 0)
{
foreach (var composition in device.GetCompositions())
{
doLog($" Cpst | {composition.IdPath}");
}
}
}
doLog(sep);
doLog();
}
private static void Client_SampleReceived(object sender, Streams.IStreamsResponseDocument document)
{
doLog(sep);
doLog("SAMPLE");
doLog(sep);
foreach (var deviceStream in document.Streams)
{
// DeviceStream
doLog($"Stream: {deviceStream.Name}");
// Component Streams
foreach (var componentStream in deviceStream.ComponentStreams)
{
processData(componentStream);
}
}
doLog(sep);
doLog();
}
private static void doLog(string msg = "")
{
string dtMessage = $"{DateTime.Now:HH:mm:ss.fff} | {msg}";
File.AppendAllText(filePath, $"{dtMessage}{Environment.NewLine}");
Console.WriteLine(dtMessage);
}
private static void doPreliminaryProbe(string baseUrl)
{
doLog();
doLog("Call Probe");
var prbClient = new MTConnectHttpProbeClient(baseUrl);
prbClient.Timeout = 20000;
var prbDoc = prbClient.Get();
if (prbDoc == null)
{
doLog("Preliminari Probe | No answer, continue...");
}
else
{
doLog(sep);
doLog("Preliminary PROBE");
doLog(sep);
foreach (var device in prbDoc.Devices)
{
// Device
doLog($"DEV: {device.Id}");
// All DataItems (traverse the entire Device model)
if (device.DataItems.Count() > 0)
{
foreach (var dataItem in device.GetDataItems())
{
doLog($" DItm | {dataItem.IdPath}");
}
}
// All Components (traverse the entire Device model)
if (device.Components.Count() > 0)
{
foreach (var component in device.GetComponents())
{
doLog($" Comp | {component.IdPath}");
}
}
// All Compositions (traverse the entire Device model)
if (device.Compositions.Count() > 0)
{
foreach (var composition in device.GetCompositions())
{
doLog($" Cpst | {composition.IdPath}");
}
}
}
doLog(sep);
doLog();
}
}
private static void Main(string[] args)
{
// setup oggetti
//var baseUrl = "127.0.0.1:5000";
var baseUrl = "192.168.1.27:5000";
// inizio ciclo
doLog(sep);
doLog("Rest Client test application");
doLog(sep);
doPreliminaryProbe(baseUrl);
doLog("Call connection");
client = new MTConnectHttpClient(baseUrl);
// sample interval
client.Interval = 500;
// timeout x richieste
client.Timeout = 4000;
// timeout riconnessione
client.ReconnectionInterval = 5000;
// aggancio eventi
client.ClientStarted += Client_ClientStarted;
client.ClientStopped += Client_ClientStopped;
client.ConnectionError += Client_ConnectionError;
client.ProbeReceived += Client_ProbeReceived;
client.AssetsReceived += Client_AssetsReceived;
client.CurrentReceived += Client_CurrentReceived;
client.SampleReceived += Client_SampleReceived;
// conviene usare sample x avere la stessa cosa ma con altre info...
//client.ObservationReceived += Client_ObservationReceived;
// vero avvio
client.Start();
Task.Delay(5000);
doLog();
ConsoleKeyInfo answ;
doLog("Press ESC to exit");
answ = Console.ReadKey();
while (answ == null || answ.Key != ConsoleKey.Escape)
{
doLog("Press ESC to exit");
Task.Delay(1000);
answ = Console.ReadKey();
}
doLog("...closing Now!");
}
private static void processData(IComponentStream dataStream)
{
doLog($"Component {dataStream.Name} -->");
// DataItems (Samples, Events, and Conditions)
foreach (var observation in dataStream.Observations)
{
processObservation(observation);
}
}
private static void processObservation(IObservation observation)
{
string sMsg = $" - {observation.DataItemId} | {observation.Category}";
switch (observation.Category)
{
case Devices.DataItemCategory.CONDITION:
break;
case Devices.DataItemCategory.EVENT:
break;
case Devices.DataItemCategory.SAMPLE:
break;
default:
break;
}
if (observation.Values != null && observation.Values.Count() > 0)
{
foreach (var item in observation.Values)
{
sMsg += $" | {item.Key}: {item.Value}";
}
}
doLog(sMsg);
}
#endregion Private Methods
}
}
+33
View File
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MTConnect")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MTConnect")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c33d677a-ddab-41ef-831f-dc9401bc573e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+53
View File
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl.AsyncInterfaces" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Configuration" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Configuration.Abstractions" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Configuration.Binder" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Configuration.CommandLine" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Configuration.EnvironmentVariables" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Configuration.FileExtensions" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Configuration.Json" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Configuration.UserSecrets" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.DependencyInjection" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.FileProviders.Abstractions" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.FileProviders.Physical" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.FileSystemGlobbing" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Hosting" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Hosting.Abstractions" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Logging" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Logging.Abstractions" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Logging.Configuration" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Logging.Console" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Logging.Debug" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Logging.EventLog" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Logging.EventSource" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Options" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Options.ConfigurationExtensions" version="7.0.0" targetFramework="net462" />
<package id="Microsoft.Extensions.Primitives" version="7.0.0" targetFramework="net462" />
<package id="MQTTnet" version="4.3.3.952" targetFramework="net462" />
<package id="MQTTnet.Extensions.ManagedClient" version="4.3.3.952" targetFramework="net462" />
<package id="MTConnect.NET" version="6.5.1" targetFramework="net462" />
<package id="MTConnect.NET-Common" version="6.5.1" targetFramework="net462" />
<package id="MTConnect.NET-HTTP" version="6.5.1" targetFramework="net462" />
<package id="MTConnect.NET-JSON" version="6.5.1" targetFramework="net462" />
<package id="MTConnect.NET-JSON-cppagent" version="6.5.1" targetFramework="net462" />
<package id="MTConnect.NET-MQTT" version="6.5.1" targetFramework="net462" />
<package id="MTConnect.NET-SHDR" version="6.5.1" targetFramework="net462" />
<package id="MTConnect.NET-TLS" version="6.5.1" targetFramework="net462" />
<package id="MTConnect.NET-XML" version="6.5.1" targetFramework="net462" />
<package id="System.Buffers" version="4.5.1" targetFramework="net462" />
<package id="System.Diagnostics.DiagnosticSource" version="7.0.0" targetFramework="net462" />
<package id="System.Memory" version="4.5.5" targetFramework="net462" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net462" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net462" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net462" />
<package id="System.Security.Cryptography.Algorithms" version="4.3.1" targetFramework="net462" />
<package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net462" />
<package id="System.Text.Encodings.Web" version="7.0.0" targetFramework="net462" />
<package id="System.Text.Json" version="7.0.0" targetFramework="net462" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net462" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net462" />
<package id="YamlDotNet" version="13.7.1" targetFramework="net462" />
</packages>
+70
View File
@@ -0,0 +1,70 @@
@echo off
echo Effettua pulizia post build: configurazione %1. directory %2
RD /S /Q %2"\lib\da"
RD /S /Q %2"\lib\de"
RD /S /Q %2"\lib\es"
RD /S /Q %2"\lib\fr"
RD /S /Q %2"\lib\it"
RD /S /Q %2"\lib\ja-JP"
RD /S /Q %2"\lib\ko"
RD /S /Q %2"\lib\nl"
RD /S /Q %2"\lib\pl"
RD /S /Q %2"\lib\pt"
RD /S /Q %2"\lib\ru"
RD /S /Q %2"\lib\sv"
RD /S /Q %2"\lib\tr"
RD /S /Q %2"\lib\zh"
MOVE /Y %2"da" %2"lib\"
MOVE /Y %2"de" %2"lib\"
MOVE /Y %2"es" %2"lib\"
MOVE /Y %2"fr" %2"lib\"
MOVE /Y %2"it" %2"lib\"
MOVE /Y %2"ja-JP" %2"lib\"
MOVE /Y %2"ko" %2"lib\"
MOVE /Y %2"nl" %2"lib\"
MOVE /Y %2"pl" %2"lib\"
MOVE /Y %2"pt" %2"lib\"
MOVE /Y %2"ru" %2"lib\"
MOVE /Y %2"sv" %2"lib\"
MOVE /Y %2"tr" %2"lib\"
MOVE /Y %2"zh" %2"lib\"
if %1 == "Release" goto Release
if %1 == "Debug" goto Debug
if %1 == "Remote_DEBUG" goto RemoteDebug
:Release
REM INIZIO eliminando i files pdb
del /S %2"*.pdb""
del /S %2"*.xml""
del /S %2"lib/*.pdb""
echo Release: eliminato pdb + xml!!!
goto END
:Debug
echo Debug: nulla da eliminare
REM copia script verso server remoto
REM ROBOCOPY . \\10.150.0.1\Steamware\IOB-WIN-NEXT-DEB /MIR
goto END
:RemoteDebug
REM copia script verso server remoto
REM echo Debug remoto: effettuo robocopy sync (verificare remote per cliente)
REM IOB-WIN-SIM
REM ROBOCOPY . \\IOB-WIN-SIMULA\Steamware\IOB-WIN-NEXT-DEB /MIR
REM IOBVPN4MACHINE
REM ROBOCOPY . \\10.51.90.5\Steamware\TestCli /MIR
ROBOCOPY . \\10.51.90.9\Steamware\TestCli\CLI /MIR
goto END
:END
echo Fatto!
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
</configuration>
+82
View File
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{1A4D0968-9C4B-4509-98AF-20A62DF59558}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Mitsubishi</RootNamespace>
<AssemblyName>Mitsubishi</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Remote_DEBUG|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Remote_DEBUG\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="postBuildTgt.bat" />
</ItemGroup>
<ItemGroup>
<COMReference Include="EZNCAUTLib">
<Guid>{1B93D6AF-FD32-4281-83FE-533F666FAE6C}</Guid>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>True</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>
</PreBuildEvent>
</PropertyGroup>
<PropertyGroup>
<PostBuildEvent>"$(ProjectDir)postBuildTgt.bat" "$(ConfigurationName)" "$(TargetDir)"</PostBuildEvent>
</PropertyGroup>
</Project>
+336
View File
@@ -0,0 +1,336 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Mitsubishi
{
internal class Program
{
static void Main(string[] args)
{
// preparo area x file test x debug successivo
var appPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var fPath = Directory.GetParent(appPath).FullName;
string basePath = Path.Combine(fPath, "Test");
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
outPath = Path.Combine(basePath, "test.log");
File.WriteAllText(outPath, "");
bool testWrite = false;
DoLog(sep);
DoLog("Mitsubishi Client test application");
DoLog(sep);
DoLog("");
Console.WriteLine("Vuoi simulare scritture? S/N");
ConsoleKeyInfo answ = Console.ReadKey();
testWrite = answ.KeyChar == 's' || answ.KeyChar == 'S';
// obj connessione
EZNCAUTLib.DispEZNcCommunication oEZNcAutCom = null;
oEZNcAutCom = new EZNCAUTLib.DispEZNcCommunication();
// [Local variable declaration]
object BlockValue = "";
int iRet = 0;
//Open communication
iRet = oEZNcAutCom.SetTCPIPProtocol("192.168.213.199", 683);
//Console.WriteLine($"R: {iRet}");
iRet = oEZNcAutCom.Open3(5, 1, 10, "EZNC_LOCALHOST");
DoLog(sep);
DoLog("Retrieve Serial/Vers");
DoLog(sep);
int partSys = -1;
oEZNcAutCom.System_GetSystemInformation(0, out partSys);
DoLog($"PartSys: {partSys}");
int numAx = -1; ;
oEZNcAutCom.System_GetSystemInformation(1, out numAx);
DoLog($"Num Ax: {numAx}");
string serNo = "";
oEZNcAutCom.System_GetSerialNo(out serNo);
DoLog($"SerNo: {serNo}");
string pVers = "";
oEZNcAutCom.System_GetVersion(0, 0, out pVers);
DoLog($"Vers 0: {pVers}");
oEZNcAutCom.System_GetVersion(0, 1, out pVers);
DoLog($"Vers 1: {pVers}");
oEZNcAutCom.System_GetVersion(0, 2, out pVers);
DoLog($"Vers 2: {pVers}");
DoLog(sep);
DoLog("");
DoLog(sep);
DoLog("Test DateTime");
DoLog(sep);
// preparo memorie
int pDate = 0;
int pTime = 0;
try
{
oEZNcAutCom.Time_GetClockData(out pDate, out pTime);
DoLog($"Date-Time | D: {pDate} | T: {pTime}");
}
catch (Exception exc)
{
DoLog($"{exc}");
}
DoLog(sep);
DoLog("");
DoLog(sep);
DoLog("Test Program");
DoLog(sep);
// preparo memorie
string prgText = "";
int prgState = 0;
// solo nome...
iRet = oEZNcAutCom.Program_GetProgramNumber2((Int32)PROGRAMTYPE.EZNC_MAINPRG, out String strProgramNo);
DoLog($"ProgramName: {strProgramNo}");
DoLog("");
// leggo contenuto
try
{
oEZNcAutCom.Program_CurrentBlockRead(10, out prgText, out prgState);
DoLog($"Program {prgState} | {prgText}");
}
catch (Exception exc)
{
DoLog($"{exc}");
}
DoLog(sep);
DoLog("");
DoLog(sep);
DoLog("Test CycleTyme");
DoLog(sep);
// preparo memorie
int plTime = 0;
try
{
oEZNcAutCom.Status_GetCycleTime(out plTime);
DoLog($"GetCycleTime | Time: {plTime}");
}
catch (Exception exc)
{
DoLog($"{exc}");
}
DoLog(sep);
DoLog("");
DoLog(sep);
DoLog("Test Lettura posizioni");
DoLog(sep);
double pdPosit = 0;
for (int i = 1; i < 4; i++)
{
iRet = oEZNcAutCom.Position_GetCurrentPosition(i, out pdPosit);
DoLog($"Pos: {i} | {pdPosit}");
}
DoLog(sep);
DoLog("");
DoLog(sep);
DoLog("Test scrittura Var500");
DoLog(sep);
// NB: max 7 char!!!
if (testWrite)
{
oEZNcAutCom.CommonVariable_SetName(500, "ODL");
oEZNcAutCom.CommonVariable_SetName(501, "CodArt");
oEZNcAutCom.CommonVariable_SetName(502, "NumPz");
oEZNcAutCom.CommonVariable_SetName(503, "");
oEZNcAutCom.CommonVariable_Write2(500, 105, 1);
oEZNcAutCom.CommonVariable_Write2(501, 205, 1);
oEZNcAutCom.CommonVariable_Write2(502, 305, 1);
oEZNcAutCom.CommonVariable_Write2(503, 0, 1);
}
DoLog("CommonVariable 500..503 Write Done!");
DoLog(sep);
DoLog("");
DoLog(sep);
DoLog("Test lettura Var500");
DoLog(sep);
string varName = "";
double pData = 0;
int pType = 0;
for (int i = 500; i < 505; i++)
{
oEZNcAutCom.CommonVariable_GetName(i, out varName);
oEZNcAutCom.CommonVariable_Read2(i, out pData, out pType);
DoLog($"Var: {i} | {varName} | val: {pData} | type: {pType}");
}
DoLog(sep);
DoLog("");
// lettura lampade
DoLog(sep);
DoLog("Test lettura lampade Y60..Y63");
DoLog(sep);
object pvRead = "bbb";
int sec = 53;
Dictionary<string, string> DictLamp = new Dictionary<string, string>();
//Y60 --> 10000+96
int subSec = 10096;
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 4; i++)
{
oEZNcAutCom.Generic_ReadData(0, sec, subSec + i, ref pvRead);
DictLamp.Add($"{subSec + i}", $"{pvRead}");
}
StringBuilder sb = new StringBuilder();
foreach (var item in DictLamp)
{
sb.Append($"{item.Key}:{item.Value} | ");
}
DoLog($"Lamp: Generic ReadData | sec: {sec} | {sb.ToString()}");
Thread.Sleep(100);
DictLamp = new Dictionary<string, string>();
}
DoLog(sep);
DoLog("");
// lettura parametri (pzcount)
DoLog(sep);
DoLog("Test Parametri");
DoLog(sep);
int lAxis = 0;
int startPar = 8001;
if (testWrite)
{
// scrivo pz req a 100...
String[] sValue = new String[1];
sValue[0] = "101";
oEZNcAutCom.Parameter_SetData3(0, 8003, lAxis, (object)sValue);
}
object parValue = "www";
try
{
oEZNcAutCom.Parameter_GetData3(0, startPar, 3, lAxis, out parValue);
string[] rawData = (string[])parValue;
DoLog($"Found {rawData.Count()} values");
int i = 0;
foreach (var item in rawData)
{
DoLog($"Params | #: {startPar + i} | {item}");
i++;
}
}
catch (Exception exc)
{
DoLog($"{exc}");
}
DoLog(sep);
DoLog("");
DoLog(sep);
DoLog("Test Allarmi");
DoLog(sep);
// preparo memorie
Array plSystem = new long[1];
Array pbWarning = new bool[1];
Array plAlarmType = new long[1];
string pbstrBuffer = "";
try
{
for (int i = 0; i < 5; i++)
{
oEZNcAutCom.System_GetAlarm2(1, i, out pbstrBuffer);
DoLog($"Alarm {i}: {pbstrBuffer}");
}
}
catch (Exception exc)
{
DoLog($"{exc}");
}
DoLog(sep);
DoLog("");
DoLog(sep);
DoLog("Test Feed");
DoLog(sep);
// preparo memorie
double feed = 0;
try
{
for (int i = 0; i <= 5; i++)
{
oEZNcAutCom.Position_GetFeedSpeed(i, out feed);
DoLog($"FeedSpeed {i}: {feed}");
oEZNcAutCom.Command_GetFeedCommand(i, out feed);
DoLog($"FeedCommand {i}: {feed}");
}
}
catch (Exception exc)
{
DoLog($"{exc}");
}
DoLog(sep);
DoLog("");
DoLog(sep);
DoLog("Test RunStatus");
DoLog(sep);
// preparo memorie
int plStatus = 0;
try
{
for (int i = 0; i < 4; i++)
{
oEZNcAutCom.Status_GetRunStatus(i, out plStatus);
DoLog($"GetRunStatus | Idx: {i} | Status: {plStatus}");
}
}
catch (Exception exc)
{
DoLog($"{exc}");
}
DoLog(sep);
DoLog("");
// Close.
iRet = oEZNcAutCom.Close();
//Release object
oEZNcAutCom = null;
DoLog("Press enter to close");
Console.ReadLine();
}
protected static void DoLog(string logMessage)
{
File.AppendAllText(outPath, $"{logMessage}{Environment.NewLine}");
Console.WriteLine(logMessage);
}
public enum PROGRAMTYPE
{
EZNC_MAINPRG = 0, //メインプログラム
EZNC_SUBPRG = 1, //サブプログラム
}
protected static string outPath = "";
private static string sep = "------------------------";
private static Stopwatch sw = new Stopwatch();
}
}
+33
View File
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Mitsubishi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mitsubishi")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1a4d0968-9c4b-4509-98af-20a62df59558")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+70
View File
@@ -0,0 +1,70 @@
@echo off
echo Effettua pulizia post build: configurazione %1. directory %2
RD /S /Q %2"\lib\da"
RD /S /Q %2"\lib\de"
RD /S /Q %2"\lib\es"
RD /S /Q %2"\lib\fr"
RD /S /Q %2"\lib\it"
RD /S /Q %2"\lib\ja-JP"
RD /S /Q %2"\lib\ko"
RD /S /Q %2"\lib\nl"
RD /S /Q %2"\lib\pl"
RD /S /Q %2"\lib\pt"
RD /S /Q %2"\lib\ru"
RD /S /Q %2"\lib\sv"
RD /S /Q %2"\lib\tr"
RD /S /Q %2"\lib\zh"
MOVE /Y %2"da" %2"lib\"
MOVE /Y %2"de" %2"lib\"
MOVE /Y %2"es" %2"lib\"
MOVE /Y %2"fr" %2"lib\"
MOVE /Y %2"it" %2"lib\"
MOVE /Y %2"ja-JP" %2"lib\"
MOVE /Y %2"ko" %2"lib\"
MOVE /Y %2"nl" %2"lib\"
MOVE /Y %2"pl" %2"lib\"
MOVE /Y %2"pt" %2"lib\"
MOVE /Y %2"ru" %2"lib\"
MOVE /Y %2"sv" %2"lib\"
MOVE /Y %2"tr" %2"lib\"
MOVE /Y %2"zh" %2"lib\"
if %1 == "Release" goto Release
if %1 == "Debug" goto Debug
if %1 == "Remote_DEBUG" goto RemoteDebug
:Release
REM INIZIO eliminando i files pdb
del /S %2"*.pdb""
del /S %2"*.xml""
del /S %2"lib/*.pdb""
echo Release: eliminato pdb + xml!!!
goto END
:Debug
echo Debug: nulla da eliminare
REM copia script verso server remoto
REM ROBOCOPY . \\10.150.0.1\Steamware\IOB-WIN-NEXT-DEB /MIR
goto END
:RemoteDebug
REM copia script verso server remoto
REM echo Debug remoto: effettuo robocopy sync (verificare remote per cliente)
REM IOB-WIN-SIM
REM ROBOCOPY . \\IOB-WIN-SIMULA\Steamware\IOB-WIN-NEXT-DEB /MIR
REM IOBVPN4MACHINE
REM ROBOCOPY . \\10.51.90.5\Steamware\TestCli /MIR
ROBOCOPY . \\10.51.90.6\Steamware\TestCli /MIR
goto END
:END
echo Fatto!
+44
View File
@@ -0,0 +1,44 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mitsubishi", "Mitsubishi\Mitsubishi.csproj", "{1A4D0968-9C4B-4509-98AF-20A62DF59558}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestAppCitizen", "RestAppCitizen\RestAppCitizen.csproj", "{F206B5DB-E062-417E-BF29-197FB8111DCD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MTConnect", "MTConnect\MTConnect.csproj", "{C33D677A-DDAB-41EF-831F-DC9401BC573E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
Remote_DEBUG|Any CPU = Remote_DEBUG|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1A4D0968-9C4B-4509-98AF-20A62DF59558}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1A4D0968-9C4B-4509-98AF-20A62DF59558}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1A4D0968-9C4B-4509-98AF-20A62DF59558}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1A4D0968-9C4B-4509-98AF-20A62DF59558}.Release|Any CPU.Build.0 = Release|Any CPU
{1A4D0968-9C4B-4509-98AF-20A62DF59558}.Remote_DEBUG|Any CPU.ActiveCfg = Remote_DEBUG|Any CPU
{1A4D0968-9C4B-4509-98AF-20A62DF59558}.Remote_DEBUG|Any CPU.Build.0 = Remote_DEBUG|Any CPU
{F206B5DB-E062-417E-BF29-197FB8111DCD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F206B5DB-E062-417E-BF29-197FB8111DCD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F206B5DB-E062-417E-BF29-197FB8111DCD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F206B5DB-E062-417E-BF29-197FB8111DCD}.Release|Any CPU.Build.0 = Release|Any CPU
{F206B5DB-E062-417E-BF29-197FB8111DCD}.Remote_DEBUG|Any CPU.ActiveCfg = Release|Any CPU
{F206B5DB-E062-417E-BF29-197FB8111DCD}.Remote_DEBUG|Any CPU.Build.0 = Release|Any CPU
{C33D677A-DDAB-41EF-831F-DC9401BC573E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C33D677A-DDAB-41EF-831F-DC9401BC573E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C33D677A-DDAB-41EF-831F-DC9401BC573E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C33D677A-DDAB-41EF-831F-DC9401BC573E}.Release|Any CPU.Build.0 = Release|Any CPU
{C33D677A-DDAB-41EF-831F-DC9401BC573E}.Remote_DEBUG|Any CPU.ActiveCfg = Remote_DEBUG|Any CPU
{C33D677A-DDAB-41EF-831F-DC9401BC573E}.Remote_DEBUG|Any CPU.Build.0 = Remote_DEBUG|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DC9CC892-232E-4D99-8C91-07F023E0F4FE}
EndGlobalSection
EndGlobal
+99
View File
@@ -0,0 +1,99 @@
// See https://aka.ms/new-console-template for more information
using System.Diagnostics;
using System.Dynamic;
using Newtonsoft.Json;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(sep);
Console.WriteLine("Rest Client test application");
Console.WriteLine(sep);
Console.WriteLine();
Console.WriteLine("Call connection");
// setup oggetti
int tOut = 60;
string apiUrl = "http://192.168.80.61:8733/DRIVER_MES/rest/";
rCall = new RestCaller(apiUrl, tOut);
// chiamate!
CallAndLog("checkconnection");
string token = CallAndLog("gettoken/mecmaticames/mecmatica@mes").Replace("\"", "");
string gLamp = CallAndLog($"getsingleladderio/{token}/Y/8E");
string yLamp = CallAndLog($"getsingleladderio/{token}/Y/21");
string rLamp = CallAndLog($"getsingleladderio/{token}/Y/22");
string qtyTot = CallAndLog($"gettotalquantity/{token}");
string qtyReq = CallAndLog($"getneededquantity/{token}");
string qtyWrk = CallAndLog($"getworkedquantity/{token}");
string cTime = CallAndLog($"getcycletime/{token}");
string pName = CallAndLog($"getmainprogram/{token}");
string cAlarm = CallAndLog($"getalarm/{token}");
var sAlarm = JsonConvert.DeserializeObject<WarnInfo>(cAlarm);
cAlarm = JsonConvert.SerializeObject(sAlarm, Formatting.Indented);
string allAlarm = CallAndLog($"getallalarmlog/{token}");
var alarmList = JsonConvert.DeserializeObject<List<AlarmInfo>>(allAlarm);
allAlarm = JsonConvert.SerializeObject(alarmList, Formatting.Indented);
string err = CallAndLog($"getsingleladderio/ABC/Y/22");
// ora scrivo i files dei test x debug successivo
var appPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var fPath = Directory.GetParent(appPath).FullName;
string basePath = Path.Combine(fPath, "Test");
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
File.WriteAllText(Path.Combine(basePath, "token.txt"), token);
File.WriteAllText(Path.Combine(basePath, "gLamp.txt"), gLamp);
File.WriteAllText(Path.Combine(basePath, "yLamp.txt"), yLamp);
File.WriteAllText(Path.Combine(basePath, "rLamp.txt"), rLamp);
File.WriteAllText(Path.Combine(basePath, "qtyTot.txt"), qtyTot);
File.WriteAllText(Path.Combine(basePath, "qtyReq.txt"), qtyReq);
File.WriteAllText(Path.Combine(basePath, "qtyWrk.txt"), qtyWrk);
File.WriteAllText(Path.Combine(basePath, "cTime.txt"), cTime);
File.WriteAllText(Path.Combine(basePath, "pName.txt"), pName);
File.WriteAllText(Path.Combine(basePath, "cAlarm.txt"), cAlarm);
File.WriteAllText(Path.Combine(basePath, "allAlarm.txt"), allAlarm);
}
private static RestCaller rCall { get; set; } = new RestCaller("http://localhost", 60);
private static string sep = "------------------------";
private static Stopwatch sw = new Stopwatch();
private static string CallAndLog(string fullUri)
{
sw.Restart();
Console.WriteLine(sep);
Console.WriteLine($"Calling: {fullUri}");
// chiamo
string answ = rCall.ExecuteCallGet(fullUri);
sw.Stop();
// loggo
Console.WriteLine(answ);
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}");
Console.WriteLine(sep);
Console.WriteLine();
return answ;
}
}
internal class AlarmInfo
{
public int id { get; set; } = 0;
public string? ErrorMessage { get; set; } = null;
public DateTime date { get; set; } = DateTime.Today.AddYears(-10);
public string message { get; set; } = "";
public string type { get; set; } = "";
}
internal class WarnInfo
{
public bool IsAlarm { get; set; } = false;
public bool IsCaution { get; set; } = false;
public string? ErrorMessage { get; set; } = null;
public string message { get; set; } = "";
}
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="RestSharp" Version="112.1.0" />
</ItemGroup>
</Project>
+62
View File
@@ -0,0 +1,62 @@
using RestSharp;
public class RestCaller
{
/// <summary>
/// Classe gestione chiamate REST
/// </summary>
/// <param name="ApiUrl"></param>
/// <param name="TimeOutSec"></param>
public RestCaller(string ApiUrl, int TimeOutSec)
{
tOut = TimeOutSec;
apiUrl = ApiUrl;
restOptStd = new RestClientOptions
{
Timeout = TimeSpan.FromSeconds(tOut),
BaseUrl = new Uri(apiUrl)
};
}
/// <summary>
/// Esecuzione chiamata Rest tipo GET
/// </summary>
/// <param name="resource"></param>
/// <returns></returns>
public string ExecuteCallGet(string resource)
{
string answ = "";
if (!string.IsNullOrEmpty(resource))
{
// client chiamate rest
using (var client = new RestClient(restOptStd))
{
var currReq = new RestRequest(resource, Method.Get);
// currReq.AddHeader("Content-type", "application/xml");
currReq.AddHeader("Content-type", "application/json");
// effettuo vera chiamata
var currResp = client.Get(currReq);
if (currResp.StatusCode == System.Net.HttpStatusCode.OK && currResp.Content != null)
{
answ = $"{currResp.Content}";
}
}
}
return answ;
}
protected string apiUrl = "";
protected int tOut = 60;
/// <summary>
/// Conf client RestSharp standard:
/// - timeout 1 min
/// </summary>
private RestClientOptions restOptStd = new RestClientOptions { Timeout = TimeSpan.FromSeconds(60) };
}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
{"ErrorMessage":null,"IsAlarm":false,"IsCaution":true,"message":"CAUTION ON MACHINE"}
+1
View File
@@ -0,0 +1 @@
56
+1
View File
@@ -0,0 +1 @@
{"Address":"8E","Description":"","ErrorMessage":null,"IOType":"Y","VarValue":"0"}
View File
+1
View File
@@ -0,0 +1 @@
500
+1
View File
@@ -0,0 +1 @@
500
+1
View File
@@ -0,0 +1 @@
0
+1
View File
@@ -0,0 +1 @@
{"Address":"22","Description":"","ErrorMessage":null,"IOType":"Y","VarValue":"0"}
+1
View File
@@ -0,0 +1 @@
6d65636d61746963616d6573c2a76d65636d6174696361406d6573c2a731
+1
View File
@@ -0,0 +1 @@
{"Address":"21","Description":"","ErrorMessage":null,"IOType":"Y","VarValue":"0"}