Implementing an OPC DA client from scratch - opc

I would like to implement my own OPC DA client (versions 2.02, 2.05a, 3.00) from scratch but without using any third-party. Also I would like to make use of OPCEnum.exe service to get a list of installed OPC servers. Is there any kind of document that explains detailed and step by step the process to implement an OPC client?

I have a c# implementation but actually it's hard to fit it in here. I'll try to summarize the steps required.
Mostly you need to have OpcRcw.Comn.dll and OpcRcw.Da.dll from the OPC Core Components Redistributable package downloable for free from Opcfoundation.org. Once installed, the files are located in C:\Windows\assembly\GAC_MSIL. Create a reference in your project.
About coding, this is what you should do (there are three objects you want to implement, Server, Group and Item):
Let's start with server:
Type typeofOPCserver = Type.GetTypeFromProgID(serverName, computerName, true);
m_opcServer = (IOPCServer)Activator.CreateInstance(typeofOPCserver);
m_opcCommon = (IOPCCommon)m_opcServer;
IConnectionPointContainer icpc = (IConnectionPointContainer)m_opcServer;
Guid sinkGUID = typeof(IOPCShutdown).GUID;
icpc.FindConnectionPoint(ref sinkGUID, out m_OPCCP);
m_OPCCP.Advise(this, out m_cookie_CP);
I've striped a LOT of checking to fit it in here, take it as a sample...
Then you need a method on server to add groups:
// Parameter as following:
// [in] active, so do OnDataChange callback
// [in] Request this Update Rate from Server
// [in] Client Handle, not necessary in this sample
// [in] No time interval to system UTC time
// [in] No Deadband, so all data changes are reported
// [in] Server uses english language to for text values
// [out] Server handle to identify this group in later calls
// [out] The answer from Server to the requested Update Rate
// [in] requested interface type of the group object
// [out] pointer to the requested interface
m_opcServer.AddGroup(m_groupName, Convert.ToInt32(m_isActive), m_reqUpdateRate, m_clientHandle, pTimeBias, pDeadband, m_LocaleID, out m_serverHandle, out m_revUpdateRate, ref iid, out objGroup);
// Get our reference from the created group
m_OPCGroupStateMgt = (IOPCGroupStateMgt)objGroup;
Finally you need to create items:
m_OPCItem = (IOPCItemMgt)m_OPCGroupStateMgt;
m_OPCItem.AddItems(itemList.Length, GetAllItemDefs(itemList), out ppResults, out ppErrors);
Where itemlist is an array of OPCITEMDEF[]. I build the above using GetAllItemDefs from a structure of mine.
private static OPCITEMDEF[] GetAllItemDefs(params OpcItem[] opcItemList)
{
OPCITEMDEF[] opcItemDefs = new OPCITEMDEF[opcItemList.Length];
for (int i = 0; i < opcItemList.Length; i++)
{
OpcItem opcItem = opcItemList[i];
opcItemDefs[i].szAccessPath = "";
opcItemDefs[i].bActive = Convert.ToInt32(opcItem.IsActive);
opcItemDefs[i].vtRequestedDataType = Convert.ToInt16(opcItem.ItemType, CultureInfo.InvariantCulture);
opcItemDefs[i].dwBlobSize = 0;
opcItemDefs[i].pBlob = IntPtr.Zero;
opcItemDefs[i].hClient = opcItem.ClientHandle;
opcItemDefs[i].szItemID = opcItem.Id;
}
return opcItemDefs;
}
Finally, about enumerating Servers, I use this two functions:
/// <summary>
/// Enumerates hosts that may be accessed for server discovery.
/// </summary>
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public string[] EnumerateHosts()
{
IntPtr pInfo;
int entriesRead = 0;
int totalEntries = 0;
int result = NetServerEnum(
IntPtr.Zero,
LEVEL_SERVER_INFO_100,
out pInfo,
MAX_PREFERRED_LENGTH,
out entriesRead,
out totalEntries,
SV_TYPE_WORKSTATION | SV_TYPE_SERVER,
IntPtr.Zero,
IntPtr.Zero);
if (result != 0)
throw new ApplicationException("NetApi Error = " + String.Format("0x{0,0:X}", result));
string[] computers = new string[entriesRead];
IntPtr pos = pInfo;
for (int ii = 0; ii < entriesRead; ii++)
{
SERVER_INFO_100 info = (SERVER_INFO_100)Marshal.PtrToStructure(pos, typeof(SERVER_INFO_100));
computers[ii] = info.sv100_name;
pos = (IntPtr)(pos.ToInt32() + Marshal.SizeOf(typeof(SERVER_INFO_100)));
}
NetApiBufferFree(pInfo);
return computers;
}
/// <summary>
/// Returns a list of servers that support the specified specification on the specified host.
/// </summary>
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public string[] GetAvailableServers(Specification specification)
{
lock (this)
{
// connect to the server.
ArrayList servers = new ArrayList();
MULTI_QI[] results = new MULTI_QI[1];
GCHandle hIID = GCHandle.Alloc(IID_IUnknown, GCHandleType.Pinned);
results[0].iid = hIID.AddrOfPinnedObject();
results[0].pItf = null;
results[0].hr = 0;
try
{
// create an instance.
Guid srvid = CLSID;
CoCreateInstanceEx(srvid, null, CLSCTX.CLSCTX_LOCAL_SERVER, IntPtr.Zero, 1, results);
m_server = (IOPCServerList2)results[0].pItf;
// convert the interface version to a guid.
Guid catid = new Guid(specification.ID);
// get list of servers in the specified specification.
IOPCEnumGUID enumerator = null;
m_server.EnumClassesOfCategories(1, new Guid[] { catid }, 0, null, out enumerator);
// read clsids.
Guid[] clsids = ReadClasses(enumerator);
// release enumerator
if (enumerator != null && enumerator.GetType().IsCOMObject)
Marshal.ReleaseComObject(enumerator);
// fetch class descriptions.
foreach (Guid clsid in clsids)
{
try
{
string url = CreateUrl(specification, clsid);
servers.Add(url);
}
catch (Exception) { }
}
}
catch
{
}
finally
{
if (hIID.IsAllocated) hIID.Free();
if (m_server != null && m_server.GetType().IsCOMObject)
Marshal.ReleaseComObject(m_server);
}
return (string[])servers.ToArray(typeof(string));
}
}
I know I've striped a lot but maybe it can still help you ;)
Please mark the answer as correct if you think I've been clear ;)
Kind Regards,
D.

Related

x710 VF use dpdk rte_flow_valida() return Function not implemented

OS:CentOS 7.3
DPDK:19.08
I use one X710 NIC, create 2 VFs in kernel driver i40e, and bind vfio-pci driver on VF 0 and Start a DPDK PMD application.
Then I try to create a Flow Rule use rte_flow, but it returns -38, Function not implemented when I called rte_flow_validate().
Does it means this VF doesn't support rte_flow API? or there are some configure or flags need to be set on VF?
DPDK RTE_FLOW are supported on both PF and VF for X710 (Fortville) NIC, with actions like
RTE_FLOW_ACTION_TYPE_QUEUE
RTE_FLOW_ACTION_TYPE_DROP
RTE_FLOW_ACTION_TYPE_PASSTHRU
RTE_FLOW_ACTION_TYPE_MARK
RTE_FLOW_ACTION_TYPE_RSS
The return value -38 for DPDK API is not Function not implemented, but actually I40E_ERR_OPCODE_MISMATCH. This means either Lookup parameters or match cases are improperly configured. Code Snippet that works on X710 VF, shared below
/* configure for 2 RX queues */
struct rte_flow_attr attr = { .ingress = 1 };
struct rte_flow_item pattern[10];
struct rte_flow_action actions[10];
struct rte_flow_item_eth eth;
struct rte_flow_item_eth eth_mask;
struct rte_flow_item_vlan vlan;
struct rte_flow_item_vlan vlan_mask;
struct rte_flow_item_ipv4 ipv4;
struct rte_flow_item_ipv4 ipv4_mask;
struct rte_flow *flow;
struct rte_flow_action_mark mark = { .id = 0xdeadbeef };
struct rte_flow_action_queue queue = { .index = 0x3 };
memset(&pattern, 0, sizeof(pattern));
memset(&actions, 0, sizeof(actions));
memset(&attr, 0, sizeof(attr));
attr.group = 0;
attr.priority = 0;
attr.ingress = 1;
attr.egress = 0;
memset(&eth_mask, 0, sizeof(struct rte_flow_item_eth));
pattern[0].type = RTE_FLOW_ITEM_TYPE_ETH;
pattern[0].spec = ð
pattern[0].last = NULL;
pattern[0].mask = NULL;
memset(&vlan_mask, 0, sizeof(struct rte_flow_item_vlan));
pattern[1].type = RTE_FLOW_ITEM_TYPE_VLAN;
pattern[1].spec = &vlan;
pattern[1].last = NULL;
pattern[1].mask = NULL;
/* set the dst ipv4 packet to the required value */
pattern[1].type = RTE_FLOW_ITEM_TYPE_IPV4;
pattern[1].spec = NULL;
pattern[1].last = NULL;
pattern[1].mask = NULL;
pattern[2].type = RTE_FLOW_ITEM_TYPE_UDP;
pattern[2].spec = NULL;
pattern[2].last = NULL;
pattern[2].mask = NULL;
/* end the pattern array */
pattern[3].type = RTE_FLOW_ITEM_TYPE_END;
/* create the drop action */
actions[0].type = RTE_FLOW_ACTION_TYPE_MARK;
actions[0].conf = &mark;
actions[1].type = RTE_FLOW_ACTION_TYPE_END;
note: request #myzhu in comments to share the actual code snippet to root cause the issue too.

Is there a way to view COM entries by traversing a TLB file in .NET?

I'm converting an application to use registration free COM. There are a few 3rd party COM dll's that would normally have regsvr32 called on them. I tested that I can create objects from these 3rd party dlls by making a side-by-side manifest.
I used the OLE/COM viewer built into Windows to get this information. However I would like to make a program that could do this for me manually, as these 3rd party libraries have lots of classes I need to put in the manifest.
Does anyone know of a way to programatically traverse a type library?
I took Hans' advice and used LoadTypeLib.
For anyone looking for example code, this should be a great starting point.
I wrote it this morning and was able to get xml that I needed.
Forgive me for not releasing the objects! I don't have time to fully flesh out the rest of this answer right now. Edits are welcome.
[DllImport("oleaut32.dll", PreserveSig = false)]
public static extern ITypeLib LoadTypeLib([In, MarshalAs(UnmanagedType.LPWStr)] string typelib);
public static void ParseTypeLib(string filePath)
{
string fileNameOnly = Path.GetFileNameWithoutExtension(filePath);
ITypeLib typeLib = LoadTypeLib(filePath);
int count = typeLib.GetTypeInfoCount();
IntPtr ipLibAtt = IntPtr.Zero;
typeLib.GetLibAttr(out ipLibAtt);
var typeLibAttr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)
Marshal.PtrToStructure(ipLibAtt, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
Guid tlbId = typeLibAttr.guid;
for(int i=0; i< count; i++)
{
ITypeInfo typeInfo = null;
typeLib.GetTypeInfo(i, out typeInfo);
//figure out what guids, typekind, and names of the thing we're dealing with
IntPtr ipTypeAttr = IntPtr.Zero;
typeInfo.GetTypeAttr(out ipTypeAttr);
//unmarshal the pointer into a structure into something we can read
var typeattr = (System.Runtime.InteropServices.ComTypes.TYPEATTR)
Marshal.PtrToStructure(ipTypeAttr, typeof(System.Runtime.InteropServices.ComTypes.TYPEATTR));
System.Runtime.InteropServices.ComTypes.TYPEKIND typeKind = typeattr.typekind;
Guid typeId = typeattr.guid;
//get the name of the type
string strName, strDocString, strHelpFile;
int dwHelpContext;
typeLib.GetDocumentation(i, out strName, out strDocString, out dwHelpContext, out strHelpFile);
if (typeKind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_COCLASS)
{
string xmlComClassFormat = "<comClass clsid=\"{0}\" tlbid=\"{1}\" description=\"{2}\" progid=\"{3}.{4}\"></comClass>";
string comClassXml = String.Format(xmlComClassFormat,
typeId.ToString("B").ToUpper(),
tlbId.ToString("B").ToUpper(),
strDocString,
fileNameOnly, strName
);
//Debug.WriteLine(comClassXml);
}
else if(typeKind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_INTERFACE)
{
string xmlProxyStubFormat = "<comInterfaceExternalProxyStub name=\"{0}\" iid=\"{1}\" tlbid=\"{2}\" proxyStubClsid32=\"{3}\"></comInterfaceExternalProxyStub>";
string proxyStubXml = String.Format(xmlProxyStubFormat,
strName,
typeId.ToString("B").ToUpper(),
tlbId.ToString("B").ToUpper(),
"{00020424-0000-0000-C000-000000000046}"
);
//Debug.WriteLine(proxyStubXml);
}
}
return;
}
}

OPC UA.NET custom Node Manager creating

I'm trying to use UA-.NETStandardLibrary by OPC Foundation to create my own OPC UA Server that will maintain some variables.
I've created a server class inherited from StandardServer and node manager inherited from CustomNodeManager2.
There were some node managers in their examples, I removed them and add my own one. The server starts normally and doesn't contain any nodes except from standard ones, as planned. So, my problem is how to create my own variable node from code (not from xml, as in examples) and be able update its value on demand.
For example, I want to add a folder with couple of nodes inside.
Does anyone have a code snippet which demonstrates how to do it? I don't want anybody write it for me, I will appreciate only if you just tell me about a right way to make it.
Thanks a lot.
I am pretty sure the snippets you are looking for are included. Here is my testing code and I am 100% positive, I didn't write the second piece of code. Anyway, if this helps you...
{
var ticker_seq = createVariable(myFolder, "MyFolder/Ticker", "Ticker", BuiltInType.UInt64, ValueRanks.Scalar);
variables.Add(ticker_seq);
subscriptions.Add(clock.Ticker.Subscribe(val =>
{
lock (Lock)
{
ticker_seq.Value = val;
ticker_seq.Timestamp = DateTime.UtcNow;
ticker_seq.ClearChangeMasks(SystemContext, false);
}
}));
}
and creation
private BaseDataVariableState createVariable(NodeState parent, string path, string name, NodeId dataType, int valueRank)
{
BaseDataVariableState variable = new BaseDataVariableState(parent);
variable.SymbolicName = name;
variable.ReferenceTypeId = ReferenceTypes.Organizes;
variable.TypeDefinitionId = VariableTypeIds.BaseDataVariableType;
variable.NodeId = new NodeId(path, NamespaceIndex);
variable.BrowseName = new QualifiedName(path, NamespaceIndex);
variable.DisplayName = new LocalizedText("en", name);
variable.WriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
variable.UserWriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
variable.DataType = dataType;
variable.ValueRank = valueRank;
variable.AccessLevel = AccessLevels.CurrentReadOrWrite;
variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite;
variable.Historizing = false;
variable.Value = 0;
variable.StatusCode = StatusCodes.Good;
variable.Timestamp = DateTime.UtcNow;
if (parent != null)
{
parent.AddChild(variable);
}
return variable;
}
creating the folder:
private FolderState CreateFolder(NodeState parent, string path, string name)
{
FolderState folder = new FolderState(parent);
folder.SymbolicName = name;
folder.ReferenceTypeId = ReferenceTypes.Organizes;
folder.TypeDefinitionId = ObjectTypeIds.FolderType;
folder.NodeId = new NodeId(path, NamespaceIndex);
folder.BrowseName = new QualifiedName(path, NamespaceIndex);
folder.DisplayName = new LocalizedText("en", name);
folder.WriteMask = AttributeWriteMask.None;
folder.UserWriteMask = AttributeWriteMask.None;
folder.EventNotifier = EventNotifiers.None;
if (parent != null)
{
parent.AddChild(folder);
}
return folder;
}

Android CalendarContract.Events.UID_2445 not populated

I am working an app that read Events of a given calendar.
public static final String[] EVENT_PROJECTION = new String[] {
Events._ID, // 0
Events.UID_2445, //1
Events.DTSTART, // 2
Events.DTEND }; // 3
// The indices for the projection array above.
private static final int PROJECTION_ID_INDEX = 0;
private static final int PROJECTION_UID_INDEX = 1;
...
ContentResolver contentResolver = ctx.getContentResolver();
Uri uri = Events.CONTENT_URI;
Cursor cur = contentResolver.query(uri,
EVENT_PROJECTION, Events.CALENDAR_ID + " = ?",
new String[] { String.valueOf(calendarId) }, null);
The calendar is synched to google calendar or Exchange Server mailbox. I am able to get the event using the code above, but the I noticed that Events.UID_2445 attribute is never populated.
String uid = cur.getString(PROJECTION_UID_INDEX)); //this line always returns null
Using google calendar data api and exchange web services, I have confirmed that it has ICAL UID attribute populated. It looks like calendar sync does not store that attribute in the Event object. Does anyone else have the same issue or do you see anything wrong with the code that I use? Thanks

Microsoft Robotics and Sql

I have an issue implementing CCR with SQL. It seems that when I step through my code the updates and inserts I am trying to execute work great. But when I run through my interface without any breakpoints, it seems to be working and it shows the inserts, updates, but at the end of the run, nothing got updated to the database.
I proceeded to add a pause to my code every time I pull anew thread from my pool and it works... but that defeats the purpose of async coding right? I want my interface to be faster, not slow it down...
Any suggestions... here is part of my code:
I use two helper classes to set my ports and get a response back...
/// <summary>
/// Gets the Reader, requires connection to be managed
/// </summary>
public static PortSet<Int32, Exception> GetReader(SqlCommand sqlCommand)
{
Port<Int32> portResponse = null;
Port<Exception> portException = null;
GetReaderResponse(sqlCommand, ref portResponse, ref portException);
return new PortSet<Int32, Exception>(portResponse, portException);
}
// Wrapper for SqlCommand's GetResponse
public static void GetReaderResponse(SqlCommand sqlCom,
ref Port<Int32> portResponse, ref Port<Exception> portException)
{
EnsurePortsExist(ref portResponse, ref portException);
sqlCom.BeginExecuteNonQuery(ApmResultToCcrResultFactory.Create(
portResponse, portException,
delegate(IAsyncResult ar) { return sqlCom.EndExecuteNonQuery(ar); }), null);
}
then I do something like this to queue up my calls...
DispatcherQueue queue = CreateDispatcher();
String[] commands = new String[2];
Int32 result = 0;
commands[0] = "exec someupdateStoredProcedure";
commands[1] = "exec someInsertStoredProcedure '" + Settings.Default.RunDate.ToString() + "'";
for (Int32 i = 0; i < commands.Length; i++)
{
using (SqlConnection connSP = new SqlConnection(Settings.Default.nbfConn + ";MultipleActiveResultSets=true;Async=true"))
using (SqlCommand cmdSP = new SqlCommand())
{
connSP.Open();
cmdSP.Connection = connSP;
cmdSP.CommandTimeout = 150;
cmdSP.CommandText = "set arithabort on; " + commands[i];
Arbiter.Activate(queue, Arbiter.Choice(ApmToCcrAdapters.GetReader(cmdSP),
delegate(Int32 reader) { result = reader; },
delegate(Exception e) { result = 0; throw new Exception(e.Message); }));
}
}
where ApmToCcrAdapters is the class name where my helper methods are...
The problem is when I pause my code right after the call to Arbiter.Activate and I check my database, everything looks fine... if I get rid of the pause ad run my code through, nothing happens to the database, and no exceptions are thrown either...
The problem here is that you are calling Arbiter.Activate in the scope of your two using blocks. Don't forget that the CCR task you create is queued and the current thread continues... right past the scope of the using blocks. You've created a race condition, because the Choice must execute before connSP and cmdSP are disposed and that's only going to happen when you're interfering with the thread timings, as you have observed when debugging.
If instead you were to deal with disposal manually in the handler delegates for the Choice, this problem would no longer occur, however this makes for brittle code where it's easy to overlook disposal.
I'd recommend implementing the CCR iterator pattern and collecting results with a MulitpleItemReceive so that you can keep your using statements. It makes for cleaner code. Off the top of my head it would look something like this:
private IEnumerator<ITask> QueryIterator(
string command,
PortSet<Int32,Exception> resultPort)
{
using (SqlConnection connSP =
new SqlConnection(Settings.Default.nbfConn
+ ";MultipleActiveResultSets=true;Async=true"))
using (SqlCommand cmdSP = new SqlCommand())
{
Int32 result = 0;
connSP.Open();
cmdSP.Connection = connSP;
cmdSP.CommandTimeout = 150;
cmdSP.CommandText = "set arithabort on; " + commands[i];
yield return Arbiter.Choice(ApmToCcrAdapters.GetReader(cmdSP),
delegate(Int32 reader) { resultPort.Post(reader); },
delegate(Exception e) { resultPort.Post(e); });
}
}
and you could use it something like this:
var resultPort=new PortSet<Int32,Exception>();
foreach(var command in commands)
{
Arbiter.Activate(queue,
Arbiter.FromIteratorHandler(()=>QueryIterator(command,resultPort))
);
}
Arbiter.Activate(queue,
Arbiter.MultipleItemReceive(
resultPort,
commands.Count(),
(results,exceptions)=>{
//everything is done and you've got 2
//collections here, results and exceptions
//to process as you want
}
)
);