Giter Club home page Giter Club logo

titaniumas.opc.client's People

Contributors

alexey-kachalov avatar alexey-titov avatar huffsamuel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

titaniumas.opc.client's Issues

PowerShell: Unable to initialize OPC DA client. It should run under MTA apartment state due to CoInitializeSecurity call.

Try to use library in Powershell(4.x)

  1. Start powershell-console with '-mta' switch. Nevertheless, I got the error described in title when calling [TitaniumAS.Opc.Client.Bootstrap]::Initialize().
  2. In PS-console; typing: [System.Threading.Thread]::CurrentThread.GetApartmentState() gives me 'MTA'
  3. in PS-console; typing: $host.Runspace.ApartmentState gives me 'Unknown.'

Testing in C#(VS-Studio), with console-thread in MTA, does work.

How to View the Connectable Server Names

Hello! alexey-kachalov

I'm Youn-gi kim

First of all, thank you for your source. :)

I have some questions to ask you.

I succeeded in connecting to the opc server as your source. However, you need to know the opc server name when connecting.

  1. How to Find the Connectable Server Names..?
  2. group.ValuesChanged += GroupOnValuesChanged; //not working
    // Is not it an event that reads periodically whenever a value changes?
    // If not, can you periodically read values to multiple addresses using thread and etc..?
    best regards,

ps - I am not good at English myself so I used Google Translate. Sorry

x64 support

Is it possible to support x64?
I see that the OPC Runtime installs OpcEnum.exe in the SysWOW64 folder...

Getting the right Canonical Data Type

Hi,

I am looking for the correct way to get Canonical Data Type for tags. I have tried a few approaches but none of them work across all the OPC Server scenarios that I am testing against:

Approach 1) Using Group

            OpcDaGroup @group = server.AddGroup(GroupName, groupState);  // add group on OPC Server
            OpcDaItemResult[] results = @group.AddItems(itemDefinitions); // add items on OPC server
            foreach (OpcDaItemResult result in results) //print errors
            {
                if (result.Error.Failed)
                {
                    eventLog.WriteEntry("[Deming Capture Service] Error on create item");
                }
                else
                {
                    eventLog.WriteEntry(result.Item.ItemId + "...." +  result.Item.CanonicalDataType);
                }
            }

This prints Random.Int4....System.Int32, Random.Real4....System.Single on Matrikon OPC Simulator. What I am really looking for is the OPC Data Type like VT_R4 or the OPC Data ID like 4,3 etc. This seems to be happening because of

CanonicalDataType = TypeConverter.FromVarEnum((VarEnum) opcItemDefinition.vtCanonicalDataType);
but I am not sure how to get it back to the original form.

Approach 2) Using browse to get the item properties

            var browser = new OpcDaBrowserAuto(server);

            OpcDaItemProperties[] properties = browser.GetProperties(tags.ToArray(),
                                                                     new OpcDaPropertiesQuery(true, OpcDaItemPropertyIds.OPC_PROP_CDT));
            foreach (OpcDaItemProperties prop in properties)
            {
                foreach (OpcDaItemProperty _prop in prop.Properties)
                {
                    eventLog.WriteEntry(_prop.ItemId + "::" + _prop.Value + "::" + _prop.PropertyId + "  :: " +_prop.ToString());
                    if (_prop.PropertyId == (int)OpcDaItemPropertyIds.OPC_PROP_CDT)
                    {
                        if (_prop.Value == null)
                        {
                            tag_data_types[_prop.ItemId] = "na";
                        }
                        else
                        {
                            tag_data_types[_prop.ItemId] = _prop.Value.ToString();
                        }
                    }
                }
            }

This does seem to work on Matrikon Simulator and one more, but on another system it throws garbage values like

Error::4::1  :: 1 Item Canonical DataType (ItemId: Error, DataType TitaniumAS.Opc.Client.Common.IllegalType, Value: 4, ErrorId: OPC_E_INVALID_PID: The specified property ID is not valid for the item.)

I confirmed by using OpenOPC that the CDT values are set and OpenOPC shows them correctly. I am not sure why I get this error on a particular machine only. It's been on my head for more than a week now. Any idea what should I try or what am I missing here.

Getting a list of available OPC servers

Hey there,

great library! I've just been messing around with it today and it's working mostly great but I have one question.

Is there a way to get all available Opc servers on the machine? I know other Opc DA client libraries can do this and it's important if you don't know the name of the server.

Thanks and keep up the good work!

Bootstrap error in Winforms app

Hi,

I've installed the package into my project
I have changed threading model to MTAThread.
I call bootstrap in the main() function before the program is executed

namespace BoningRoomVisionSystemTest
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]
        static void Main()
        {
            System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.MTA);

            TitaniumAS.Opc.Client.Bootstrap.Initialize(); <-- exception here!

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new VisionSystemTest());
        }
    }
}

however when I try to call the bootstrap I receive the error: -2147417831
CoInitializeSecurity: Security must be initialized before any interfaces are marshalled or unmarshalled. It cannot be changed once initialized.

However if I follow the link provided in the Bootstrap.cs to pinvoke.net the example provided shows that the threading model should be STA. When I try this I get an exception saying that I cannot set this threading model. I think it may already be set to this, as it seemed to be the default before I commented it out in the code.

Even with STA model I still receive the same COM exception error.

After this error I cannot connect to a local OPCEnum server. I get an error saying the class is not registered, but I think it is because bootstrap has not been called.

How can I get this to work properly?

Thanks

Karl.

OPC variable write error.

This my function which i am using to write new values for OPC DA server variable. Actually, variable is MeterCount which shows the length in meters and i am making a button to reset its value(means 0). I want to write the new value from WPF application(VS 2015) but its not working... can anyone please help me with this. Reading the values is not problem its working perfectly but writing is not working.

   private void MeterReset_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            object[] opcvalues = { true , "0.00 m" };   
            HRESULT[] rs = readGroup.Write(readGroup.Items, opcvalues);
            readGroup.ValuesChanged += OnGroupValuesChanged;
            readGroup.UpdateRate = TimeSpan.FromMilliseconds(100);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Null Reference Exception

So I've compiled the script and I'm using it in Unity3D. It gives this error for a null reference exception.
image

I've already gone through the troubleshooting guide and checked all the compiling outputs.
Here is my code:

using System;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TitaniumAS.Opc.Client.Common;
using TitaniumAS.Opc.Client.Da;
using TitaniumAS.Opc.Client.Da.Browsing;

public class Test : MonoBehaviour
{

// Use this for initialization
void Start()
{
    Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1");
    using (var server = new OpcDaServer(url))
    {
        // Connect to the server first.
        server.Connect();

        // Create a group with items.
        CreateGroupWithItems(server);

        server.Groups.Should().HaveCount(1);
        server.Groups[0].Name.Should().Be("MyGroup");
        server.Groups[0].Items.Should().HaveCount(2);
        server.Groups[0].Items[0].ItemId.Should().Be("Bucket Brigade.Int4");
        server.Groups[0].Items[1].ItemId.Should().Be("Random.Int2");
    }
}

private static OpcDaGroup CreateGroupWithItems(OpcDaServer server)
{
    // Create a group with items.
    OpcDaGroup group = server.AddGroup("MyGroup");
    group.IsActive = true;

    var definition1 = new OpcDaItemDefinition
    {
        ItemId = "Bucket Brigade.Int4",
        IsActive = true
    };
    var definition2 = new OpcDaItemDefinition
    {
        ItemId = "Random.Int2",
        IsActive = true
    };
    OpcDaItemDefinition[] definitions = { definition1, definition2 };
    OpcDaItemResult[] results = group.AddItems(definitions);

    // Handle adding results.
    foreach (OpcDaItemResult result in results)
    {
        if (result.Error.Failed)
            Debug.Log("Error adding items: {0}");
    }

    return group;
}
// Update is called once per frame
void Update () {
	
}

}

Where have I gone wrong?

Subscribe to server aliases

Hi,
README.md shows how to subscribe to a group created by the client but can it subscribe to an alias already existing in the server? Can it also subscribe to tags?
Thanks in advance

ReadAsync Does Not Seem to Work Properly

First, this is a great package and I have been using it for a while with very good success. However, recently started implementing async/await TAP pattern to main program and ran into some issues with ReadAsync. It does not appear to work with implementation as shown below:

Attempt 1: The below runs inside another async method.

var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(2500));
OpcDaItemValue[] readValues = await group.ReadAsync(group.Items, cts.Token);

-- seems like the cancellation token does not have any effect

Attempt 2:: The below runs inside another async method.

var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromMilliseconds(2500));
OpcDaItemValue[] readValues = await group.ReadAsync(group.Items, cts.Token);

-- seems like the cancellation token does not have any effect

Also, if group.Items count happens to be 0, the ReadAsync fails somewhere and hangs and never returns to the caller.

Disconnect not working

Hello,
when I try to disconnect from OPC server using server.Dispose(), server.Disconnect() or using() { } nothing happens and the application never proceed with the next step.

Any suggestion?

Thank

ExternalException (0x80040154): CoCreateInstanceEx: Class not registered

Hello,

I tried using your project to make a small test app but I get this Exception when trying to connect...

************** Texte de l'exception **************
System.Runtime.InteropServices.ExternalException (0x80040154): CoCreateInstanceEx: Classe non enregistrée

à TitaniumAS.Opc.Client.Interop.System.Com.CreateInstance(Guid clsid, String host, NetworkCredential credential)
à TitaniumAS.Opc.Client.Common.OpcServerEnumeratorAuto.CLSIDFromProgId(String progId, String host)
à TitaniumAS.Opc.Client.Da.OpcDaServer.<>c__DisplayClass7.b__4(String host, String progId)
à TitaniumAS.Opc.Client.Common.UrlParser.Parse[T](Uri opcServerUrl, Func3 withProgId, Func3 withCLSID)
à TitaniumAS.Opc.Client.Da.OpcDaServer.Connect()
à OPCTester.Form1.button1_Click(Object sender, EventArgs e) dans C:\Users\EB.NIKLAS\Desktop\TitaniumAS.Opc.Client-master\TitaniumAS.Opc.Client-master\OPCTester\Form1.cs:ligne 32
à System.Windows.Forms.Control.OnClick(EventArgs e)
à System.Windows.Forms.Button.OnClick(EventArgs e)
à System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
à System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
à System.Windows.Forms.Control.WndProc(Message& m)
à System.Windows.Forms.ButtonBase.WndProc(Message& m)
à System.Windows.Forms.Button.WndProc(Message& m)
à System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
à System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
à System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

This is the simple code I used:

`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TitaniumAS.Opc.Client.Common;
using TitaniumAS.Opc.Client.Da;
using TitaniumAS.Opc.Client.Da.Browsing;

namespace OPCTester
{
public partial class Form1 : Form
{
OpcDaBrowserAuto browser;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Make an URL of OPC DA server using builder.
        Uri url = UrlBuilder.Build(textBox1.Text);
        var server = new OpcDaServer(url);

        // Connect to the server first.
        server.Connect();

        // Create a browser and browse all elements recursively.
        browser = new OpcDaBrowserAuto(server);
        BrowseChildren(browser);


    }

    void BrowseChildren(IOpcDaBrowser browser, string itemId = null, int indent = 0)
    {
        try
        {
            // When itemId is null, root elements will be browsed.
            OpcDaBrowseElement[] elements = browser.GetElements(itemId);

            // Output elements.
            foreach (OpcDaBrowseElement element in elements)
            {
                string text = new String(' ', indent);
                text += element;
                ListViewItem lvi = new ListViewItem();
                lvi.SubItems.Add(text);
                lvi.BackColor = Color.Red;
                listView1.Items.Insert(0, lvi);
                // Output the element.



                // Skip elements without children.
                if (!element.HasChildren)
                    continue;

                // Output children of the element.
                BrowseChildren(browser, element.ItemId, indent + 2);
            }
        }
        catch (Exception e) {

            ListViewItem lvi = new ListViewItem();
            lvi.SubItems.Add(e.ToString());
            lvi.BackColor = Color.Red;
            listView1.Items.Insert(0, lvi);                
        }
    }

}

}

Do you know what the problem might be?`

Browsing elements throws exception

I am trying to browse the elements as shown in the readme

            Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1");
            using (var server = new OpcDaServer(url))
            {
                // Connect to the server first.
                server.Connect();

                var browser = new OpcDaBrowserAuto(server);
                BrowseChildren(browser);
            }

However, I am getting an exception when itemId is null (as shown in the attached image). Any ideas what may be going wrong?
excep

ItemId error

Hello,

I have just set up an application to retrieve data by OPC. Everything works perfectly well, however, when I want to retrieve data and their name contains the ":" character, my programme returns an error.

Do you know if there is a way to add variable names with the ":" character in a group?

Variable: D13:Drive.Speed.Act

Below is a simplified piece of code from my program with one of the variables I have a problem with:

using System;
using TitaniumAS.Opc.Client.Da;
using System.Threading;

namespace OPCDA
{
class Program
{
static void Main(string[] args)
{
const string AdresseServeur = "ServerAddress"; //Adresse du serveur OPC
const string IpServeur = "ServerIP"; //Adresse du serveur OPC
const string TypeServeurOPC = "opcda"; //Adresse du serveur OPC

        var uriBuilder = new UriBuilder
        {
            Scheme = TypeServeurOPC,
            Host = IpServeur,
            Path = AdresseServeur
        };
        var uri = uriBuilder.Uri;

        TitaniumAS.Opc.Client.Bootstrap.Initialize();

        using (var server = new OpcDaServer(uri))
        {
            server.Connect();

            OpcDaGroup group = server.AddGroup("MyGroup");
            group.IsActive = true;

            var itemBool = new OpcDaItemDefinition
            {
                ItemId = "D13:Drive.Speed.Act",
                IsActive = true
            };

            OpcDaItemDefinition[] opcDaItems = { itemBool };
            OpcDaItemResult[] results = group.AddItems(opcDaItems);

            foreach (OpcDaItemResult result in results)
            {
                if (result.Error.Failed)
                    Console.WriteLine("Error adding items: {0}", result.Error);
            }

            while (true)
            {
                OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device);
                Console.WriteLine("Value is {0}", Convert.ToString(values[0].Value));
                Thread.Sleep(3000);
            }
        }
    }
}

}

Thank you in advance for your help.

Best regards,

Unable to cast COM object of type 'System.__ComObject' to interface type 'TitaniumAS.Opc.Client.Interop.Da.IOPCBrowse'

I'm trying to connect DA v2.0 and this give error below

System.InvalidCastException: 'Unable to cast COM object of type 'System.__ComObject' to interface type 'TitaniumAS.Opc.Client.Interop.Da.IOPCBrowse'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{39227004-A18F-4B57-8B0A-5235670F4468}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).'
the OPC DA is on opcda://localhost/Server.1
Do I need to setup DCOM or something on this error?

error occurred while connecting to remote OPC Serve

While using this code when trying to connect to remote OPC server through an OPC Client we get the following error:

11/26/2016 4:44:03 AM :Error MessageCoCreateInstanceEx: Server execution failed
StackTrace : at TitaniumAS.Opc.Client.Interop.System.Com.CreateInstance(Guid clsid, String host, NetworkCredential credential)
at TitaniumAS.Opc.Client.Common.OpcServerEnumeratorAuto.CLSIDFromProgId(String progId, String host)
at TitaniumAS.Opc.Client.Da.OpcDaServer.<>c__DisplayClass7.b__4(String host, String progId)
at TitaniumAS.Opc.Client.Common.UrlParser.Parse[T](Uri opcServerUrl, Func3 withProgId, Func3 withCLSID)
at TitaniumAS.Opc.Client.Da.OpcDaServer.Connect()
at OPC_Client.Form1.ReadValuesSynchronously() in e:\OPC_Client\Form1.cs:line 46

Can someone help us in overcoming this error

NuGet Package Version

I just noticed that the NuGet package is still at v1.0.2 (from 04/20/2016), and it's missing some patches and upgrades (e.g. async connect, etc.).

Do you plan to release a new package version on NuGet (with the latest repo code)?

Fetch and show real time data on same page...

Dear sir,

I made wpf application which fetch opcda data using your library and i am able to show real-time data on screen for one opc server.....

Now I want to show multiple opc server data on same screen....

How can i achieve this on same page??

Thanks,

Item on Error

Hi,

is it possible to get the item when an error occurs (adding to group and on subscription)

golem

Can't connect to OPC DA server, missing NoOpLogger.cs

Hi All,

I'm trying to connect to a OPC DA sim server running on my local machine,
and created a new .NETCore 2.1 Console app, downloaded the TitaniumAS.Opc.Client.NetCore Nuget package.

I run Windows 10, x64, Visual Studio 2017
Its missing a NoOpLogger.cs file. Should I worry?

Using TitaniumAS in Unity - Security error

I'm attempting to use your project within Unity3D but I'm getting a Initialize Security issue.

Full error note:

ExternalException: CoInitializeSecurity: Security must be initialized before any interfaces are marshalled or unmarshalled. It cannot be changed once initialized.

TitaniumAS.Opc.Client.Interop.System.Com.InitializeSecurity () (at <90125a9bf9174c0aae2889f6f6adea56>:0)
TitaniumAS.Opc.Client.Bootstrap.Initialize () (at <90125a9bf9174c0aae2889f6f6adea56>:0)
Rethrow as OpcClientException: Unable to initialize OPC DA client. It should run under MTA apartment state due to CoInitializeSecurity call. See http://www.pinvoke.net/default.aspx/ole32/CoInitializeSecurity.html for details.
TitaniumAS.Opc.Client.Bootstrap.Initialize () (at <90125a9bf9174c0aae2889f6f6adea56>:0)
Connection.OnEnable () (at Assets/Scripts/Connection.cs:19)

I'm struggling to find where I override the current security settings with the settings specified at the URL in the error message.

Any help would be great appreciated.

Thanks

AddItems slow response

Hello everyone,
I suddenly have and issue with the method AddItems.
I have multiple threads thall continuously write and read from the OPC. And for each time I add the OPC group with their Items.
But here:
OpcDaItemDefinition[] definitions = {definition1, definition2};
OpcDaItemResult[] results = group.AddItems(definitions);

The second line (when calling AddItems) many times it takes more than a minute to be complete, delaying any read or write function.
Any idea why? and how to avoid this delay?
Thanks

OpcDaItemResult.Error.Failed - 'FAILED' is ambiguous

I am unable to read the result of a .AddItems() call.
The OpcDaItemResult.Item object is fine.
Both OpcDaItemResult.Error.Failed or OpcDaItemResult.Error.Success Cause an error in VS 2015 VB.NET,

BC31429 'FAILED' is ambiguous because multiple kinds of members with this name exist in structure 'HRESULT'.

I am unable to effectively follow your example code because result.Error.Failed will not compile with above issue.

OpcDaItemResult[] results = group.AddItems(definitions);
// Handle adding results.
foreach (OpcDaItemResult result in results)
{
    if (result.Error.Failed)
        Console.WriteLine("Error adding items: {0}", result.Error);
}

Any advice on the issue here? I am using 1.0.2 of your DLL.

OPC DA Client gets old timestamps from items

Hi,
I'm trying to read somew real dato from an opc server. I'm able to read the data but after 7 minutes of reading the data Timestamp is older than the Timestamp I was reading.
For example:
item:1 value 1 timestamp: 13/06/2017 11:31:10
item:1 value 1 timestamp: 13/06/2017 11:31:20
item:1 value 1 timestamp: 13/06/2017 11:31:30
After a time, (without rtestarting the server or the client or the pc) then the read data are
item:1 value 1 timestamp: 13/06/2017 11:21:10
item:1 value 1 timestamp: 13/06/2017 11:21:20
item:1 value 1 timestamp: 13/06/2017 11:21:30
I've tried syn and async reading with same results.
I need to get the newest value only And I don´t kwon why I get old timestamps suddenly. What can I be doing wrong?
Thanks in advance,

exeption while accessing data using DA Client

I am using TitaniumAS opc client to access data from OPC-DA Server. My windows Program runs fine for few cycles, but then throws exception. More prominently , when I kill the executable and start again. Below is the stack trance.
Any clues about possible cause will help me to isolate and fix the problem..

Server connected 16:27:00
2020/10/16 16:29:15:672 [ERROR] TitaniumAS.Opc.Client.Common.ComWrapper - Error: System.Runtime.InteropServices.COMException (0x80010105): The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))
   at TitaniumAS.Opc.Client.Interop.Da.IOPCGroupStateMgt.GetState(Int32& pUpdateRate, Boolean& pActive, String& ppName, Int32& pTimeBias, Single& pPercentDeadband, Int32& pLCID, Int32& phClientGroup, Int32& phServerGroup)
   at TitaniumAS.Opc.Client.Da.Wrappers.OpcGroupStateMgt.<>c__DisplayClass5.<GetState>b__4()
   at TitaniumAS.Opc.Client.Common.ComWrapper.DoComCall(Object comObject, String methodName, Action comAction, Object[] arguments) Method name: IOPCGroupStateMgt::GetState Object: 4436986
Server disconnected 16:30:26

Unhandled Exception: System.Runtime.InteropServices.COMException: The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))
   at TitaniumAS.Opc.Client.Interop.Da.IOPCGroupStateMgt.GetState(Int32& pUpdateRate, Boolean& pActive, String& ppName, Int32& pTimeBias, Single& pPercentDeadband, Int32& pLCID, Int32& phClientGroup, Int32& phServerGroup)
   at TitaniumAS.Opc.Client.Da.Wrappers.OpcGroupStateMgt.<>c__DisplayClass5.<GetState>b__4()
   at TitaniumAS.Opc.Client.Common.ComWrapper.DoComCall(Object comObject, String methodName, Action comAction, Object[] arguments)
   at TitaniumAS.Opc.Client.Da.Wrappers.OpcGroupStateMgt.GetState(TimeSpan& updateRate, Boolean& active, String& name, TimeSpan& timeBias, Single& percentDeadband, Int32& lcid, Int32& clientHandle, Int32& serverHandle)
   at TitaniumAS.Opc.Client.Da.OpcDaGroup.SyncState()
   at TitaniumAS.Opc.Client.Da.OpcDaGroup..ctor(Object groupComObject, OpcDaServer opcDaServer)
   at TitaniumAS.Opc.Client.Da.OpcDaServer.AddGroup(String name, OpcDaGroupState state)
   at DADataAcquisition.DataAcquitionService.addItemsToDAGroup(OpcDaServer server, OpcServerDevice device) in C:\Users\milind\source\repos\DADataAcquisition\DADataAcquisition\DataAcquitionService.cs:line 36
   at DADataAcquisition.DataAcquitionService.<OnTimerEvent>d__7.MoveNext() in C:\Users\milind\source\repos\DADataAcquisition\DADataAcquisition\DataAcquitionService.cs:line 80
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Exception when connecting to RSLinx server: class not registered

Hello,
I am trying to connect to an RSLinx server with Titanium and i get the following exception:

**An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in TitaniumAS.Opc.Client.dll

Additional information: CoCreateInstanceEx: Class not registered**

Is RSLinx not supported?

Unable to cast 'System.__ComObject' to IOPCGroupStateMgt2

Please suggest me how can I handle this issue. is there any way I can force OPC client to use IOPCGroupStateMgt.

Exception:
System.InvalidCastException: 'Unable to cast COM object of type 'System.__ComObject' to interface type 'TitaniumAS.Opc.Client.Interop.Da.IOPCGroupStateMgt2'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{8E368666-D72E-4F78-87ED-647611C61C9F}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).'

Trying to write to Kepserver V6

When I try to write some items to the server it's giving an error
OPC DA 2.x not supported by the server. However, the server does support 1,0 2,0 2,05a 3.0

How could go around this problem?

Siemens OPC DA

Hi.

Is Titanium compatible with Siemens OPC DA? Im trying to connect, but always getting errors...

Error "File not found"

Uri url = UrlBuilder.Build("dOPCSim.Kassl.Simulation");
var server = new OpcServer(url) // ERROR file not found

The server is installed and worked with other OPCDA clients. Project compiled with x86, 32 bit.
What possible problems could there be?

And one more qustion/ Is it posible to browse available opc servers (local and remote)?
Thanks!

"CoCreateInstanceEx: Access is denied"

While connecting remote OPC DA server using TitaniumAs Opc client, getting "CoCreateInstanceEx: Access is denied". How to handle this issue? Is it possible to connect without configuring COM-DCOM settings.

OPC Server gives previous timestamp sometimes

I am using this library to build an app. I am using Matrikon OPC Simulator for DA protocol. I noticed that sometimes the values read from OPC Server are from past. It would be like a series of near-real-time values and then there would be a series of values from about 7-8 minutes back. Then again the near-real-time values and so on. This looks pretty weird to me and I am not sure what/where is the issue lying.

The app is a windows service that uses Timer to wake up every 1 second and get the data from OPC Server. It uses locks and timer disabling to make sure that only one thread be running at a time. The data read is interpreted in a custom Class which is then written as JSON files to the hdd.

public partial class OPCDAPollingService : ServiceBase
{
    private System.Timers.Timer timer;
    protected override void OnStart(string[] args)
    {
        var groupState = new OpcDaGroupState
        {
            Culture = CultureInfo.CurrentCulture, //set LCID for group - some OPC servers may be sensitive for this
            IsActive = true, //only active group can be subscribed
            PercentDeadband = 0.0f, //percent deadband
            TimeBias = TimeSpan.Zero,
            UpdateRate = TimeSpan.FromMilliseconds(UpdateRateInMilliseconds),
            UserData = "some userdata" //user data
        };
        Uri url = UrlBuilder.Build(opcServerName);
        server = new OpcDaServer(url);
        server.Connect();
        opcGroup = server.AddGroup(GroupName, groupState);  // add group on OPC Server
        OpcDaItemResult[] results = opcGroup.AddItems(itemDefinitions); // add items on OPC server
        foreach (OpcDaItemResult result in results) //print errors
        {
            if (result.Error.Failed)
            {
                eventLog.WriteEntry("[Deming Capture Service] Error on create item");
            }
            else
            {
                eventLog.WriteEntry(result.Item.ItemId + "...." + result.Item.CanonicalDataType);
            }
        }
        this.timer = new System.Timers.Timer(UpdateRateInMilliseconds);
        this.timer.AutoReset = false;
        this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.ReadOPCandWrite);
        this.timer.Start();
    }
    protected override void OnStop()
    {
        server.Disconnect();
    }
    private void ReadOPCandWrite(object sender, System.Timers.ElapsedEventArgs e){
        timer.Stop();
        lock (_lock)
        {
            ReadOPCTagValues();
            
        }
        timer.Start();
    }
    private void ReadOPCTagValues()
    {
        eventLog.WriteEntry(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + 
            " @ " + "Beginning OPC Server Query");
        TelemetryDataCaptured tdc = new TelemetryDataCaptured();
        Task<OpcDaItemValue[]> task = opcGroup.ReadAsync(opcGroup.Items);
        task.Wait();
        OpcDaItemValue[] itemValues = task.Result;
        foreach (OpcDaItemValue value in itemValues)
        {
          eventLog.WriteEntry(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + " @ " +
                value.Timestamp.ToString()
                );
          TagData tagdata = new TagData(value.Item.ItemId, value.Value.ToString(), value.Timestamp);
          tdc.capturedData.Add(tagdata);
        }

        tdc.WritePortableData(cacheDir);
    }
}

The log generated looks something like below. This is generated from eventLog so it's in reverse chronological order with the latest event on top. Notice that at 8:53:52 the results were correct, but the next instant it changes.

Information	9/5/2017 8:53:56 AM	OPCDAPollingClient	0	None	4 @ 9/5/2017 8:46:46 AM +00:00
Information	9/5/2017 8:53:56 AM	OPCDAPollingClient	0	None	4 @ 9/5/2017 8:46:46 AM +00:00
Information	9/5/2017 8:53:55 AM	OPCDAPollingClient	0	None	4 @ Beginning OPC Server Query
Information	9/5/2017 8:53:55 AM	OPCDAPollingClient	0	None	8 @ 9/5/2017 8:46:45 AM +00:00
Information	9/5/2017 8:53:55 AM	OPCDAPollingClient	0	None	8 @ 9/5/2017 8:46:45 AM +00:00
Information	9/5/2017 8:53:55 AM	OPCDAPollingClient	0	None	8 @ Beginning OPC Server Query
Information	9/5/2017 8:53:54 AM	OPCDAPollingClient	0	None	4 @ 9/5/2017 8:46:44 AM +00:00
Information	9/5/2017 8:53:54 AM	OPCDAPollingClient	0	None	4 @ 9/5/2017 8:46:44 AM +00:00
Information	9/5/2017 8:53:54 AM	OPCDAPollingClient	0	None	4 @ Beginning OPC Server Query
Information	9/5/2017 8:53:53 AM	OPCDAPollingClient	0	None	4 @ 9/5/2017 8:46:43 AM +00:00
Information	9/5/2017 8:53:53 AM	OPCDAPollingClient	0	None	4 @ 9/5/2017 8:46:43 AM +00:00
Information	9/5/2017 8:53:53 AM	OPCDAPollingClient	0	None	4 @ Beginning OPC Server Query
Information	9/5/2017 8:53:52 AM	OPCDAPollingClient	0	None	8 @ 9/5/2017 8:53:52 AM +00:00
Information	9/5/2017 8:53:52 AM	OPCDAPollingClient	0	None	8 @ 9/5/2017 8:53:52 AM +00:00
Information	9/5/2017 8:53:52 AM	OPCDAPollingClient	0	None	8 @ Beginning OPC Server Query
Information	9/5/2017 8:53:51 AM	OPCDAPollingClient	0	None	5 @ 9/5/2017 8:53:51 AM +00:00
Information	9/5/2017 8:53:51 AM	OPCDAPollingClient	0	None	5 @ 9/5/2017 8:53:51 AM +00:00
Information	9/5/2017 8:53:51 AM	OPCDAPollingClient	0	None	5 @ Beginning OPC Server Query
Information	9/5/2017 8:53:50 AM	OPCDAPollingClient	0	None	8 @ 9/5/2017 8:53:50 AM +00:00
Information	9/5/2017 8:53:50 AM	OPCDAPollingClient	0	None	8 @ 9/5/2017 8:53:50 AM +00:00
Information	9/5/2017 8:53:50 AM	OPCDAPollingClient	0	None	8 @ Beginning OPC Server Query
Information	9/5/2017 8:53:49 AM	OPCDAPollingClient	0	None	4 @ 9/5/2017 8:53:49 AM +00:00
Information	9/5/2017 8:53:49 AM	OPCDAPollingClient	0	None	4 @ 9/5/2017 8:53:49 AM +00:00
Information	9/5/2017 8:53:49 AM	OPCDAPollingClient	0	None	4 @ Beginning OPC Server Query
Information	9/5/2017 8:53:49 AM	OPCDAPollingClient	0	None	5 @ 9/5/2017 8:53:48 AM +00:00
Information	9/5/2017 8:53:49 AM	OPCDAPollingClient	0	None	5 @ 9/5/2017 8:53:48 AM +00:00
Information	9/5/2017 8:53:48 AM	OPCDAPollingClient	0	None	5 @ Beginning OPC Server Query
Information	9/5/2017 8:53:48 AM	OPCDAPollingClient	0	None	8 @ 9/5/2017 8:53:48 AM +00:00
Information	9/5/2017 8:53:48 AM	OPCDAPollingClient	0	None	8 @ 9/5/2017 8:53:48 AM +00:00
Information	9/5/2017 8:53:48 AM	OPCDAPollingClient	0	None	8 @ Beginning OPC Server Query

Any thoughts on this?

Matrikon OPC Server for DDE

Hi,
Browsing works fine with address "Matrikon.OPC.Simulation.1" but it doesn't work when I change the address to "Matrikon.OPC.DDE.1". I'm using the 30 day free trial. Do you know if there is something different or any limitation?
Thanks

Debug Idea: Return Item with correct ItemId if adding item to group fails

Hey,

just an idea/suggestion here - I was adding a lot of OPC items to group and one of them had an error (typo in opc tag) causing the entire group to fail. It took me a while to find it since when the item is added to group the result.Error is set but the item itself is not returned so it's not possible to see which Item caused the error (unless you breakpoint in Titanium code).

I fixed this with a workaround where I return a dummy item with the correct Itemid when result.Error is not null - See my modified CreateItemResults function:

        private OpcDaItemResult[] CreateItemResults(IList<OpcDaItemDefinition> itemDefinitions, OPCITEMDEF[] pItemArray,
            OPCITEMRESULT[] opcDaItemResults, HRESULT[] ppErrors, bool setGroup)
        {
            var results = new OpcDaItemResult[pItemArray.Length];
            for (int index = 0; index < opcDaItemResults.Length; index++)
            {
                OPCITEMRESULT opcItemResult = opcDaItemResults[index];
                OpcDaItemDefinition opcItemDefinition = itemDefinitions[index];
                HRESULT error = ppErrors[index];

                if (error.Succeeded)
                {
                    var item = new OpcDaItem(opcItemDefinition, opcItemResult, setGroup ? this : null)
                    {
                        UserData = opcItemDefinition.UserData
                    };
                    results[index] = new OpcDaItemResult(item, error);
                }
                else
                {
                    // JT we still want the item even if it failed to add (for Debug)
                    var item = new OpcDaItem(opcItemDefinition, opcItemResult, setGroup ? this : null)
                    {
                        UserData = opcItemDefinition.UserData
                    };
                    results[index] = new OpcDaItemResult(item, error);
                }
            }
            return results;
        }

This allows you to print out or handle the Item(s) that caused the issue, i.e:

                OpcDaItemResult[] results = group.AddItems(definitions);

                // Handle adding results.
                foreach (OpcDaItemResult result in results)
                {
                    if (result.Error.Failed)
                    {
                        Log.Error(string.Format("CVGroup error adding items: {0} - {1}", result.Error, result.Item));
                    }
                }

There is probably a better/more elegant way of doing this but just an idea implementation here. This can help a lot with debugging incorrect Opc handles in my opinion.

Keep up the great work!

Server Disconnect

It appears that when the OPC Server disconnects all clients, the codes needs to implement the re-connection / re-subscription process.

To this end there seems to be 2 events on the server object: ConnectionStateChanged and Shutdown.

For us the ConnectionStateChanged event only fired if it was subscribed to before connection and indicated that a connection had been made. The event did not seem to fire when the OPC server was shutdown (i.e. when the connection was disconnected). As a result, this event did not seem to fire at all if made after the initial connection.

For us the Shutdown even fired when implemented is some simple code (expansion of the sample code provided with the project) but when the same event subscription was made in more complex code that uses multiple threads (one for each client), the event did not seem to fire for any of the clients (when the OPC Server was shutdown).

What is the recommended way for detecting OPC Server communication loss and implementing an automatic re-connection?

SafeArrayTypeMismatchException

Hi all,

using the Matrikon OPC simulation server I can read OPC items easily. It worked like a charm right from the start!

However, I am trying to communicate with an OPC server of another vendor (ABB), and then I get the below exception.

From the stacktrace I can make out that the datatype in the managed code and unmanaged code is not the same or not marshalled correctly (??). But I have not the knowledge nor the expertise so that I can deduce what needs to be altered for this to work.

Can anybody here help me with this? Of push me in the right direction?
Any support is much appreciated

Unhandled Exception: System.Runtime.InteropServices.SafeArrayTypeMismatchException: Mismatch has occurred between the runtime type of the array and the sub type recorded in the metadata.
at System.Runtime.InteropServices.Marshal.PtrToStructureHelper(IntPtr ptr, Object structure, Boolean allowValueClasses)
at System.Runtime.InteropServices.Marshal.PtrToStructure(IntPtr ptr, Type structureType)
at TitaniumAS.Opc.Client.Da.Internal.ArrayHelpers.CreateOpcItemResults(OPCITEMDEF[] pItemArray, IntPtr ppAddResults)
at TitaniumAS.Opc.Client.Da.Wrappers.OpcItemMgt.<>c__DisplayClass5.b__4()
at TitaniumAS.Opc.Client.Common.ComWrapper.DoComCall[TResult](Object comObject, String methodName, Func1 comAction, Object[] arguments) at TitaniumAS.Opc.Client.Da.Wrappers.OpcItemMgt.AddItems(OPCITEMDEF[] itemDefinitions, HRESULT[]& errors) at TitaniumAS.Opc.Client.Da.OpcDaGroup.AddItems(IList1 itemDefinitions)
at OPC_DA_Client.OPCRead..ctor(OpcDaServer opcDaServer) in C:\Users\tverwaal\source\repos\OPC_DA_Client\OPC_DA_Client\OPCRead.cs:line 41
at OPC_DA_Client.OPCProcess.Initialize() in C:\Users\tverwaal\source\repos\OPC_DA_Client\OPC_DA_Client\OPCProcess.cs:line 62
at OPC_DA_Client.Program.RunApplication() in C:\Users\tverwaal\source\repos\OPC_DA_Client\OPC_DA_Client\Program.cs:line 45
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

Bootstrap Throwing Error about CoInitializeSecurity

Hi,

I'm currently facing some issue with the initialization of the DA Client. The external exception throws: CoInitializeSecurity: Security must be initialized before any interfaces are marshalled or unmarshalled. It cannot be changed once initialized.

Can anybody point me how to start console application with this library?

System Access Violation exception

my opc server is kepware and before this line, i connected successfully to the server
but i receive this error when run this line in your sample :
OpcDaItemResult[] results = group.AddItems(definitions);

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

please help me.

thanks

.NET Core Version

I would like to know if there is a .NET Core version of TitaniumAS.Opc.Client, developed by your contributors, in the works.

I see that there is TitaniumAS.Opc.Client.NetCore on the NPM, however, the project URL is broken and we are experiencing a few issues/bugs with this framework version (compared to your .NET Framework version)

System.TypeInitializationException

Hello,
I want to write a OPC-Client in C# and connect it to a OPC-Server, which is running on the Raspberry Pi (with Codesys). Then I want to send some integer values to the Server. My problem is that can't get a connection to the server. I get the following exception:

System.TypeInitializationException: "The type initializer for 'TitaniumAS.Opc.Client.Common.ComWrapper' threw an exception."
No. 1: ConfigurationException: Failed obtaining configuration for Common.Logging from configuration section 'common/logging'.
No. 2: FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

This is my Code:


using System;
using TitaniumAS.Opc.Client.Common;
using TitaniumAS.Opc.Client;
using TitaniumAS.Opc.Client.Da;

namespace OPC_Client
{
        class Program
        {
            static void Main(string[] args)
            {
            System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.MTA);

            Bootstrap.Initialize();

            Uri url = UrlBuilder.Build("opc.tcp://ip:4840");        //"ip" is the raspberry pi ip-adress
 
            using (var _server = new OpcDaServer(url))          //EXCEPTION
                {
                _server.Connect();   
                }
            }
        }
}

The TitaniumAS.Opc.Client NuGet package is installed.
I don't have a problem to get a connection to the server with the program "Unified Automation UaExpert", but I have to use a C# program.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.