//******************************************************************************************************// PIOutputAdapter.cs - Gbtc//// Copyright © 2010, Grid Protection Alliance. All Rights Reserved.//// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See// the NOTICE file distributed with this work for additional information regarding copyright ownership.// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may// not use this file except in compliance with the License. You may obtain a copy of the License at://// http://www.opensource.org/licenses/MIT//// Unless agreed to in writing, the subject software distributed under the License is distributed on an// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the// License for the specific language governing permissions and limitations.//// Code Modification History:// ----------------------------------------------------------------------------------------------------// 08/13/2012 - Ryan McCoy// Generated original version of source code.// 06/18/2014 - J. Ritchie Carroll// Optimized PI-SDK code performance with connection pooling// 12/17/2014 - J. Ritchie Carroll// Updated code to use AF-SDK - using single PIConnection for now////****************************************************************************************************** using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.IO;using System.Linq;using System.Text;using System.Threading;using GSF;using GSF.Collections;using GSF.Data;using GSF.IO;using GSF.Threading;using GSF.TimeSeries;using GSF.TimeSeries.Adapters;using OSIsoft.AF.Asset;using OSIsoft.AF.Data;using OSIsoft.AF.PI;using OSIsoft.AF.Time; namespace PIAdapters{ /// <summary> /// Exports measurements to PI if the point tag or alternate tag corresponds to a PI point's tag name. /// </summary> [Description("OSI-PI: Archives measurements to an OSI-PI server using AF-SDK")] public class PIOutputAdapter : OutputAdapterBase { #region [ Members ] // Fields // Define cached mapping between GSFSchema measurements and PI points private readonly ConcurrentDictionary<MeasurementKey, PIPoint> m_mappedPIPoints; private readonly ProcessQueue<AFValue>[] m_archiveQueues; // Collection of point archival queues private readonly ProcessQueue<MeasurementKey> m_mapRequestQueue; // Requested measurement to PI point mapping queue private readonly ShortSynchronizedOperation m_restartConnection; // Restart connection operation private readonly ConcurrentDictionary<Guid, string> m_tagMap; // Tag name to measurement Guid lookup private readonly HashSet<MeasurementKey> m_pendingMappings; // List of pending measurement mappings private PIConnection m_connection; // PI server connection for meta-data synchronization private DateTime m_lastMetadataRefresh; // Tracks time of last meta-data refresh private long m_processedMappings; // Total number of mappings processed so far private long m_processedMeasurements; // Total number of measurements processed so far private long m_totalProcessingTime; // Total point processing time private volatile bool m_refreshingMetadata; // Flag that determines if meta-data is currently refreshing private double m_metadataRefreshProgress; // Current meta-data refresh progress private bool m_disposed; // Flag that determines if class is disposed #endregion #region [ Constructors ] /// <summary> /// Creates a new <see cref="PIOutputAdapter"/> /// </summary> public PIOutputAdapter() { m_mappedPIPoints = new ConcurrentDictionary<MeasurementKey, PIPoint>(); m_archiveQueues = new ProcessQueue<AFValue>[Environment.ProcessorCount]; for (int i = 0; i < m_archiveQueues.Length; i++) m_archiveQueues[i] = ProcessQueue<AFValue>.CreateRealTimeQueue(ArchiveAFValues, Timeout.Infinite, false, false); m_mapRequestQueue = ProcessQueue<MeasurementKey>.CreateAsynchronousQueue(EstablishPIPointMappings, Environment.ProcessorCount); m_restartConnection = new ShortSynchronizedOperation(Start); m_tagMap = new ConcurrentDictionary<Guid, string>(); m_pendingMappings = new HashSet<MeasurementKey>(); m_lastMetadataRefresh = DateTime.MinValue; RunMetadataSync = true; AutoCreateTags = true; AutoUpdateTags = true; } #endregion #region [ Properties ] /// <summary> /// Returns true to indicate that this <see cref="PIOutputAdapter"/> is sending measurements to a historian, OSIsoft PI. /// </summary> public override bool OutputIsForArchive => true; /// <summary> /// Returns false to indicate that this <see cref="PIOutputAdapter"/> will connect synchronously /// </summary> protected override bool UseAsyncConnect => false; /// <summary> /// Gets or sets the name of the PI server for the adapter's PI connection. /// </summary> [ConnectionStringParameter, Description("Defines the name of the PI server for the adapter's PI connection.")] public string ServerName { get; set; } /// <summary> /// Gets or sets the name of the PI user ID for the adapter's PI connection. /// </summary> [ConnectionStringParameter, Description("Defines the name of the PI user ID for the adapter's PI connection."), DefaultValue("")] public string UserName { get; set; } /// <summary> /// Gets or sets the password used for the adapter's PI connection. /// </summary> [ConnectionStringParameter, Description("Defines the password used for the adapter's PI connection."), DefaultValue("")] public string Password { get; set; } /// <summary> /// Gets or sets the timeout interval (in milliseconds) for the adapter's connection /// </summary> [ConnectionStringParameter, Description("Defines the timeout interval (in milliseconds) for the adapter's connection"), DefaultValue(PIConnection.DefaultConnectTimeout)] public int ConnectTimeout { get; set; } /// <summary> /// Gets or sets whether or not this adapter should automatically manage metadata for PI points. /// </summary> [ConnectionStringParameter, Description("Determines if this adapter should automatically manage metadata for PI points (recommended)."), DefaultValue(true)] public bool RunMetadataSync { get; set; } /// <summary> /// Gets or sets whether or not this adapter should automatically manage metadata for PI points. /// </summary> [ConnectionStringParameter, Description("Determines if this adapter should automatically create new tags when managing metadata for PI points (recommended). Value will only be considered when RunMetadataSync is True."), DefaultValue(true)] public bool AutoCreateTags { get; set; } /// <summary> /// Gets or sets whether or not this adapter should automatically manage metadata for PI points. /// </summary> [ConnectionStringParameter, Description("Determines if this adapter should automatically update existing tags when managing metadata for PI points (recommended). This will make openPDC the master for maintaining PI tag metadata (like the tag name); otherwise, when False, PI will be the master. Value will only be considered when RunMetadataSync is True."), DefaultValue(true)] public bool AutoUpdateTags { get; set; } /// <summary> /// Gets or sets the number of tag name prefixes, e.g., "SOURCE!", applied by subscriptions to remove from PI tag names. /// </summary> [ConnectionStringParameter, Description("Defines the number of tag name prefixes applied by subscriptions, e.g., \"SOURCE!\", to remove from PI tag names. Value will only be considered when RunMetadataSync is True."), DefaultValue(0)] public int TagNamePrefixRemoveCount { get; set; } /// <summary> /// Gets or sets the point source string used when automatically creating new PI points during the metadata update /// </summary> [ConnectionStringParameter, Description("Defines the point source string used when automatically creating new PI points during the metadata update. Value will only be considered when RunMetadataSync is True."), DefaultValue("GSF")] public string PIPointSource { get; set; } /// <summary> /// Gets or sets the point class string used when automatically creating new PI points during the metadata update. On the PI server, this class should inherit from classic. /// </summary> [ConnectionStringParameter, Description("Defines the point class string used when automatically creating new PI points during the metadata update. On the PI server, this class should inherit from classic. Value will only be considered when RunMetadataSync is True."), DefaultValue("classic")] public string PIPointClass { get; set; } /// <summary> /// Gets or sets flag that determines if defined point compression will be used during archiving. /// </summary> [ConnectionStringParameter, Description("Defines the flag that determines if defined point compression will be used during archiving."), DefaultValue(true)] public bool UseCompression { get; set; } /// <summary> /// Gets or sets the filename to be used for tag map cache. /// </summary> [ConnectionStringParameter, Description("Defines the filename to be used for tag map cache file name. Leave blank for cache name to be same as adapter name with a \".cache\" extension."), DefaultValue("")] public string TagMapCacheFileName { get; set; } /// <summary> /// Returns the detailed status of the data output source. /// </summary> public override string Status { get { StringBuilder status = new StringBuilder(); status.Append(base.Status); status.AppendLine(); status.AppendFormat(" OSI-PI server name: {0}", ServerName); status.AppendLine(); status.AppendFormat(" Connected to server: {0}", (object)m_connection == null ? "No" : m_connection.Connected ? "Yes" : "No"); status.AppendLine(); status.AppendFormat(" Using compression: {0}", UseCompression); status.AppendLine(); status.AppendFormat(" Meta-data sync enabled: {0}", RunMetadataSync); status.AppendLine(); if (RunMetadataSync) { status.AppendFormat(" Auto-create tags: {0}", AutoCreateTags); status.AppendLine(); status.AppendFormat(" Auto-update tags: {0}", AutoUpdateTags); status.AppendLine(); status.AppendFormat(" Tag prefixes to remove: {0}", TagNamePrefixRemoveCount); status.AppendLine(); status.AppendFormat(" OSI-PI point source: {0}", PIPointSource); status.AppendLine(); status.AppendFormat(" OSI-PI point class: {0}", PIPointClass); status.AppendLine(); } if ((object)m_mapRequestQueue != null) { status.AppendLine(); status.AppendLine(">> Mapping Request Queue Status"); status.AppendLine(); status.Append(m_mapRequestQueue.Status); status.AppendLine(); } status.AppendFormat(" Tag-map cache file name: {0}", FilePath.TrimFileName(TagMapCacheFileName.ToNonNullString("[undefined]"), 51)); status.AppendLine(); status.AppendFormat(" Active tag-map cache size: {0:N0} mappings", m_mappedPIPoints.Count); status.AppendLine(); status.AppendFormat(" Pending tag-mappings: {0:N0} mappings, {1:0.00%} complete", m_pendingMappings.Count, 1.0D - m_pendingMappings.Count / (double)m_mappedPIPoints.Count); status.AppendLine(); if (RunMetadataSync) { status.AppendFormat(" Meta-data sync process: {0}, {1:0.00%} complete", m_refreshingMetadata ? "Active" : "Idle", m_metadataRefreshProgress); status.AppendLine(); } if ((object)m_archiveQueues != null && m_archiveQueues.Length > 0) { status.AppendLine(); status.AppendFormat(">> Archive Queue Status (1 of {0}){1}", m_archiveQueues.Length, Environment.NewLine); status.AppendLine(); status.Append(m_archiveQueues[0].Status); status.AppendLine(); } status.AppendFormat(" Points archived/second: {0:#,##0.00}", Interlocked.Read(ref m_processedMeasurements) / (Interlocked.Read(ref m_totalProcessingTime) / (double)Ticks.PerSecond)); status.AppendLine(); return status.ToString(); } } #endregion #region [ Methods ] /// <summary> /// Releases the unmanaged resources used by the <see cref="PIOutputAdapter"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if ((object)m_mapRequestQueue != null) m_mapRequestQueue.Dispose(); if ((object)m_archiveQueues != null) { foreach (ProcessQueue<AFValue> archiveQueue in m_archiveQueues) archiveQueue.Dispose(); } if ((object)m_connection != null) { m_connection.Disconnected -= m_connection_Disconnected; m_connection.Dispose(); m_connection = null; } if ((object)m_mappedPIPoints != null) m_mappedPIPoints.Clear(); } } finally { m_disposed = true; // Prevent duplicate dispose. base.Dispose(disposing); // Call base class Dispose(). } } } /// <summary> /// Returns a brief status of this <see cref="PIOutputAdapter"/> /// </summary> /// <param name="maxLength">Maximum number of characters in the status string</param> /// <returns>Status</returns> public override string GetShortStatus(int maxLength) { return $"Archived {m_processedMeasurements:N0} measurements to PI.".CenterText(maxLength); } /// <summary> /// Initializes this <see cref="PIOutputAdapter"/>. /// </summary> public override void Initialize() { base.Initialize(); Dictionary<string, string> settings = Settings; string setting; int intValue; if (!settings.TryGetValue(nameof(ServerName), out setting)) throw new InvalidOperationException($"The \"{nameof(ServerName)}\" setting is required for PI connections."); ServerName = setting; UserName = settings.TryGetValue(nameof(UserName), out setting) ? setting : null; Password = settings.TryGetValue(nameof(Password), out setting) ? setting : null; if (!settings.TryGetValue(nameof(ConnectTimeout), out setting) || !int.TryParse(setting, out intValue)) intValue = PIConnection.DefaultConnectTimeout; ConnectTimeout = intValue; UseCompression = !settings.TryGetValue(nameof(UseCompression), out setting) || setting.ParseBoolean(); if (!settings.TryGetValue(nameof(TagNamePrefixRemoveCount), out setting) || !int.TryParse(setting, out intValue)) intValue = 0; TagNamePrefixRemoveCount = intValue; if (settings.TryGetValue(nameof(RunMetadataSync), out setting)) RunMetadataSync = setting.ParseBoolean(); if (settings.TryGetValue(nameof(AutoCreateTags), out setting)) AutoCreateTags = setting.ParseBoolean(); if (settings.TryGetValue(nameof(AutoUpdateTags), out setting)) AutoUpdateTags = setting.ParseBoolean(); PIPointSource = settings.TryGetValue(nameof(PIPointSource), out setting) ? setting : "GSF"; PIPointClass = settings.TryGetValue(nameof(PIPointClass), out setting) ? setting : "classic"; if (!settings.TryGetValue(nameof(TagMapCacheFileName), out setting) || string.IsNullOrWhiteSpace(setting)) setting = Name + "_TagMap.cache"; TagMapCacheFileName = FilePath.GetAbsolutePath(setting); } /// <summary> /// Connects to the configured PI server. /// </summary> protected override void AttemptConnection() { m_processedMappings = 0; m_processedMeasurements = 0; m_totalProcessingTime = 0; m_connection = new PIConnection { ServerName = this.ServerName, UserName = this.UserName, Password = this.Password, ConnectTimeout = this.ConnectTimeout }; m_connection.Disconnected += m_connection_Disconnected; m_connection.Open(); m_mappedPIPoints.Clear(); lock (m_pendingMappings) { m_pendingMappings.Clear(); } m_mapRequestQueue.Clear(); m_mapRequestQueue.Start(); foreach (ProcessQueue<AFValue> archiveQueue in m_archiveQueues) archiveQueue.Start(); // Kick off meta-data refresh RefreshMetadata(); } /// <summary> /// Closes this <see cref="PIOutputAdapter"/> connections to the PI server. /// </summary> protected override void AttemptDisconnection() { foreach (ProcessQueue<AFValue> archiveQueue in m_archiveQueues) archiveQueue.Stop(); m_mapRequestQueue.Stop(); m_mapRequestQueue.Clear(); m_mappedPIPoints.Clear(); lock (m_pendingMappings) { m_pendingMappings.Clear(); } if ((object)m_connection != null) { m_connection.Disconnected -= m_connection_Disconnected; m_connection.Dispose(); m_connection = null; } } /// <summary> /// Sorts measurements and sends them to the configured PI server in batches /// </summary> /// <param name="measurements">Measurements to queue</param> protected override void ProcessMeasurements(IMeasurement[] measurements) { if ((object)measurements == null || measurements.Length <= 0 || (object)m_connection == null) return; foreach (IMeasurement measurement in measurements) { PIPoint point; // If adapter gets disabled while executing this thread - go ahead and exit if (!Enabled) return; // Lookup connection point mapping for this measurement, if it wasn't found - go ahead and exit if (!m_mappedPIPoints.TryGetValue(measurement.Key, out point)) continue; if ((object)point == null) { // If connection point is not defined, kick off process to create a new mapping tryLines 1–500 of 1115. Load more
//****************************************************************************************************** // PIOutputAdapter.cs - Gbtc // // Copyright © 2010, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://www.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 08/13/2012 - Ryan McCoy // Generated original version of source code. // 06/18/2014 - J. Ritchie Carroll // Optimized PI-SDK code performance with connection pooling // 12/17/2014 - J. Ritchie Carroll // Updated code to use AF-SDK - using single PIConnection for now // //****************************************************************************************************** using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading; using GSF; using GSF.Collections; using GSF.Data; using GSF.IO; using GSF.Threading; using GSF.TimeSeries; using GSF.TimeSeries.Adapters; using OSIsoft.AF.Asset; using OSIsoft.AF.Data; using OSIsoft.AF.PI; using OSIsoft.AF.Time; namespace PIAdapters { /// <summary> /// Exports measurements to PI if the point tag or alternate tag corresponds to a PI point's tag name. /// </summary> [Description("OSI-PI: Archives measurements to an OSI-PI server using AF-SDK")] public class PIOutputAdapter : OutputAdapterBase { #region [ Members ] // Fields // Define cached mapping between GSFSchema measurements and PI points private readonly ConcurrentDictionary<MeasurementKey, PIPoint> m_mappedPIPoints; private readonly ProcessQueue<AFValue>[] m_archiveQueues; // Collection of point archival queues private readonly ProcessQueue<MeasurementKey> m_mapRequestQueue; // Requested measurement to PI point mapping queue private readonly ShortSynchronizedOperation m_restartConnection; // Restart connection operation private readonly ConcurrentDictionary<Guid, string> m_tagMap; // Tag name to measurement Guid lookup private readonly HashSet<MeasurementKey> m_pendingMappings; // List of pending measurement mappings private PIConnection m_connection; // PI server connection for meta-data synchronization private DateTime m_lastMetadataRefresh; // Tracks time of last meta-data refresh private long m_processedMappings; // Total number of mappings processed so far private long m_processedMeasurements; // Total number of measurements processed so far private long m_totalProcessingTime; // Total point processing time private volatile bool m_refreshingMetadata; // Flag that determines if meta-data is currently refreshing private double m_metadataRefreshProgress; // Current meta-data refresh progress private bool m_disposed; // Flag that determines if class is disposed #endregion #region [ Constructors ] /// <summary> /// Creates a new <see cref="PIOutputAdapter"/> /// </summary> public PIOutputAdapter() { m_mappedPIPoints = new ConcurrentDictionary<MeasurementKey, PIPoint>(); m_archiveQueues = new ProcessQueue<AFValue>[Environment.ProcessorCount]; for (int i = 0; i < m_archiveQueues.Length; i++) m_archiveQueues[i] = ProcessQueue<AFValue>.CreateRealTimeQueue(ArchiveAFValues, Timeout.Infinite, false, false); m_mapRequestQueue = ProcessQueue<MeasurementKey>.CreateAsynchronousQueue(EstablishPIPointMappings, Environment.ProcessorCount); m_restartConnection = new ShortSynchronizedOperation(Start); m_tagMap = new ConcurrentDictionary<Guid, string>(); m_pendingMappings = new HashSet<MeasurementKey>(); m_lastMetadataRefresh = DateTime.MinValue; RunMetadataSync = true; AutoCreateTags = true; AutoUpdateTags = true; } #endregion #region [ Properties ] /// <summary> /// Returns true to indicate that this <see cref="PIOutputAdapter"/> is sending measurements to a historian, OSIsoft PI. /// </summary> public override bool OutputIsForArchive => true; /// <summary> /// Returns false to indicate that this <see cref="PIOutputAdapter"/> will connect synchronously /// </summary> protected override bool UseAsyncConnect => false; /// <summary> /// Gets or sets the name of the PI server for the adapter's PI connection. /// </summary> [ConnectionStringParameter, Description("Defines the name of the PI server for the adapter's PI connection.")] public string ServerName { get; set; } /// <summary> /// Gets or sets the name of the PI user ID for the adapter's PI connection. /// </summary> [ConnectionStringParameter, Description("Defines the name of the PI user ID for the adapter's PI connection."), DefaultValue("")] public string UserName { get; set; } /// <summary> /// Gets or sets the password used for the adapter's PI connection. /// </summary> [ConnectionStringParameter, Description("Defines the password used for the adapter's PI connection."), DefaultValue("")] public string Password { get; set; } /// <summary> /// Gets or sets the timeout interval (in milliseconds) for the adapter's connection /// </summary> [ConnectionStringParameter, Description("Defines the timeout interval (in milliseconds) for the adapter's connection"), DefaultValue(PIConnection.DefaultConnectTimeout)] public int ConnectTimeout { get; set; } /// <summary> /// Gets or sets whether or not this adapter should automatically manage metadata for PI points. /// </summary> [ConnectionStringParameter, Description("Determines if this adapter should automatically manage metadata for PI points (recommended)."), DefaultValue(true)] public bool RunMetadataSync { get; set; } /// <summary> /// Gets or sets whether or not this adapter should automatically manage metadata for PI points. /// </summary> [ConnectionStringParameter, Description("Determines if this adapter should automatically create new tags when managing metadata for PI points (recommended). Value will only be considered when RunMetadataSync is True."), DefaultValue(true)] public bool AutoCreateTags { get; set; } /// <summary> /// Gets or sets whether or not this adapter should automatically manage metadata for PI points. /// </summary> [ConnectionStringParameter, Description("Determines if this adapter should automatically update existing tags when managing metadata for PI points (recommended). This will make openPDC the master for maintaining PI tag metadata (like the tag name); otherwise, when False, PI will be the master. Value will only be considered when RunMetadataSync is True."), DefaultValue(true)] public bool AutoUpdateTags { get; set; } /// <summary> /// Gets or sets the number of tag name prefixes, e.g., "SOURCE!", applied by subscriptions to remove from PI tag names. /// </summary> [ConnectionStringParameter, Description("Defines the number of tag name prefixes applied by subscriptions, e.g., \"SOURCE!\", to remove from PI tag names. Value will only be considered when RunMetadataSync is True."), DefaultValue(0)] public int TagNamePrefixRemoveCount { get; set; } /// <summary> /// Gets or sets the point source string used when automatically creating new PI points during the metadata update /// </summary> [ConnectionStringParameter, Description("Defines the point source string used when automatically creating new PI points during the metadata update. Value will only be considered when RunMetadataSync is True."), DefaultValue("GSF")] public string PIPointSource { get; set; } /// <summary> /// Gets or sets the point class string used when automatically creating new PI points during the metadata update. On the PI server, this class should inherit from classic. /// </summary> [ConnectionStringParameter, Description("Defines the point class string used when automatically creating new PI points during the metadata update. On the PI server, this class should inherit from classic. Value will only be considered when RunMetadataSync is True."), DefaultValue("classic")] public string PIPointClass { get; set; } /// <summary> /// Gets or sets flag that determines if defined point compression will be used during archiving. /// </summary> [ConnectionStringParameter, Description("Defines the flag that determines if defined point compression will be used during archiving."), DefaultValue(true)] public bool UseCompression { get; set; } /// <summary> /// Gets or sets the filename to be used for tag map cache. /// </summary> [ConnectionStringParameter, Description("Defines the filename to be used for tag map cache file name. Leave blank for cache name to be same as adapter name with a \".cache\" extension."), DefaultValue("")] public string TagMapCacheFileName { get; set; } /// <summary> /// Returns the detailed status of the data output source. /// </summary> public override string Status { get { StringBuilder status = new StringBuilder(); status.Append(base.Status); status.AppendLine(); status.AppendFormat(" OSI-PI server name: {0}", ServerName); status.AppendLine(); status.AppendFormat(" Connected to server: {0}", (object)m_connection == null ? "No" : m_connection.Connected ? "Yes" : "No"); status.AppendLine(); status.AppendFormat(" Using compression: {0}", UseCompression); status.AppendLine(); status.AppendFormat(" Meta-data sync enabled: {0}", RunMetadataSync); status.AppendLine(); if (RunMetadataSync) { status.AppendFormat(" Auto-create tags: {0}", AutoCreateTags); status.AppendLine(); status.AppendFormat(" Auto-update tags: {0}", AutoUpdateTags); status.AppendLine(); status.AppendFormat(" Tag prefixes to remove: {0}", TagNamePrefixRemoveCount); status.AppendLine(); status.AppendFormat(" OSI-PI point source: {0}", PIPointSource); status.AppendLine(); status.AppendFormat(" OSI-PI point class: {0}", PIPointClass); status.AppendLine(); } if ((object)m_mapRequestQueue != null) { status.AppendLine(); status.AppendLine(">> Mapping Request Queue Status"); status.AppendLine(); status.Append(m_mapRequestQueue.Status); status.AppendLine(); } status.AppendFormat(" Tag-map cache file name: {0}", FilePath.TrimFileName(TagMapCacheFileName.ToNonNullString("[undefined]"), 51)); status.AppendLine(); status.AppendFormat(" Active tag-map cache size: {0:N0} mappings", m_mappedPIPoints.Count); status.AppendLine(); status.AppendFormat(" Pending tag-mappings: {0:N0} mappings, {1:0.00%} complete", m_pendingMappings.Count, 1.0D - m_pendingMappings.Count / (double)m_mappedPIPoints.Count); status.AppendLine(); if (RunMetadataSync) { status.AppendFormat(" Meta-data sync process: {0}, {1:0.00%} complete", m_refreshingMetadata ? "Active" : "Idle", m_metadataRefreshProgress); status.AppendLine(); } if ((object)m_archiveQueues != null && m_archiveQueues.Length > 0) { status.AppendLine(); status.AppendFormat(">> Archive Queue Status (1 of {0}){1}", m_archiveQueues.Length, Environment.NewLine); status.AppendLine(); status.Append(m_archiveQueues[0].Status); status.AppendLine(); } status.AppendFormat(" Points archived/second: {0:#,##0.00}", Interlocked.Read(ref m_processedMeasurements) / (Interlocked.Read(ref m_totalProcessingTime) / (double)Ticks.PerSecond)); status.AppendLine(); return status.ToString(); } } #endregion #region [ Methods ] /// <summary> /// Releases the unmanaged resources used by the <see cref="PIOutputAdapter"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if ((object)m_mapRequestQueue != null) m_mapRequestQueue.Dispose(); if ((object)m_archiveQueues != null) { foreach (ProcessQueue<AFValue> archiveQueue in m_archiveQueues) archiveQueue.Dispose(); } if ((object)m_connection != null) { m_connection.Disconnected -= m_connection_Disconnected; m_connection.Dispose(); m_connection = null; } if ((object)m_mappedPIPoints != null) m_mappedPIPoints.Clear(); } } finally { m_disposed = true; // Prevent duplicate dispose. base.Dispose(disposing); // Call base class Dispose(). } } } /// <summary> /// Returns a brief status of this <see cref="PIOutputAdapter"/> /// </summary> /// <param name="maxLength">Maximum number of characters in the status string</param> /// <returns>Status</returns> public override string GetShortStatus(int maxLength) { return $"Archived {m_processedMeasurements:N0} measurements to PI.".CenterText(maxLength); } /// <summary> /// Initializes this <see cref="PIOutputAdapter"/>. /// </summary> public override void Initialize() { base.Initialize(); Dictionary<string, string> settings = Settings; string setting; int intValue; if (!settings.TryGetValue(nameof(ServerName), out setting)) throw new InvalidOperationException($"The \"{nameof(ServerName)}\" setting is required for PI connections."); ServerName = setting; UserName = settings.TryGetValue(nameof(UserName), out setting) ? setting : null; Password = settings.TryGetValue(nameof(Password), out setting) ? setting : null; if (!settings.TryGetValue(nameof(ConnectTimeout), out setting) || !int.TryParse(setting, out intValue)) intValue = PIConnection.DefaultConnectTimeout; ConnectTimeout = intValue; UseCompression = !settings.TryGetValue(nameof(UseCompression), out setting) || setting.ParseBoolean(); if (!settings.TryGetValue(nameof(TagNamePrefixRemoveCount), out setting) || !int.TryParse(setting, out intValue)) intValue = 0; TagNamePrefixRemoveCount = intValue; if (settings.TryGetValue(nameof(RunMetadataSync), out setting)) RunMetadataSync = setting.ParseBoolean(); if (settings.TryGetValue(nameof(AutoCreateTags), out setting)) AutoCreateTags = setting.ParseBoolean(); if (settings.TryGetValue(nameof(AutoUpdateTags), out setting)) AutoUpdateTags = setting.ParseBoolean(); PIPointSource = settings.TryGetValue(nameof(PIPointSource), out setting) ? setting : "GSF"; PIPointClass = settings.TryGetValue(nameof(PIPointClass), out setting) ? setting : "classic"; if (!settings.TryGetValue(nameof(TagMapCacheFileName), out setting) || string.IsNullOrWhiteSpace(setting)) setting = Name + "_TagMap.cache"; TagMapCacheFileName = FilePath.GetAbsolutePath(setting); } /// <summary> /// Connects to the configured PI server. /// </summary> protected override void AttemptConnection() { m_processedMappings = 0; m_processedMeasurements = 0; m_totalProcessingTime = 0; m_connection = new PIConnection { ServerName = this.ServerName, UserName = this.UserName, Password = this.Password, ConnectTimeout = this.ConnectTimeout }; m_connection.Disconnected += m_connection_Disconnected; m_connection.Open(); m_mappedPIPoints.Clear(); lock (m_pendingMappings) { m_pendingMappings.Clear(); } m_mapRequestQueue.Clear(); m_mapRequestQueue.Start(); foreach (ProcessQueue<AFValue> archiveQueue in m_archiveQueues) archiveQueue.Start(); // Kick off meta-data refresh RefreshMetadata(); } /// <summary> /// Closes this <see cref="PIOutputAdapter"/> connections to the PI server. /// </summary> protected override void AttemptDisconnection() { foreach (ProcessQueue<AFValue> archiveQueue in m_archiveQueues) archiveQueue.Stop(); m_mapRequestQueue.Stop(); m_mapRequestQueue.Clear(); m_mappedPIPoints.Clear(); lock (m_pendingMappings) { m_pendingMappings.Clear(); } if ((object)m_connection != null) { m_connection.Disconnected -= m_connection_Disconnected; m_connection.Dispose(); m_connection = null; } } /// <summary> /// Sorts measurements and sends them to the configured PI server in batches /// </summary> /// <param name="measurements">Measurements to queue</param> protected override void ProcessMeasurements(IMeasurement[] measurements) { if ((object)measurements == null || measurements.Length <= 0 || (object)m_connection == null) return; foreach (IMeasurement measurement in measurements) { PIPoint point; // If adapter gets disabled while executing this thread - go ahead and exit if (!Enabled) return; // Lookup connection point mapping for this measurement, if it wasn't found - go ahead and exit if (!m_mappedPIPoints.TryGetValue(measurement.Key, out point)) continue; if ((object)point == null) { // If connection point is not defined, kick off process to create a new mapping try