FormUtils.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. using Opc.Ua;
  2. using Opc.Ua.Client;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace OpcUaHelper
  9. {
  10. /// <summary>
  11. /// 辅助类
  12. /// </summary>
  13. public class FormUtils
  14. {
  15. /// <summary>
  16. /// Gets the display text for the access level attribute.
  17. /// </summary>
  18. /// <param name="accessLevel">The access level.</param>
  19. /// <returns>The access level formatted as a string.</returns>
  20. private static string GetAccessLevelDisplayText( byte accessLevel )
  21. {
  22. StringBuilder buffer = new StringBuilder( );
  23. if (accessLevel == AccessLevels.None)
  24. {
  25. buffer.Append( "None" );
  26. }
  27. if ((accessLevel & AccessLevels.CurrentRead) == AccessLevels.CurrentRead)
  28. {
  29. buffer.Append( "Read" );
  30. }
  31. if ((accessLevel & AccessLevels.CurrentWrite) == AccessLevels.CurrentWrite)
  32. {
  33. if (buffer.Length > 0)
  34. {
  35. buffer.Append( " | " );
  36. }
  37. buffer.Append( "Write" );
  38. }
  39. if ((accessLevel & AccessLevels.HistoryRead) == AccessLevels.HistoryRead)
  40. {
  41. if (buffer.Length > 0)
  42. {
  43. buffer.Append( " | " );
  44. }
  45. buffer.Append( "HistoryRead" );
  46. }
  47. if ((accessLevel & AccessLevels.HistoryWrite) == AccessLevels.HistoryWrite)
  48. {
  49. if (buffer.Length > 0)
  50. {
  51. buffer.Append( " | " );
  52. }
  53. buffer.Append( "HistoryWrite" );
  54. }
  55. if ((accessLevel & AccessLevels.SemanticChange) == AccessLevels.SemanticChange)
  56. {
  57. if (buffer.Length > 0)
  58. {
  59. buffer.Append( " | " );
  60. }
  61. buffer.Append( "SemanticChange" );
  62. }
  63. return buffer.ToString( );
  64. }
  65. /// <summary>
  66. /// Gets the display text for the event notifier attribute.
  67. /// </summary>
  68. /// <param name="eventNotifier">The event notifier.</param>
  69. /// <returns>The event notifier formatted as a string.</returns>
  70. private static string GetEventNotifierDisplayText( byte eventNotifier )
  71. {
  72. StringBuilder buffer = new StringBuilder( );
  73. if (eventNotifier == EventNotifiers.None)
  74. {
  75. buffer.Append( "None" );
  76. }
  77. if ((eventNotifier & EventNotifiers.SubscribeToEvents) == EventNotifiers.SubscribeToEvents)
  78. {
  79. buffer.Append( "Subscribe" );
  80. }
  81. if ((eventNotifier & EventNotifiers.HistoryRead) == EventNotifiers.HistoryRead)
  82. {
  83. if (buffer.Length > 0)
  84. {
  85. buffer.Append( " | " );
  86. }
  87. buffer.Append( "HistoryRead" );
  88. }
  89. if ((eventNotifier & EventNotifiers.HistoryWrite) == EventNotifiers.HistoryWrite)
  90. {
  91. if (buffer.Length > 0)
  92. {
  93. buffer.Append( " | " );
  94. }
  95. buffer.Append( "HistoryWrite" );
  96. }
  97. return buffer.ToString( );
  98. }
  99. /// <summary>
  100. /// Gets the display text for the value rank attribute.
  101. /// </summary>
  102. /// <param name="valueRank">The value rank.</param>
  103. /// <returns>The value rank formatted as a string.</returns>
  104. private static string GetValueRankDisplayText( int valueRank )
  105. {
  106. switch (valueRank)
  107. {
  108. case ValueRanks.Any: return "Any";
  109. case ValueRanks.Scalar: return "Scalar";
  110. case ValueRanks.ScalarOrOneDimension: return "ScalarOrOneDimension";
  111. case ValueRanks.OneOrMoreDimensions: return "OneOrMoreDimensions";
  112. case ValueRanks.OneDimension: return "OneDimension";
  113. case ValueRanks.TwoDimensions: return "TwoDimensions";
  114. }
  115. return valueRank.ToString( );
  116. }
  117. /// <summary>
  118. /// Gets the display text for the specified attribute.
  119. /// </summary>
  120. /// <param name="session">The currently active session.</param>
  121. /// <param name="attributeId">The id of the attribute.</param>
  122. /// <param name="value">The value of the attribute.</param>
  123. /// <returns>The attribute formatted as a string.</returns>
  124. public static string GetAttributeDisplayText( Session session, uint attributeId, Variant value )
  125. {
  126. if (value == Variant.Null)
  127. {
  128. return String.Empty;
  129. }
  130. switch (attributeId)
  131. {
  132. case Attributes.AccessLevel:
  133. case Attributes.UserAccessLevel:
  134. {
  135. byte? field = value.Value as byte?;
  136. if (field != null)
  137. {
  138. return GetAccessLevelDisplayText( field.Value );
  139. }
  140. break;
  141. }
  142. case Attributes.EventNotifier:
  143. {
  144. byte? field = value.Value as byte?;
  145. if (field != null)
  146. {
  147. return GetEventNotifierDisplayText( field.Value );
  148. }
  149. break;
  150. }
  151. case Attributes.DataType:
  152. {
  153. return session.NodeCache.GetDisplayText( value.Value as NodeId );
  154. }
  155. case Attributes.ValueRank:
  156. {
  157. int? field = value.Value as int?;
  158. if (field != null)
  159. {
  160. return GetValueRankDisplayText( field.Value );
  161. }
  162. break;
  163. }
  164. case Attributes.NodeClass:
  165. {
  166. int? field = value.Value as int?;
  167. if (field != null)
  168. {
  169. return ((NodeClass)field.Value).ToString( );
  170. }
  171. break;
  172. }
  173. case Attributes.NodeId:
  174. {
  175. NodeId field = value.Value as NodeId;
  176. if (!NodeId.IsNull( field ))
  177. {
  178. return field.ToString( );
  179. }
  180. return "Null";
  181. }
  182. }
  183. // check for byte strings.
  184. if (value.Value is byte[])
  185. {
  186. return Utils.ToHexString( value.Value as byte[] );
  187. }
  188. // use default format.
  189. return value.ToString( );
  190. }
  191. /// <summary>
  192. /// Discovers the servers on the local machine.
  193. /// </summary>
  194. /// <param name="configuration">The configuration.</param>
  195. /// <returns>A list of server urls.</returns>
  196. public static IList<string> DiscoverServers( ApplicationConfiguration configuration )
  197. {
  198. List<string> serverUrls = new List<string>( );
  199. // set a short timeout because this is happening in the drop down event.
  200. EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create( configuration );
  201. endpointConfiguration.OperationTimeout = 5000;
  202. // Connect to the local discovery server and find the available servers.
  203. using (DiscoveryClient client = DiscoveryClient.Create( new Uri( "opc.tcp://localhost:4840" ), endpointConfiguration ))
  204. {
  205. ApplicationDescriptionCollection servers = client.FindServers( null );
  206. // populate the drop down list with the discovery URLs for the available servers.
  207. for (int ii = 0; ii < servers.Count; ii++)
  208. {
  209. if (servers[ii].ApplicationType == ApplicationType.DiscoveryServer)
  210. {
  211. continue;
  212. }
  213. for (int jj = 0; jj < servers[ii].DiscoveryUrls.Count; jj++)
  214. {
  215. string discoveryUrl = servers[ii].DiscoveryUrls[jj];
  216. // Many servers will use the '/discovery' suffix for the discovery endpoint.
  217. // The URL without this prefix should be the base URL for the server.
  218. if (discoveryUrl.EndsWith( "/discovery" ))
  219. {
  220. discoveryUrl = discoveryUrl.Substring( 0, discoveryUrl.Length - "/discovery".Length );
  221. }
  222. // ensure duplicates do not get added.
  223. if (!serverUrls.Contains( discoveryUrl ))
  224. {
  225. serverUrls.Add( discoveryUrl );
  226. }
  227. }
  228. }
  229. }
  230. return serverUrls;
  231. }
  232. /// <summary>
  233. /// Finds the endpoint that best matches the current settings.
  234. /// </summary>
  235. /// <param name="discoveryUrl">The discovery URL.</param>
  236. /// <param name="useSecurity">if set to <c>true</c> select an endpoint that uses security.</param>
  237. /// <returns>The best available endpoint.</returns>
  238. public static EndpointDescription SelectEndpoint( string discoveryUrl, bool useSecurity )
  239. {
  240. // needs to add the '/discovery' back onto non-UA TCP URLs.
  241. if (!discoveryUrl.StartsWith( Utils.UriSchemeOpcTcp ))
  242. {
  243. if (!discoveryUrl.EndsWith( "/discovery" ))
  244. {
  245. discoveryUrl += "/discovery";
  246. }
  247. }
  248. // parse the selected URL.
  249. Uri uri = new Uri( discoveryUrl );
  250. // set a short timeout because this is happening in the drop down event.
  251. EndpointConfiguration configuration = EndpointConfiguration.Create( );
  252. configuration.OperationTimeout = 5000;
  253. EndpointDescription selectedEndpoint = null;
  254. // Connect to the server's discovery endpoint and find the available configuration.
  255. using (DiscoveryClient client = DiscoveryClient.Create( uri, configuration ))
  256. {
  257. EndpointDescriptionCollection endpoints = client.GetEndpoints( null );
  258. // select the best endpoint to use based on the selected URL and the UseSecurity checkbox.
  259. for (int ii = 0; ii < endpoints.Count; ii++)
  260. {
  261. EndpointDescription endpoint = endpoints[ii];
  262. // check for a match on the URL scheme.
  263. if (endpoint.EndpointUrl.StartsWith( uri.Scheme ))
  264. {
  265. // check if security was requested.
  266. if (useSecurity)
  267. {
  268. if (endpoint.SecurityMode == MessageSecurityMode.None)
  269. {
  270. continue;
  271. }
  272. }
  273. else
  274. {
  275. if (endpoint.SecurityMode != MessageSecurityMode.None)
  276. {
  277. continue;
  278. }
  279. }
  280. // pick the first available endpoint by default.
  281. if (selectedEndpoint == null)
  282. {
  283. selectedEndpoint = endpoint;
  284. }
  285. // The security level is a relative measure assigned by the server to the
  286. // endpoints that it returns. Clients should always pick the highest level
  287. // unless they have a reason not too.
  288. if (endpoint.SecurityLevel > selectedEndpoint.SecurityLevel)
  289. {
  290. selectedEndpoint = endpoint;
  291. }
  292. }
  293. }
  294. // pick the first available endpoint by default.
  295. if (selectedEndpoint == null && endpoints.Count > 0)
  296. {
  297. selectedEndpoint = endpoints[0];
  298. }
  299. }
  300. // if a server is behind a firewall it may return URLs that are not accessible to the client.
  301. // This problem can be avoided by assuming that the domain in the URL used to call
  302. // GetEndpoints can be used to access any of the endpoints. This code makes that conversion.
  303. // Note that the conversion only makes sense if discovery uses the same protocol as the endpoint.
  304. Uri endpointUrl = Utils.ParseUri( selectedEndpoint.EndpointUrl );
  305. if (endpointUrl != null && endpointUrl.Scheme == uri.Scheme)
  306. {
  307. UriBuilder builder = new UriBuilder( endpointUrl );
  308. builder.Host = uri.DnsSafeHost;
  309. builder.Port = uri.Port;
  310. selectedEndpoint.EndpointUrl = builder.ToString( );
  311. }
  312. // return the selected endpoint.
  313. return selectedEndpoint;
  314. }
  315. /// <summary>
  316. /// Browses the address space and returns the references found.
  317. /// </summary>
  318. /// <param name="session">The session.</param>
  319. /// <param name="nodesToBrowse">The set of browse operations to perform.</param>
  320. /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
  321. /// <returns>
  322. /// The references found. Null if an error occurred.
  323. /// </returns>
  324. public static ReferenceDescriptionCollection Browse( ISession session, BrowseDescriptionCollection nodesToBrowse, bool throwOnError )
  325. {
  326. try
  327. {
  328. ReferenceDescriptionCollection references = new ReferenceDescriptionCollection( );
  329. BrowseDescriptionCollection unprocessedOperations = new BrowseDescriptionCollection( );
  330. while (nodesToBrowse.Count > 0)
  331. {
  332. // start the browse operation.
  333. BrowseResultCollection results = null;
  334. DiagnosticInfoCollection diagnosticInfos = null;
  335. session.Browse(
  336. null,
  337. null,
  338. 0,
  339. nodesToBrowse,
  340. out results,
  341. out diagnosticInfos );
  342. ClientBase.ValidateResponse( results, nodesToBrowse );
  343. ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToBrowse );
  344. ByteStringCollection continuationPoints = new ByteStringCollection( );
  345. for (int ii = 0; ii < nodesToBrowse.Count; ii++)
  346. {
  347. // check for error.
  348. if (StatusCode.IsBad( results[ii].StatusCode ))
  349. {
  350. // this error indicates that the server does not have enough simultaneously active
  351. // continuation points. This request will need to be resent after the other operations
  352. // have been completed and their continuation points released.
  353. if (results[ii].StatusCode == StatusCodes.BadNoContinuationPoints)
  354. {
  355. unprocessedOperations.Add( nodesToBrowse[ii] );
  356. }
  357. continue;
  358. }
  359. // check if all references have been fetched.
  360. if (results[ii].References.Count == 0)
  361. {
  362. continue;
  363. }
  364. // save results.
  365. references.AddRange( results[ii].References );
  366. // check for continuation point.
  367. if (results[ii].ContinuationPoint != null)
  368. {
  369. continuationPoints.Add( results[ii].ContinuationPoint );
  370. }
  371. }
  372. // process continuation points.
  373. ByteStringCollection revisedContiuationPoints = new ByteStringCollection( );
  374. while (continuationPoints.Count > 0)
  375. {
  376. // continue browse operation.
  377. session.BrowseNext(
  378. null,
  379. true,
  380. continuationPoints,
  381. out results,
  382. out diagnosticInfos );
  383. ClientBase.ValidateResponse( results, continuationPoints );
  384. ClientBase.ValidateDiagnosticInfos( diagnosticInfos, continuationPoints );
  385. for (int ii = 0; ii < continuationPoints.Count; ii++)
  386. {
  387. // check for error.
  388. if (StatusCode.IsBad( results[ii].StatusCode ))
  389. {
  390. continue;
  391. }
  392. // check if all references have been fetched.
  393. if (results[ii].References.Count == 0)
  394. {
  395. continue;
  396. }
  397. // save results.
  398. references.AddRange( results[ii].References );
  399. // check for continuation point.
  400. if (results[ii].ContinuationPoint != null)
  401. {
  402. revisedContiuationPoints.Add( results[ii].ContinuationPoint );
  403. }
  404. }
  405. // check if browsing must continue;
  406. revisedContiuationPoints = continuationPoints;
  407. }
  408. // check if unprocessed results exist.
  409. nodesToBrowse = unprocessedOperations;
  410. }
  411. // return complete list.
  412. return references;
  413. }
  414. catch (Exception exception)
  415. {
  416. if (throwOnError)
  417. {
  418. throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
  419. }
  420. return null;
  421. }
  422. }
  423. /// <summary>
  424. /// Finds the type of the event for the notification.
  425. /// </summary>
  426. /// <param name="monitoredItem">The monitored item.</param>
  427. /// <param name="notification">The notification.</param>
  428. /// <returns>The NodeId of the EventType.</returns>
  429. public static NodeId FindEventType( MonitoredItem monitoredItem, EventFieldList notification )
  430. {
  431. EventFilter filter = monitoredItem.Status.Filter as EventFilter;
  432. if (filter != null)
  433. {
  434. for (int ii = 0; ii < filter.SelectClauses.Count; ii++)
  435. {
  436. SimpleAttributeOperand clause = filter.SelectClauses[ii];
  437. if (clause.BrowsePath.Count == 1 && clause.BrowsePath[0] == BrowseNames.EventType)
  438. {
  439. return notification.EventFields[ii].Value as NodeId;
  440. }
  441. }
  442. }
  443. return null;
  444. }
  445. /// <summary>
  446. /// Browses the address space and returns the references found.
  447. /// </summary>
  448. /// <param name="session">The session.</param>
  449. /// <param name="nodeToBrowse">The NodeId for the starting node.</param>
  450. /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
  451. /// <returns>
  452. /// The references found. Null if an error occurred.
  453. /// </returns>
  454. public static ReferenceDescriptionCollection Browse( Session session, BrowseDescription nodeToBrowse, bool throwOnError )
  455. {
  456. try
  457. {
  458. ReferenceDescriptionCollection references = new ReferenceDescriptionCollection( );
  459. // construct browse request.
  460. BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );
  461. nodesToBrowse.Add( nodeToBrowse );
  462. // start the browse operation.
  463. BrowseResultCollection results = null;
  464. DiagnosticInfoCollection diagnosticInfos = null;
  465. session.Browse(
  466. null,
  467. null,
  468. 0,
  469. nodesToBrowse,
  470. out results,
  471. out diagnosticInfos );
  472. ClientBase.ValidateResponse( results, nodesToBrowse );
  473. ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToBrowse );
  474. do
  475. {
  476. // check for error.
  477. if (StatusCode.IsBad( results[0].StatusCode ))
  478. {
  479. throw new ServiceResultException( results[0].StatusCode );
  480. }
  481. // process results.
  482. for (int ii = 0; ii < results[0].References.Count; ii++)
  483. {
  484. references.Add( results[0].References[ii] );
  485. }
  486. // check if all references have been fetched.
  487. if (results[0].References.Count == 0 || results[0].ContinuationPoint == null)
  488. {
  489. break;
  490. }
  491. // continue browse operation.
  492. ByteStringCollection continuationPoints = new ByteStringCollection( );
  493. continuationPoints.Add( results[0].ContinuationPoint );
  494. session.BrowseNext(
  495. null,
  496. false,
  497. continuationPoints,
  498. out results,
  499. out diagnosticInfos );
  500. ClientBase.ValidateResponse( results, continuationPoints );
  501. ClientBase.ValidateDiagnosticInfos( diagnosticInfos, continuationPoints );
  502. }
  503. while (true);
  504. //return complete list.
  505. return references;
  506. }
  507. catch (Exception exception)
  508. {
  509. if (throwOnError)
  510. {
  511. throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
  512. }
  513. return null;
  514. }
  515. }
  516. /// <summary>
  517. /// Browses the address space and returns all of the supertypes of the specified type node.
  518. /// </summary>
  519. /// <param name="session">The session.</param>
  520. /// <param name="typeId">The NodeId for a type node in the address space.</param>
  521. /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
  522. /// <returns>
  523. /// The references found. Null if an error occurred.
  524. /// </returns>
  525. public static ReferenceDescriptionCollection BrowseSuperTypes( Session session, NodeId typeId, bool throwOnError )
  526. {
  527. ReferenceDescriptionCollection supertypes = new ReferenceDescriptionCollection( );
  528. try
  529. {
  530. // find all of the children of the field.
  531. BrowseDescription nodeToBrowse = new BrowseDescription( );
  532. nodeToBrowse.NodeId = typeId;
  533. nodeToBrowse.BrowseDirection = BrowseDirection.Inverse;
  534. nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype;
  535. nodeToBrowse.IncludeSubtypes = false; // more efficient to use IncludeSubtypes=False when possible.
  536. nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types.
  537. nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
  538. ReferenceDescriptionCollection references = Browse( session, nodeToBrowse, throwOnError );
  539. while (references != null && references.Count > 0)
  540. {
  541. // should never be more than one supertype.
  542. supertypes.Add( references[0] );
  543. // only follow references within this server.
  544. if (references[0].NodeId.IsAbsolute)
  545. {
  546. break;
  547. }
  548. // get the references for the next level up.
  549. nodeToBrowse.NodeId = (NodeId)references[0].NodeId;
  550. references = Browse( session, nodeToBrowse, throwOnError );
  551. }
  552. // return complete list.
  553. return supertypes;
  554. }
  555. catch (Exception exception)
  556. {
  557. if (throwOnError)
  558. {
  559. throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
  560. }
  561. return null;
  562. }
  563. }
  564. /// <summary>
  565. /// Constructs an event object from a notification.
  566. /// </summary>
  567. /// <param name="session">The session.</param>
  568. /// <param name="monitoredItem">The monitored item that produced the notification.</param>
  569. /// <param name="notification">The notification.</param>
  570. /// <param name="knownEventTypes">The known event types.</param>
  571. /// <param name="eventTypeMappings">Mapping between event types and known event types.</param>
  572. /// <returns>
  573. /// The event object. Null if the notification is not a valid event type.
  574. /// </returns>
  575. public static BaseEventState ConstructEvent(
  576. Session session,
  577. MonitoredItem monitoredItem,
  578. EventFieldList notification,
  579. Dictionary<NodeId, Type> knownEventTypes,
  580. Dictionary<NodeId, NodeId> eventTypeMappings )
  581. {
  582. // find the event type.
  583. NodeId eventTypeId = FindEventType( monitoredItem, notification );
  584. if (eventTypeId == null)
  585. {
  586. return null;
  587. }
  588. // look up the known event type.
  589. Type knownType = null;
  590. NodeId knownTypeId = null;
  591. if (eventTypeMappings.TryGetValue( eventTypeId, out knownTypeId ))
  592. {
  593. knownType = knownEventTypes[knownTypeId];
  594. }
  595. // try again.
  596. if (knownType == null)
  597. {
  598. if (knownEventTypes.TryGetValue( eventTypeId, out knownType ))
  599. {
  600. knownTypeId = eventTypeId;
  601. eventTypeMappings.Add( eventTypeId, eventTypeId );
  602. }
  603. }
  604. // try mapping it to a known type.
  605. if (knownType == null)
  606. {
  607. // browse for the supertypes of the event type.
  608. ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes( session, eventTypeId, false );
  609. // can't do anything with unknown types.
  610. if (supertypes == null)
  611. {
  612. return null;
  613. }
  614. // find the first supertype that matches a known event type.
  615. for (int ii = 0; ii < supertypes.Count; ii++)
  616. {
  617. NodeId superTypeId = (NodeId)supertypes[ii].NodeId;
  618. if (knownEventTypes.TryGetValue( superTypeId, out knownType ))
  619. {
  620. knownTypeId = superTypeId;
  621. eventTypeMappings.Add( eventTypeId, superTypeId );
  622. }
  623. if (knownTypeId != null)
  624. {
  625. break;
  626. }
  627. }
  628. // can't do anything with unknown types.
  629. if (knownTypeId == null)
  630. {
  631. return null;
  632. }
  633. }
  634. // construct the event based on the known event type.
  635. BaseEventState e = (BaseEventState)Activator.CreateInstance( knownType, new object[] { (NodeState)null } );
  636. // get the filter which defines the contents of the notification.
  637. EventFilter filter = monitoredItem.Status.Filter as EventFilter;
  638. // initialize the event with the values in the notification.
  639. e.Update( session.SystemContext, filter.SelectClauses, notification );
  640. // save the orginal notification.
  641. e.Handle = notification;
  642. return e;
  643. }
  644. /// <summary>
  645. /// Returns the node ids for a set of relative paths.
  646. /// </summary>
  647. /// <param name="session">An open session with the server to use.</param>
  648. /// <param name="startNodeId">The starting node for the relative paths.</param>
  649. /// <param name="namespacesUris">The namespace URIs referenced by the relative paths.</param>
  650. /// <param name="relativePaths">The relative paths.</param>
  651. /// <returns>A collection of local nodes.</returns>
  652. public static List<NodeId> TranslateBrowsePaths(
  653. Session session,
  654. NodeId startNodeId,
  655. NamespaceTable namespacesUris,
  656. params string[] relativePaths )
  657. {
  658. // build the list of browse paths to follow by parsing the relative paths.
  659. BrowsePathCollection browsePaths = new BrowsePathCollection( );
  660. if (relativePaths != null)
  661. {
  662. for (int ii = 0; ii < relativePaths.Length; ii++)
  663. {
  664. BrowsePath browsePath = new BrowsePath( );
  665. // The relative paths used indexes in the namespacesUris table. These must be
  666. // converted to indexes used by the server. An error occurs if the relative path
  667. // refers to a namespaceUri that the server does not recognize.
  668. // The relative paths may refer to ReferenceType by their BrowseName. The TypeTree object
  669. // allows the parser to look up the server's NodeId for the ReferenceType.
  670. browsePath.RelativePath = RelativePath.Parse(
  671. relativePaths[ii],
  672. session.TypeTree,
  673. namespacesUris,
  674. session.NamespaceUris );
  675. browsePath.StartingNode = startNodeId;
  676. browsePaths.Add( browsePath );
  677. }
  678. }
  679. // make the call to the server.
  680. BrowsePathResultCollection results;
  681. DiagnosticInfoCollection diagnosticInfos;
  682. ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds(
  683. null,
  684. browsePaths,
  685. out results,
  686. out diagnosticInfos );
  687. // ensure that the server returned valid results.
  688. Session.ValidateResponse( results, browsePaths );
  689. Session.ValidateDiagnosticInfos( diagnosticInfos, browsePaths );
  690. // collect the list of node ids found.
  691. List<NodeId> nodes = new List<NodeId>( );
  692. for (int ii = 0; ii < results.Count; ii++)
  693. {
  694. // check if the start node actually exists.
  695. if (StatusCode.IsBad( results[ii].StatusCode ))
  696. {
  697. nodes.Add( null );
  698. continue;
  699. }
  700. // an empty list is returned if no node was found.
  701. if (results[ii].Targets.Count == 0)
  702. {
  703. nodes.Add( null );
  704. continue;
  705. }
  706. // Multiple matches are possible, however, the node that matches the type model is the
  707. // one we are interested in here. The rest can be ignored.
  708. BrowsePathTarget target = results[ii].Targets[0];
  709. if (target.RemainingPathIndex != UInt32.MaxValue)
  710. {
  711. nodes.Add( null );
  712. continue;
  713. }
  714. // The targetId is an ExpandedNodeId because it could be node in another server.
  715. // The ToNodeId function is used to convert a local NodeId stored in a ExpandedNodeId to a NodeId.
  716. nodes.Add( ExpandedNodeId.ToNodeId( target.TargetId, session.NamespaceUris ) );
  717. }
  718. // return whatever was found.
  719. return nodes;
  720. }
  721. /// <summary>
  722. /// Collects the fields for the type.
  723. /// </summary>
  724. /// <param name="session">The session.</param>
  725. /// <param name="fields">The fields.</param>
  726. /// <param name="fieldNodeIds">The node id for the declaration of the field.</param>
  727. public static void CollectFieldsForType( Session session, NodeId typeId, SimpleAttributeOperandCollection fields, List<NodeId> fieldNodeIds )
  728. {
  729. // get the supertypes.
  730. ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes( session, typeId, false );
  731. if (supertypes == null)
  732. {
  733. return;
  734. }
  735. // process the types starting from the top of the tree.
  736. Dictionary<NodeId, QualifiedNameCollection> foundNodes = new Dictionary<NodeId, QualifiedNameCollection>( );
  737. QualifiedNameCollection parentPath = new QualifiedNameCollection( );
  738. for (int ii = supertypes.Count - 1; ii >= 0; ii--)
  739. {
  740. CollectFields( session, (NodeId)supertypes[ii].NodeId, parentPath, fields, fieldNodeIds, foundNodes );
  741. }
  742. // collect the fields for the selected type.
  743. CollectFields( session, typeId, parentPath, fields, fieldNodeIds, foundNodes );
  744. }
  745. /// <summary>
  746. /// Collects the fields for the instance.
  747. /// </summary>
  748. /// <param name="session">The session.</param>
  749. /// <param name="fields">The fields.</param>
  750. /// <param name="fieldNodeIds">字段</param>
  751. /// <param name="instanceId">The node id for the declaration of the field.</param>
  752. public static void CollectFieldsForInstance( Session session, NodeId instanceId, SimpleAttributeOperandCollection fields, List<NodeId> fieldNodeIds )
  753. {
  754. Dictionary<NodeId, QualifiedNameCollection> foundNodes = new Dictionary<NodeId, QualifiedNameCollection>( );
  755. QualifiedNameCollection parentPath = new QualifiedNameCollection( );
  756. CollectFields( session, instanceId, parentPath, fields, fieldNodeIds, foundNodes );
  757. }
  758. /// <summary>
  759. /// Collects the fields for the instance node.
  760. /// </summary>
  761. /// <param name="session">The session.</param>
  762. /// <param name="nodeId">The node id.</param>
  763. /// <param name="parentPath">The parent path.</param>
  764. /// <param name="fields">The event fields.</param>
  765. /// <param name="fieldNodeIds">The node id for the declaration of the field.</param>
  766. /// <param name="foundNodes">The table of found nodes.</param>
  767. private static void CollectFields(
  768. Session session,
  769. NodeId nodeId,
  770. QualifiedNameCollection parentPath,
  771. SimpleAttributeOperandCollection fields,
  772. List<NodeId> fieldNodeIds,
  773. Dictionary<NodeId, QualifiedNameCollection> foundNodes )
  774. {
  775. // find all of the children of the field.
  776. BrowseDescription nodeToBrowse = new BrowseDescription( );
  777. nodeToBrowse.NodeId = nodeId;
  778. nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
  779. nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.Aggregates;
  780. nodeToBrowse.IncludeSubtypes = true;
  781. nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable);
  782. nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
  783. ReferenceDescriptionCollection children = FormUtils.Browse( session, nodeToBrowse, false );
  784. if (children == null)
  785. {
  786. return;
  787. }
  788. // process the children.
  789. for (int ii = 0; ii < children.Count; ii++)
  790. {
  791. ReferenceDescription child = children[ii];
  792. if (child.NodeId.IsAbsolute)
  793. {
  794. continue;
  795. }
  796. // construct browse path.
  797. QualifiedNameCollection browsePath = new QualifiedNameCollection( parentPath );
  798. browsePath.Add( child.BrowseName );
  799. // check if the browse path is already in the list.
  800. int index = ContainsPath( fields, browsePath );
  801. if (index < 0)
  802. {
  803. SimpleAttributeOperand field = new SimpleAttributeOperand( );
  804. field.TypeDefinitionId = ObjectTypeIds.BaseEventType;
  805. field.BrowsePath = browsePath;
  806. field.AttributeId = (child.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId;
  807. fields.Add( field );
  808. fieldNodeIds.Add( (NodeId)child.NodeId );
  809. }
  810. // recusively find all of the children.
  811. NodeId targetId = (NodeId)child.NodeId;
  812. // need to guard against loops.
  813. if (!foundNodes.ContainsKey( targetId ))
  814. {
  815. foundNodes.Add( targetId, browsePath );
  816. CollectFields( session, (NodeId)child.NodeId, browsePath, fields, fieldNodeIds, foundNodes );
  817. }
  818. }
  819. }
  820. /// <summary>
  821. /// Determines whether the specified select clause contains the browse path.
  822. /// </summary>
  823. /// <param name="selectClause">The select clause.</param>
  824. /// <param name="browsePath">The browse path.</param>
  825. /// <returns>
  826. /// <c>true</c> if the specified select clause contains path; otherwise, <c>false</c>.
  827. /// </returns>
  828. private static int ContainsPath( SimpleAttributeOperandCollection selectClause, QualifiedNameCollection browsePath )
  829. {
  830. for (int ii = 0; ii < selectClause.Count; ii++)
  831. {
  832. SimpleAttributeOperand field = selectClause[ii];
  833. if (field.BrowsePath.Count != browsePath.Count)
  834. {
  835. continue;
  836. }
  837. bool match = true;
  838. for (int jj = 0; jj < field.BrowsePath.Count; jj++)
  839. {
  840. if (field.BrowsePath[jj] != browsePath[jj])
  841. {
  842. match = false;
  843. break;
  844. }
  845. }
  846. if (match)
  847. {
  848. return ii;
  849. }
  850. }
  851. return -1;
  852. }
  853. }
  854. }