Exemplo n.º 1
0
 /// <summary>
 /// Creates a new <see cref="OutageLog"/>.
 /// </summary>
 public OutageLog()
 {
     m_writeLogWaitHandle   = new ManualResetEventSlim(false);
     m_readLogOperation     = new ShortSynchronizedOperation(ReadLog);
     m_writeLogOperation    = new ShortSynchronizedOperation(WriteLog);
     m_condenseLogOperation = new ShortSynchronizedOperation(CondenseLog);
     m_readerWriterLock     = new object();
 }
Exemplo n.º 2
0
 public PointQueue()
 {
     m_publishOperation      = new ShortSynchronizedOperation(HandlePublication, HandleException);
     m_pointQueue            = new List <Point>();
     m_publishTimer          = new Timer(s_settings.WindowSize);
     m_publishTimer.Elapsed += PublishTimer_Elapsed;
     m_publicationInterval   = Time.ToElapsedTimeString(TimeSpan.FromMilliseconds(m_publishTimer.Interval).TotalSeconds, 3).ToLower();
     m_publishTimer.Start();
 }
Exemplo n.º 3
0
        private void BulkCalculationState_Load(object sender, EventArgs e)
        {
            try
            {
                // Load current settings registering a symbolic reference to this form instance for use by default value expressions
                m_settings = new Settings(new Dictionary <string, object> {
                    { "Form", this }
                }.RegisterSymbols());

                // Restore last window size/location
                this.RestoreLayout();

                string configFile = GetConfigurationFileName();

                if (!File.Exists(configFile))
                {
                    throw new FileNotFoundException("Host service config file was not found.");
                }

                XDocument serviceConfig = XDocument.Load(configFile);

                string connectionString = serviceConfig
                                          .Descendants("systemSettings")
                                          .SelectMany(systemSettings => systemSettings.Elements("add"))
                                          .Where(element => "ConnectionString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                          .Select(element => (string)element.Attribute("value"))
                                          .FirstOrDefault();

                string dataProviderString = serviceConfig
                                            .Descendants("systemSettings")
                                            .SelectMany(systemSettings => systemSettings.Elements("add"))
                                            .Where(element => "DataProviderString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                            .Select(element => (string)element.Attribute("value"))
                                            .FirstOrDefault();

                m_connection         = new AdoDataConnection(connectionString, dataProviderString);
                m_actionAdapterTable = new TableOperations <CustomActionAdapter>(m_connection);
                RefreshActionAdapters();

                m_updateTotals = new ShortSynchronizedOperation(UpdateTotals);
                SyncCheckedListBox();
                ConnectConsole();

                m_formLoaded = true;
            }
            catch (Exception ex)
            {
                m_log.Publish(MessageLevel.Error, "FormLoad", "Failed while loading settings", exception: ex);

            #if DEBUG
                throw;
            #else
                MessageBox.Show(this, $"Failed during initialization: {ex.Message}", "Initialization Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            #endif
            }
        }
Exemplo n.º 4
0
        // Static Constructor
        static GrafanaAuthProxyController()
        {
            // Create a shared HTTP client instance
            s_http = new HttpClient(new HttpClientHandler {
                UseCookies = false
            });

            // Make sure openHistorian specific default service settings exist
            CategorizedSettingsElementCollection grafanaHosting = ConfigurationFile.Current.Settings["grafanaHosting"];

            // Make sure needed settings exist
            grafanaHosting.Add("ServerPath", DefaultServerPath, "Defines the path to the Grafana server to host - set to empty string to disable hosting.");
            grafanaHosting.Add("AuthProxyHeaderName", "X-WEBAUTH-USER", "Defines the authorization header name used for Grafana user authentication.");
            grafanaHosting.Add("InitializationTimeout", DefaultInitializationTimeout, "Defines the timeout, in seconds, for the Grafana system to initialize.");
            grafanaHosting.Add("AdminUser", "admin", "Defines the Grafana Administrator user required for managing configuration.");
            grafanaHosting.Add("LogoutResource", "Logout.cshtml", "Defines the relative URL to the logout page to use for Grafana users.");
            grafanaHosting.Add("AvatarResource", "Images/Icons/openHistorian.png", "Defines the relative URL to the 40x40px avatar image to use for Grafana users.");
            grafanaHosting.Add("HostedURL", DefaultHostedURL, "Defines the local URL to the hosted Grafana server instance. Setting is for internal use, external access to Grafana instance will be proxied via WebHostURL.");
            grafanaHosting.Add("OrganizationID", DefaultOrganizationID, "Defines the database ID of the target organization used for user synchronization.");
            grafanaHosting.Add("LastDashboardCookieName", DefaultLastDashboardCookieName, "Defines the session cookie name used to save the last visited Grafana dashboard.");

            // Get settings as currently defined in configuration file
            s_authProxyHeaderName   = grafanaHosting["AuthProxyHeaderName"].Value;
            s_initializationTimeout = grafanaHosting["InitializationTimeout"].ValueAs(DefaultInitializationTimeout) * 1000;
            s_adminUser             = grafanaHosting["AdminUser"].Value;
            s_logoutResource        = grafanaHosting["LogoutResource"].Value;
            s_avatarResource        = grafanaHosting["AvatarResource"].Value;
            s_baseUrl                 = grafanaHosting["HostedURL"].Value;
            s_organizationID          = grafanaHosting["OrganizationID"].ValueAs(DefaultOrganizationID);
            s_lastDashboardCookieName = grafanaHosting["LastDashboardCookieName"].ValueAs(DefaultLastDashboardCookieName);

            if (File.Exists(grafanaHosting["ServerPath"].ValueAs(DefaultServerPath)))
            {
                s_initializationWaitHandle = new ManualResetEventSlim();

                // Establish a synchronized operation for handling Grafana user synchronizations
                s_synchronizeUsers = new ShortSynchronizedOperation(SynchronizeUsers, ex => {
                    AggregateException aggregate = ex as AggregateException;

                    if ((object)aggregate != null)
                    {
                        foreach (Exception innerException in aggregate.Flatten().InnerExceptions)
                        {
                            OnStatusMessage($"ERROR: {innerException.Message}");
                        }
                    }
                    else
                    {
                        OnStatusMessage($"ERROR: {ex.Message}");
                    }
                });

                // Attach to event for notifications of when security context has been refreshed
                AdoSecurityProvider.SecurityContextRefreshed += AdoSecurityProvider_SecurityContextRefreshed;
            }
        }
Exemplo n.º 5
0
        private long m_ignoredErrors;           // Total ignored 400 and 500 HTTP status code errors

        #endregion

        #region [ Constructors ]

        /// <summary>
        /// Creates a new <see cref="InfluxDBOutputAdapter"/>;
        /// </summary>
        public InfluxDBOutputAdapter()
        {
            m_requestRestart = new ShortSynchronizedOperation(() =>
            {
                if (Enabled)
                {
                    Start();
                }
            });
        }
Exemplo n.º 6
0
        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_archiveQueue   = ProcessQueue <AFValue> .CreateAsynchronousQueue(ArchiveAFValues, 1.0D, Environment.ProcessorCount, 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;
        }
Exemplo n.º 7
0
 /// <summary>
 /// Receives real-time updates from PI
 /// </summary>
 public PIRTInputAdapter()
 {
     m_tagKeyMap         = new ConcurrentDictionary <int, MeasurementKey>();
     m_restartConnection = new ShortSynchronizedOperation(Start);
     m_readEvents        = new ShortSynchronizedOperation(ReadEvents);
     //m_dataUpdateObserver = new DataUpdateObserver(OnProcessException);
     //m_dataUpdateObserver.DataUpdated += m_dataUpdateObserver_DataUpdated;
     m_eventTimer           = new System.Timers.Timer(1000.0D);
     m_eventTimer.Elapsed  += m_eventTimer_Elapsed;
     m_eventTimer.AutoReset = true;
     m_eventTimer.Enabled   = false;
 }
        public MainForm()
        {
            InitializeComponent();

            m_log                  = Program.Log;
            m_messages             = new StringBuilder();
            m_appendOutputMessages = new ShortSynchronizedOperation(AppendOutputMessages,
                                                                    ex => m_log.Publish(MessageLevel.Error, "AppendOutput", "Append Output Message Exception", exception: ex));

        #if DEBUG
            m_debugBuild = true;
        #else
            m_debugBuild = false;
        #endif
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a new instance of the <see cref="DoubleBufferedQueueManager{T}"/> class.
        /// </summary>
        /// <param name="itemHandler">The method to handle processing of queued items.</param>
        /// <param name="exceptionHandler">The method to handle exceptions that occur when processing items.</param>
        public DoubleBufferedQueueManager(Action <IList <T> > itemHandler, Action <Exception> exceptionHandler)
            : this()
        {
            m_itemHandlingOperation = new ShortSynchronizedOperation(CallItemHandler, exceptionHandler);

            m_itemHandler = () =>
            {
                IList <T> items = Dequeue();

                if (items.Count > 0)
                {
                    itemHandler(items);
                }
            };
        }
Exemplo n.º 10
0
        static TargetCaches()
        {
            ResetCacheFunctions = new();

            s_resetAllCaches = new(() =>
            {
                Action[] resetCacheFunctions;

                lock (ResetCacheFunctions)
                    resetCacheFunctions = ResetCacheFunctions.ToArray();

                foreach (Action resetCache in resetCacheFunctions)
                {
                    resetCache();
                }
            });
        }
Exemplo n.º 11
0
        static TargetCaches()
        {
            ResetCacheFunctions = new List <Action>();

            s_resetAllCaches = new ShortSynchronizedOperation(() =>
            {
                Action[] resetCacheFunctions;

                lock (ResetCacheFunctions)
                    resetCacheFunctions = ResetCacheFunctions.ToArray();

                foreach (Action resetCache in resetCacheFunctions)
                {
                    resetCache();
                }
            });
        }
Exemplo n.º 12
0
        private void BulkCalculationState_Load(object sender, EventArgs e)
        {
            m_sourcePath = FilePath.GetAbsolutePath("");
            string configFile = $@"{m_sourcePath}\{SourceApp}.exe.config";

            if (!File.Exists(configFile))
            {
                m_sourcePath = $@"C:\Program Files\{SourceApp}";
                configFile   = $@"{m_sourcePath}\{SourceApp}.exe.config";
            }

            if (!File.Exists(configFile))
            {
                throw new FileNotFoundException($"Config file for {SourceApp} application \"{configFile}\" was not found.");
            }

            XDocument serviceConfig = XDocument.Load(configFile);

            string connectionString = serviceConfig
                                      .Descendants("systemSettings")
                                      .SelectMany(systemSettings => systemSettings.Elements("add"))
                                      .Where(element => "ConnectionString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                      .Select(element => (string)element.Attribute("value"))
                                      .FirstOrDefault();

            string dataProviderString = serviceConfig
                                        .Descendants("systemSettings")
                                        .SelectMany(systemSettings => systemSettings.Elements("add"))
                                        .Where(element => "DataProviderString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                        .Select(element => (string)element.Attribute("value"))
                                        .FirstOrDefault();

            m_connection         = new AdoDataConnection(connectionString, dataProviderString);
            m_actionAdapterTable = new TableOperations <CustomActionAdapter>(m_connection);
            m_actionAdapters     = m_actionAdapterTable.QueryRecordsWhere("TypeName = 'DynamicCalculator.DynamicCalculator'").ToList();

            checkedListBoxDevices.DataSource    = m_actionAdapters;
            checkedListBoxDevices.DisplayMember = "AdapterName";
            checkedListBoxDevices.ValueMember   = "Enabled";

            m_updateTotals = new ShortSynchronizedOperation(UpdateTotals);

            SyncCheckedListBox();
        }
Exemplo n.º 13
0
        public MainForm()
        {
            InitializeComponent();

            m_log = Program.Log;

            m_subscriberOperationQueue = new ConcurrentQueue <Action>();
            m_subscriberOperations     = new ShortSynchronizedOperation(() =>
            {
                while (!m_formClosing && m_subscriberOperationQueue.TryDequeue(out Action operation))
                {
                    if (m_subscriber.IsConnected)
                    {
                        operation();
                    }
                }
            },
                                                                        ex => ShowUpdateMessage($"ERROR: Operations queue exception: {ex.Message}"));

            groupBoxInputMeasurements.Tag  = groupBoxInputMeasurements.Text;
            groupBoxOutputMeasurements.Tag = groupBoxOutputMeasurements.Text;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Stops the <see cref="MultiProtocolFrameParser"/>.
        /// </summary>
        public void Stop()
        {
            WaitHandle commandWaitHandle;

            m_enabled = false;
            m_rateCalcTimer.Enabled = false;
            m_configurationFrame = null;

            // Make sure data stream is disabled
            if (!m_skipDisableRealTimeData)
            {
                commandWaitHandle = SendDeviceCommand(DeviceCommand.DisableRealTimeData);

                if ((object)commandWaitHandle != null)
                    commandWaitHandle.WaitOne(1000);
            }

            if ((object)m_dataChannel != null)
            {
                try
                {
                    m_dataChannel.Disconnect();
                }
                catch (Exception ex)
                {
                    OnParsingException(ex, "Failed to properly disconnect data channel: {0}", ex.Message);
                }
                finally
                {
                    m_dataChannel.ConnectionEstablished -= m_dataChannel_ConnectionEstablished;
                    m_dataChannel.ConnectionAttempt -= m_dataChannel_ConnectionAttempt;
                    m_dataChannel.ConnectionException -= m_dataChannel_ConnectionException;
                    m_dataChannel.ConnectionTerminated -= m_dataChannel_ConnectionTerminated;
                    m_dataChannel.ReceiveData -= m_dataChannel_ReceiveData;
                    m_dataChannel.ReceiveDataException -= m_dataChannel_ReceiveDataException;
                    m_dataChannel.SendDataException -= m_dataChannel_SendDataException;
                    m_dataChannel.UnhandledUserException -= m_dataChannel_UnhandledUserException;
                    m_dataChannel.Dispose();
                }

                m_dataChannel = null;
            }

            m_readNextBuffer = null;

            if ((object)m_serverBasedDataChannel != null)
            {
                try
                {
                    m_serverBasedDataChannel.DisconnectAll();
                }
                catch (Exception ex)
                {
                    OnParsingException(ex, "Failed to properly disconnect server based data channel: {0}", ex.Message);
                }
                finally
                {
                    m_serverBasedDataChannel.ClientConnected -= m_serverBasedDataChannel_ClientConnected;
                    m_serverBasedDataChannel.ClientDisconnected -= m_serverBasedDataChannel_ClientDisconnected;
                    m_serverBasedDataChannel.ClientConnectingException -= m_serverBasedDataChannel_ClientConnectingException;
                    m_serverBasedDataChannel.ServerStarted -= m_serverBasedDataChannel_ServerStarted;
                    m_serverBasedDataChannel.ServerStopped -= m_serverBasedDataChannel_ServerStopped;
                    m_serverBasedDataChannel.ReceiveClientData -= m_serverBasedDataChannel_ReceiveClientData;
                    m_serverBasedDataChannel.ReceiveClientDataException -= m_serverBasedDataChannel_ReceiveClientDataException;
                    m_serverBasedDataChannel.SendClientDataException -= m_serverBasedDataChannel_SendClientDataException;
                    m_serverBasedDataChannel.UnhandledUserException -= m_serverBasedDataChannel_UnhandledUserException;
                    m_serverBasedDataChannel.Dispose();
                }

                m_serverBasedDataChannel = null;
            }

            if ((object)m_commandChannel != null)
            {
                try
                {
                    m_commandChannel.Disconnect();
                }
                catch (Exception ex)
                {
                    OnParsingException(ex, "Failed to properly disconnect command channel: {0}", ex.Message);
                }
                finally
                {
                    m_commandChannel.ConnectionEstablished -= m_commandChannel_ConnectionEstablished;
                    m_commandChannel.ConnectionAttempt -= m_commandChannel_ConnectionAttempt;
                    m_commandChannel.ConnectionException -= m_commandChannel_ConnectionException;
                    m_commandChannel.ConnectionTerminated -= m_commandChannel_ConnectionTerminated;
                    m_commandChannel.ReceiveData -= m_commandChannel_ReceiveData;
                    m_commandChannel.ReceiveDataException -= m_commandChannel_ReceiveDataException;
                    m_commandChannel.SendDataException -= m_commandChannel_SendDataException;
                    m_commandChannel.UnhandledUserException -= m_commandChannel_UnhandledUserException;
                    m_commandChannel.Dispose();
                }

                m_commandChannel = null;
            }

            if ((object)m_frameParser != null)
            {
                try
                {
                    m_frameParser.Stop();
                }
                catch (Exception ex)
                {
                    OnParsingException(ex, "Failed to properly stop frame parser: {0}", ex.Message);
                }
                finally
                {
                    m_frameParser.ReceivedCommandFrame -= m_frameParser_ReceivedCommandFrame;
                    m_frameParser.ReceivedConfigurationFrame -= m_frameParser_ReceivedConfigurationFrame;
                    m_frameParser.ReceivedDataFrame -= m_frameParser_ReceivedDataFrame;
                    m_frameParser.ReceivedHeaderFrame -= m_frameParser_ReceivedHeaderFrame;
                    m_frameParser.ReceivedUndeterminedFrame -= m_frameParser_ReceivedUndeterminedFrame;
                    m_frameParser.ReceivedFrameImage -= m_frameParser_ReceivedFrameImage;
                    m_frameParser.ConfigurationChanged -= m_frameParser_ConfigurationChanged;
                    m_frameParser.ParsingException -= m_frameParser_ParsingException;
                    m_frameParser.BufferParsed -= m_frameParser_BufferParsed;

                    if ((object)ReceivedFrameBufferImage != null)
                        m_frameParser.ReceivedFrameBufferImage -= m_frameParser_ReceivedFrameBufferImage;

                    m_frameParser.Dispose();
                }

                m_frameParser = null;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Initialize data channel.
        /// </summary>
        /// <param name="settings">Key/value pairs dictionary parsed from connection string.</param>
        private void InitializeDataChannel(Dictionary<string, string> settings)
        {
            string setting;

            // Instantiate selected transport layer
            switch (m_transportProtocol)
            {
                case TransportProtocol.Tcp:
                    // The TCP transport may be set up as a server or as a client, we distinguish
                    // this simply by deriving the value of an added key/value pair in the
                    // connection string called "IsListener"
                    if (settings.TryGetValue("islistener", out setting))
                    {
                        if (setting.ParseBoolean())
                            m_serverBasedDataChannel = settings.ContainsKey("receiveFrom") ? (IServer)new SharedTcpServerReference() : new TcpServer();
                        else
                            m_dataChannel = new TcpClient();
                    }
                    else
                    {
                        // If the key doesn't exist, we assume it's a client connection
                        m_dataChannel = new TcpClient();
                    }
                    break;
                case TransportProtocol.Udp:
                    InitializeUdpDataChannel(settings);
                    break;
                case TransportProtocol.Serial:
                    m_dataChannel = new SerialClient();
                    m_initiatingSerialConnection = true;
                    break;
                case TransportProtocol.File:
                    m_dataChannel = new FileClient();

                    // For file based playback, we allow the option of auto-repeat
                    FileClient fileClient = (FileClient)m_dataChannel;
                    fileClient.FileOpenMode = FileMode.Open;
                    fileClient.FileAccessMode = FileAccess.Read;
                    fileClient.FileShareMode = FileShare.Read;
                    fileClient.ReceiveOnDemand = true;
                    fileClient.ReceiveBufferSize = ushort.MaxValue;
                    fileClient.AutoRepeat = m_autoRepeatCapturedPlayback;

                    // Setup synchronized read operation for file client operations
                    m_readNextBuffer = new ShortSynchronizedOperation(ReadNextFileBuffer, ex => OnParsingException(new InvalidOperationException("Encountered an exception while reading file data: " + ex.Message, ex)));
                    break;
                default:
                    throw new InvalidOperationException(string.Format("Transport protocol \"{0}\" is not recognized, failed to initialize data channel", m_transportProtocol));
            }

            // Handle primary data connection, this *must* be defined...
            if ((object)m_dataChannel != null)
            {
                // Setup event handlers
                m_dataChannel.ConnectionEstablished += m_dataChannel_ConnectionEstablished;
                m_dataChannel.ConnectionAttempt += m_dataChannel_ConnectionAttempt;
                m_dataChannel.ConnectionException += m_dataChannel_ConnectionException;
                m_dataChannel.ConnectionTerminated += m_dataChannel_ConnectionTerminated;
                m_dataChannel.ReceiveData += m_dataChannel_ReceiveData;
                m_dataChannel.ReceiveDataException += m_dataChannel_ReceiveDataException;
                m_dataChannel.SendDataException += m_dataChannel_SendDataException;
                m_dataChannel.UnhandledUserException += m_dataChannel_UnhandledUserException;

                // Attempt connection to device
                m_dataChannel.ReceiveBufferSize = m_bufferSize;
                m_dataChannel.ConnectionString = m_connectionString;
                m_dataChannel.MaxConnectionAttempts = m_maximumConnectionAttempts;
                m_dataChannel.ConnectAsync();
            }
            else if ((object)m_serverBasedDataChannel != null)
            {
                // Setup event handlers
                m_serverBasedDataChannel.ClientConnected += m_serverBasedDataChannel_ClientConnected;
                m_serverBasedDataChannel.ClientDisconnected += m_serverBasedDataChannel_ClientDisconnected;
                m_serverBasedDataChannel.ClientConnectingException += m_serverBasedDataChannel_ClientConnectingException;
                m_serverBasedDataChannel.ServerStarted += m_serverBasedDataChannel_ServerStarted;
                m_serverBasedDataChannel.ServerStopped += m_serverBasedDataChannel_ServerStopped;
                m_serverBasedDataChannel.ReceiveClientData += m_serverBasedDataChannel_ReceiveClientData;
                m_serverBasedDataChannel.ReceiveClientDataException += m_serverBasedDataChannel_ReceiveClientDataException;
                m_serverBasedDataChannel.SendClientDataException += m_serverBasedDataChannel_SendClientDataException;
                m_serverBasedDataChannel.UnhandledUserException += m_serverBasedDataChannel_UnhandledUserException;

                // Listen for device connection
                m_serverBasedDataChannel.ReceiveBufferSize = m_bufferSize;
                m_serverBasedDataChannel.ConfigurationString = m_connectionString;
                m_serverBasedDataChannel.MaxClientConnections = 1;
                m_serverBasedDataChannel.Start();
            }
            else
            {
                throw new InvalidOperationException("No data channel was initialized, cannot start frame parser");
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes <see cref="ModbusPoller" />.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            ConnectionStringParser <ConnectionStringParameterAttribute> parser = new ConnectionStringParser <ConnectionStringParameterAttribute>();

            parser.ParseConnectionString(ConnectionString, this);

            // Register downloader with the statistics engine
            StatisticsEngine.Register(this, "Modbus", "MOD");
            StatisticsEngine.Register(m_deviceProxy, Name, "Device", "PMU");

            // Attach to output measurements for Modbus device
            OutputMeasurements = ParseOutputMeasurements(DataSource, false, $"FILTER ActiveMeasurements WHERE Device = '{Name}'");

            // Parse derived value expressions from defined signal reference fields
            m_derivedValues = OutputMeasurements.Select(measurement => measurement.Key).ToDictionary(key => key, key =>
            {
                DataTable measurements    = DataSource.Tables["ActiveMeasurements"];
                DerivedValue derivedValue = null;
                DataRow[] records         = measurements.Select($"ID = '{key}'");

                if (records.Length > 0)
                {
                    derivedValue = ParseDerivedValue(records[0]["SignalReference"].ToNonNullString());
                }

                return(derivedValue);
            });

            m_sequences = new List <Sequence>();

            Dictionary <string, string> settings = Settings;
            string setting;
            int    sequenceCount = 0;

            if (settings.TryGetValue("sequenceCount", out setting))
            {
                int.TryParse(setting, out sequenceCount);
            }

            for (int i = 0; i < sequenceCount; i++)
            {
                if (settings.TryGetValue($"sequence{i}", out setting))
                {
                    Dictionary <string, string> sequenceSettings = setting.ParseKeyValuePairs();
                    SequenceType sequenceType = SequenceType.Read;

                    if (sequenceSettings.TryGetValue("sequenceType", out setting))
                    {
                        Enum.TryParse(setting, true, out sequenceType);
                    }

                    Sequence sequence = new Sequence(sequenceType);
                    int      groupCount;

                    if (sequenceSettings.TryGetValue("groupCount", out setting) && int.TryParse(setting, out groupCount))
                    {
                        for (int j = 0; j < groupCount; j++)
                        {
                            Group group = new Group();

                            if (sequenceSettings.TryGetValue($"groupType{j}", out setting))
                            {
                                Enum.TryParse(setting, true, out group.Type);
                            }

                            if (sequenceSettings.TryGetValue($"groupStartAddress{j}", out setting))
                            {
                                ushort.TryParse(setting, out group.StartAddress);
                            }

                            if (sequenceSettings.TryGetValue($"groupPointCount{j}", out setting))
                            {
                                ushort.TryParse(setting, out group.PointCount);
                            }

                            if (group.StartAddress > 0 && group.PointCount > 0)
                            {
                                // Load any defined write sequence values
                                if (sequence.Type == SequenceType.Write)
                                {
                                    group.DataValues = new ushort[group.PointCount];

                                    for (int k = 0; k < group.PointCount; k++)
                                    {
                                        if (sequenceSettings.TryGetValue($"group{j}DataValue{k}", out setting))
                                        {
                                            ushort.TryParse(setting, out group.DataValues[k]);
                                        }
                                    }
                                }

                                sequence.Groups.Add(group);
                            }
                        }
                    }

                    if (sequence.Groups.Count > 0)
                    {
                        m_sequences.Add(sequence);
                    }
                }
            }

            if (m_sequences.Count == 0)
            {
                throw new InvalidOperationException("No sequences defined, cannot start Modbus polling.");
            }

            // Define synchronized polling operation
            m_pollingOperation = new ShortSynchronizedOperation(PollingOperation, exception => OnProcessException(MessageLevel.Warning, exception));

            // Define polling timer
            m_pollingTimer           = new Timer(m_pollingRate);
            m_pollingTimer.AutoReset = true;
            m_pollingTimer.Elapsed  += m_pollingTimer_Elapsed;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TlsClient"/> class.
        /// </summary>
        /// <param name="connectString">Connect string of the <see cref="TlsClient"/>. See <see cref="DefaultConnectionString"/> for format.</param>
        public TlsClient(string connectString)
            : base(TransportProtocol.Tcp, connectString)
        {
            m_defaultCertificateChecker = new SimpleCertificateChecker();
            m_localCertificateSelectionCallback = DefaultLocalCertificateSelectionCallback;
            m_clientCertificates = new X509Certificate2Collection();
#if MONO
            // Tls12 is not supported under Mono as of v3.8.0
            m_enabledSslProtocols = SslProtocols.Tls;
#else
            m_enabledSslProtocols = SslProtocols.Tls12;
#endif
            m_checkCertificateRevocation = true;

            m_trustedCertificatesPath = DefaultTrustedCertificatesPath;
            m_payloadAware = DefaultPayloadAware;
            m_payloadMarker = Payload.DefaultMarker;
            m_integratedSecurity = DefaultIntegratedSecurity;
            m_ignoreInvalidCredentials = DefaultIgnoreInvalidCredentials;
            m_allowDualStackSocket = DefaultAllowDualStackSocket;
            m_maxSendQueueSize = DefaultMaxSendQueueSize;
            m_dumpPayloadsOperation = new ShortSynchronizedOperation(DumpPayloads, OnSendDataException);
        }
Exemplo n.º 18
0
 /// <summary>
 /// Creates a new instance of the <see cref="DoubleBufferedQueueManager{T}"/> class.
 /// </summary>
 /// <param name="itemHandler">The method to handle processing of queued items.</param>
 /// <param name="exceptionHandler">The method to handle exceptions that occur when processing items.</param>
 public DoubleBufferedQueueManager(Action <IList <T> > itemHandler, Action <Exception> exceptionHandler)
     : this()
 {
     m_itemHandlingOperation = new ShortSynchronizedOperation(CallItemHandler, exceptionHandler);
     m_itemHandler           = () => itemHandler(Dequeue());
 }
Exemplo n.º 19
0
 /// <summary>
 /// Creates a new instance of the <see cref="DoubleBufferedQueueManager{T}"/> class.
 /// </summary>
 /// <param name="itemHandler">The method to handle processing of queued items.</param>
 /// <param name="exceptionHandler">The method to handle exceptions that occur when processing items.</param>
 public DoubleBufferedQueueManager(Action itemHandler, Action <Exception> exceptionHandler)
     : this()
 {
     m_itemHandlingOperation = new ShortSynchronizedOperation(CallItemHandler, exceptionHandler);
     m_itemHandler           = itemHandler;
 }
Exemplo n.º 20
0
 /// <summary>
 /// Receives real-time updates from PI
 /// </summary>
 public PIRTInputAdapter()
 {
     m_tagKeyMap = new ConcurrentDictionary<int, MeasurementKey>();
     m_restartConnection = new ShortSynchronizedOperation(Start);
     m_readEvents = new ShortSynchronizedOperation(ReadEvents);
     //m_dataUpdateObserver = new DataUpdateObserver(OnProcessException);
     //m_dataUpdateObserver.DataUpdated += m_dataUpdateObserver_DataUpdated;
     m_eventTimer = new System.Timers.Timer(1000.0D);
     m_eventTimer.Elapsed += m_eventTimer_Elapsed;
     m_eventTimer.AutoReset = true;
     m_eventTimer.Enabled = false;
 }
Exemplo n.º 21
0
        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;
        }
Exemplo n.º 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TcpClient"/> class.
 /// </summary>
 /// <param name="connectString">Connect string of the <see cref="TcpClient"/>. See <see cref="DefaultConnectionString"/> for format.</param>
 public TcpClient(string connectString)
     : base(TransportProtocol.Tcp, connectString)
 {
     m_payloadAware = DefaultPayloadAware;
     m_payloadMarker = Payload.DefaultMarker;
     m_integratedSecurity = DefaultIntegratedSecurity;
     m_ignoreInvalidCredentials = DefaultIgnoreInvalidCredentials;
     m_allowDualStackSocket = DefaultAllowDualStackSocket;
     m_maxSendQueueSize = DefaultMaxSendQueueSize;
     m_dumpPayloadsOperation = new ShortSynchronizedOperation(DumpPayloads, OnSendDataException);
 }
        private long m_ignoredErrors;           // Total ignored 400 and 500 HTTP status code errors

        #endregion

        #region [ Constructors ]

        /// <summary>
        /// Creates a new <see cref="InfluxDBOutputAdapter"/>;
        /// </summary>
        public InfluxDBOutputAdapter()
        {
            m_requestRestart = new ShortSynchronizedOperation(() =>
            {
                if (Enabled)
                    Start();
            });
        }