Beispiel #1
0
        /// <summary>
        /// Registers ourselves with IoTHub so we can send messages to it
        /// </summary>
        private void SelfRegisterWithIoTHub(string ownerConnectionString)
        {
            string[] parsedConnectionString = IoTHubRegistration.ParseConnectionString(ownerConnectionString, false);
            string   deviceConnectionString = string.Empty;

            if ((parsedConnectionString != null) && (parsedConnectionString.Length == 3))
            {
                string IoTHubName  = parsedConnectionString[0];
                string name        = parsedConnectionString[1];
                string accessToken = parsedConnectionString[2];

                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new UriBuilder {
                        Scheme = "https", Host = IoTHubName
                    }.Uri;

                    string sharedAccessSignature = IoTHubRegistration.GenerateSharedAccessToken(name, Convert.FromBase64String(accessToken), IoTHubName, 60000);
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", sharedAccessSignature);
                    deviceConnectionString = IoTHubRegistration.CreateDeviceInIoTHubDeviceRegistry(httpClient, m_configuration.ApplicationName.Replace(" ", "")).Result;

                    // prepend the rest of the connection string
                    deviceConnectionString = "HostName=" + IoTHubName + ";DeviceId=" + m_configuration.ApplicationName.Replace(" ", "") + ";SharedAccessKey=" + deviceConnectionString;
                    SecureIoTHubToken.Write(m_configuration.ApplicationName, deviceConnectionString);
                }
            }
            else
            {
                Trace("Opc.Ua.Publisher.Module: Could not parse IoT Hub owner connection string: " + ownerConnectionString);
            }
        }
        /// <summary>
        /// Data node in the server which registers ourselves with IoT Hub when this node is written to
        /// </summary>
        public ServiceResult ConnectionStringWrite(ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp)
        {
            var connectionString = value as string;

            if (string.IsNullOrEmpty(connectionString))
            {
                Module.Trace("ConnectionStringWrite: Invalid Argument!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments as strings!"));
            }

            statusCode = StatusCodes.Bad;
            timestamp  = DateTime.Now;

            // read current connection string and compare to the one passed in
            string currentConnectionString = SecureIoTHubToken.Read(Module.m_configuration.ApplicationName);

            if (string.Equals(connectionString, currentConnectionString, StringComparison.OrdinalIgnoreCase))
            {
                Module.Trace("ConnectionStringWrite: Connection string up to date!");
                return(ServiceResult.Create(StatusCodes.Bad, "Connection string already up-to-date!"));
            }

            // try to parse connection string
            string[] parsedConnectionString = IoTHubRegistration.ParseConnectionString(connectionString, true);
            if ((parsedConnectionString == null) || (parsedConnectionString.Length != 3))
            {
                Module.Trace("ConnectionStringWrite: Connection string parsing error: " + connectionString);
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Could not parse connection string!"));
            }

            // write connection string
            try
            {
                SecureIoTHubToken.Write(Module.m_configuration.ApplicationName, connectionString);
            }
            catch (Exception ex)
            {
                statusCode = StatusCodes.Bad;
                Module.Trace("ConnectionStringWrite: Exception: " + ex.ToString());
                return(ServiceResult.Create(StatusCodes.Bad, "Publisher registration failed: " + ex.Message));
            }

            try
            {
                // try to configure our publisher component
                Module.TryConfigurePublisherAsync().Wait();
            }
            catch (Exception ex)
            {
                statusCode = StatusCodes.Bad;
                Module.Trace("ConnectionStringWrite: Exception: " + ex.ToString());
                return(ServiceResult.Create(StatusCodes.Bad, "Publisher configuration failed: " + ex.Message));
            }

            statusCode = StatusCodes.Good;
            Module.Trace("ConnectionStringWrite: Success!");

            return(statusCode);
        }
        public void ConnectionStringWrite(string iotHubOwnerConnectionString)
        {
            DeviceClient newClient = DeviceClient.CreateFromConnectionString(iotHubOwnerConnectionString, IotHubProtocol);

            newClient.RetryPolicy = RetryPolicyType.Exponential_Backoff_With_Jitter;
            newClient.OpenAsync().Wait();
            SecureIoTHubToken.Write(OpcConfiguration.ApplicationName, iotHubOwnerConnectionString, IotDeviceCertStoreType, IotDeviceCertStorePath);
            _iotHubClient = newClient;
        }
Beispiel #4
0
        /// <summary>
        /// Data node in the server which registers ourselves with IoT Hub when this node is written to
        /// </summary>
        public ServiceResult ConnectionStringWrite(ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp)
        {
            var connectionString = value as string;

            if (string.IsNullOrEmpty(connectionString))
            {
                Program.Trace("ConnectionStringWrite: Invalid Argument!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments as strings!"));
            }

            statusCode = StatusCodes.Bad;
            timestamp  = DateTime.Now;

            // read current connection string and compare to the one passed in
            string currentConnectionString = SecureIoTHubToken.Read(Program.m_configuration.ApplicationName);

            if (string.Equals(connectionString, currentConnectionString, StringComparison.OrdinalIgnoreCase))
            {
                Program.Trace("ConnectionStringWrite: Connection string up to date!");
                return(ServiceResult.Create(StatusCodes.Bad, "Connection string already up-to-date!"));
            }

            Program.Trace("Attemping to configure publisher with connection string: " + connectionString);

            // configure publisher and write connection string
            try
            {
                DeviceClient newClient = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
                newClient.RetryPolicy = RetryPolicyType.Exponential_Backoff_With_Jitter;
                newClient.OpenAsync().Wait();
                SecureIoTHubToken.Write(Program.m_configuration.ApplicationName, connectionString);
                Program.m_deviceClient = newClient;
            }
            catch (Exception ex)
            {
                statusCode = StatusCodes.Bad;
                Program.Trace("ConnectionStringWrite: Exception: " + ex.ToString());
                return(ServiceResult.Create(StatusCodes.Bad, "Publisher registration failed: " + ex.Message));
            }

            statusCode = StatusCodes.Good;
            Program.Trace("ConnectionStringWrite: Success!");

            return(statusCode);
        }
        public bool Init(string iotHubOwnerConnectionString, uint maxSizeOfIoTHubMessageBytes, int defaultSendIntervalSeconds)
        {
            _maxSizeOfIoTHubMessageBytes = maxSizeOfIoTHubMessageBytes;
            _defaultSendIntervalSeconds  = defaultSendIntervalSeconds;

            try
            {
                // check if we also received an owner connection string
                if (string.IsNullOrEmpty(iotHubOwnerConnectionString))
                {
                    Trace("IoT Hub owner connection string not passed as argument.");

                    // check if we have an environment variable to register ourselves with IoT Hub
                    if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("_HUB_CS")))
                    {
                        iotHubOwnerConnectionString = Environment.GetEnvironmentVariable("_HUB_CS");
                        Trace("IoT Hub owner connection string read from environment.");
                    }
                }

                // register ourselves with IoT Hub
                string deviceConnectionString;
                Trace($"IoTHub device cert store type is: {IotDeviceCertStoreType}");
                Trace($"IoTHub device cert path is: {IotDeviceCertStorePath}");
                if (string.IsNullOrEmpty(iotHubOwnerConnectionString))
                {
                    Trace("IoT Hub owner connection string not specified. Assume device connection string already in cert store.");
                }
                else
                {
                    Trace($"Attempting to register ourselves with IoT Hub using owner connection string: {iotHubOwnerConnectionString}");
                    RegistryManager manager = RegistryManager.CreateFromConnectionString(iotHubOwnerConnectionString);

                    // remove any existing device
                    Device existingDevice = manager.GetDeviceAsync(ApplicationName).Result;
                    if (existingDevice != null)
                    {
                        Trace($"Device '{ApplicationName}' found in IoTHub registry. Remove it.");
                        manager.RemoveDeviceAsync(ApplicationName).Wait();
                    }

                    Trace($"Adding device '{ApplicationName}' to IoTHub registry.");
                    Device newDevice = manager.AddDeviceAsync(new Device(ApplicationName)).Result;
                    if (newDevice != null)
                    {
                        string hostname = iotHubOwnerConnectionString.Substring(0, iotHubOwnerConnectionString.IndexOf(";"));
                        deviceConnectionString = hostname + ";DeviceId=" + ApplicationName + ";SharedAccessKey=" + newDevice.Authentication.SymmetricKey.PrimaryKey;
                        Trace($"Device connection string is: {deviceConnectionString}");
                        Trace($"Adding it to device cert store.");
                        SecureIoTHubToken.Write(ApplicationName, deviceConnectionString, IotDeviceCertStoreType, IotDeviceCertStoreType);
                    }
                    else
                    {
                        Trace($"Could not register ourselves with IoT Hub using owner connection string: {iotHubOwnerConnectionString}");
                        Trace("exiting...");
                        return(false);
                    }
                }

                // try to read connection string from secure store and open IoTHub client
                Trace($"Attempting to read device connection string from cert store using subject name: {ApplicationName}");
                deviceConnectionString = SecureIoTHubToken.Read(ApplicationName, IotDeviceCertStoreType, IotDeviceCertStorePath);
                if (!string.IsNullOrEmpty(deviceConnectionString))
                {
                    Trace($"Create Publisher IoTHub client with device connection string: '{deviceConnectionString}' using '{IotHubProtocol}' for communication.");
                    _iotHubClient             = DeviceClient.CreateFromConnectionString(deviceConnectionString, IotHubProtocol);
                    _iotHubClient.RetryPolicy = RetryPolicyType.Exponential_Backoff_With_Jitter;
                    _iotHubClient.OpenAsync().Wait();
                }
                else
                {
                    Trace("Device connection string not found in secure store. Could not connect to IoTHub.");
                    Trace("exiting...");
                    return(false);
                }

                // start up task to send telemetry to IoTHub.
                _dequeueAndSendTask = null;
                _tokenSource        = new CancellationTokenSource();

                Trace("Creating task to send OPC UA messages in batches to IoT Hub...");
                _dequeueAndSendTask = Task.Run(() => DeQueueMessagesAsync(_tokenSource.Token), _tokenSource.Token);
            }
            catch (Exception e)
            {
                Trace(e, "Error during IoTHub messaging initialization.");
                return(false);
            }
            return(true);
        }
Beispiel #6
0
        public static void Main(string[] args)
        {
            // check for OSX, which we don't support
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                throw new NotSupportedException("OSX is not supported by the Gateway App on .Net Core");
            }

            // patch IoT Hub module DLL name
            string gatewayConfigFile = "gatewayconfig.json";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Console.WriteLine("Target system is Linux.");
                File.WriteAllText(gatewayConfigFile, File.ReadAllText(gatewayConfigFile).Replace("iothub.dll", "libiothub.so"));
            }
            else
            {
                Console.WriteLine("Target system is Windows.");
                File.WriteAllText(gatewayConfigFile, File.ReadAllText(gatewayConfigFile).Replace("libiothub.so", "iothub.dll"));
            }

            // print target system info
            if (IsX64Process())
            {
                Console.WriteLine("Target system is 64-bit.");
            }
            else
            {
                Console.WriteLine("Target system is 32-bit.");
                throw new Exception("32-bit systems are currently not supported due to https://github.com/Azure/azure-iot-gateway-sdk/releases#known-issues");
            }

            // make sure our gateway runtime DLLs are in the current directory
            string runtimesFolder = GetPathToRuntimesFolder(Directory.GetCurrentDirectory());

            if (string.IsNullOrEmpty(runtimesFolder))
            {
                throw new Exception("Runtimes folder not found. Please make sure you have published the gateway app!");
            }

            // we always copy them across, overwriting existing ones, to make sure we have the right ones
            string        pathToNativeGatewayModules = runtimesFolder + Path.DirectorySeparatorChar + GetRuntimeID() + Path.DirectorySeparatorChar + "native";
            List <string> filePaths = new List <string>(Directory.EnumerateFiles(pathToNativeGatewayModules));

            foreach (string sourcefilePath in filePaths)
            {
                string destinationFilePath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Path.GetFileName(sourcefilePath);
                File.Copy(sourcefilePath, destinationFilePath, true);
            }

            // check if we got command line arguments to patch our gateway config file and register ourselves with IoT Hub
            if ((args.Length > 0) && !string.IsNullOrEmpty(args[0]))
            {
                string applicationName = args[0];
                File.WriteAllText(gatewayConfigFile, File.ReadAllText(gatewayConfigFile).Replace("<ReplaceWithYourApplicationName>", applicationName));
                Console.WriteLine("Gateway config file patched with application name: " + applicationName);

                // check if we also received an owner connection string to register ourselves with IoT Hub
                if ((args.Length > 1) && !string.IsNullOrEmpty(args[1]))
                {
                    string ownerConnectionString = args[1];

                    Console.WriteLine("Attemping to register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    string deviceConnectionString = IoTHubRegistration.RegisterDeviceWithIoTHub(applicationName, ownerConnectionString);
                    if (!string.IsNullOrEmpty(deviceConnectionString))
                    {
                        SecureIoTHubToken.Write(applicationName, deviceConnectionString);
                    }
                    else
                    {
                        Console.WriteLine("Could not register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    }
                }
                else
                {
                    Console.WriteLine("IoT Hub owner connection string not passed as argument, registration with IoT Hub abandoned.");
                }

                // try to read connection string from secure store and patch gateway config file
                Console.WriteLine("Attemping to read connection string from secure store with certificate name: " + applicationName);
                string connectionString = SecureIoTHubToken.Read(applicationName);
                if (!string.IsNullOrEmpty(connectionString))
                {
                    Console.WriteLine("Attemping to configure publisher with connection string: " + connectionString);
                    string[] parsedConnectionString = IoTHubRegistration.ParseConnectionString(connectionString, true);
                    if ((parsedConnectionString != null) && (parsedConnectionString.Length == 3))
                    {
                        string _IoTHubName = parsedConnectionString[0];
                        if (_IoTHubName.Contains("."))
                        {
                            _IoTHubName = _IoTHubName.Substring(0, _IoTHubName.IndexOf('.'));
                        }
                        File.WriteAllText(gatewayConfigFile, File.ReadAllText(gatewayConfigFile).Replace("<ReplaceWithYourIoTHubName>", _IoTHubName));
                        Console.WriteLine("Gateway config file patched with IoT Hub name: " + _IoTHubName);
                    }
                    else
                    {
                        throw new Exception("Could not parse persisted device connection string!");
                    }
                }
                else
                {
                    Console.WriteLine("Device connection string not found in secure store.");
                }
            }
            else
            {
                Console.WriteLine("Application name not passed as argument, patching gateway config file abandoned");
            }

            IntPtr gateway = GatewayInterop.CreateFromJson(gatewayConfigFile);

            if (gateway != IntPtr.Zero)
            {
                Console.WriteLine(".NET Core Gateway is running. Press enter to quit.");
                Console.ReadLine();
                GatewayInterop.Destroy(gateway);
            }
            else
            {
                Console.WriteLine(".NET Core Gateway failed to initialize.");
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                if ((args.Length == 0) || string.IsNullOrEmpty(args[0]) || args[0].Equals("localhost", StringComparison.OrdinalIgnoreCase))
                {
                    m_applicationName = Utils.GetHostName();
                }
                else
                {
                    m_applicationName = args[0];
                }

                Trace("Publisher is starting up...");
                ModuleConfiguration moduleConfiguration = new ModuleConfiguration(m_applicationName);
                m_configuration = moduleConfiguration.Configuration;
                m_configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);

                // start our server interface
                try
                {
                    Trace("Starting server on endpoint " + m_configuration.ServerConfiguration.BaseAddresses[0].ToString() + "...");
                    m_server.Start(m_configuration);
                    Trace("Server started.");
                }
                catch (Exception ex)
                {
                    Trace("Starting server failed with: " + ex.Message);
                }

                // check if we also received an owner connection string
                string ownerConnectionString = string.Empty;
                if ((args.Length > 1) && !string.IsNullOrEmpty(args[1]))
                {
                    ownerConnectionString = args[1];
                }
                else
                {
                    Trace("IoT Hub owner connection string not passed as argument.");

                    // check if we have an environment variable to register ourselves with IoT Hub
                    if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("_HUB_CS")))
                    {
                        ownerConnectionString = Environment.GetEnvironmentVariable("_HUB_CS");
                    }
                }

                // register ourselves with IoT Hub
                if (ownerConnectionString != string.Empty)
                {
                    Trace("Attemping to register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    RegistryManager manager = RegistryManager.CreateFromConnectionString(ownerConnectionString);

                    // remove any existing device
                    Device existingDevice = manager.GetDeviceAsync(m_applicationName).Result;
                    if (existingDevice != null)
                    {
                        manager.RemoveDeviceAsync(m_applicationName).Wait();
                    }

                    Device newDevice = manager.AddDeviceAsync(new Device(m_applicationName)).Result;
                    if (newDevice != null)
                    {
                        string hostname = ownerConnectionString.Substring(0, ownerConnectionString.IndexOf(";"));
                        string deviceConnectionString = hostname + ";DeviceId=" + m_applicationName + ";SharedAccessKey=" + newDevice.Authentication.SymmetricKey.PrimaryKey;
                        SecureIoTHubToken.Write(m_applicationName, deviceConnectionString);
                    }
                    else
                    {
                        Trace("Could not register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    }
                }
                else
                {
                    Trace("IoT Hub owner connection string not found, registration with IoT Hub abandoned.");
                }

                // try to read connection string from secure store and open IoTHub client
                Trace("Attemping to read connection string from secure store with certificate name: " + m_applicationName);
                string connectionString = SecureIoTHubToken.Read(m_applicationName);
                if (!string.IsNullOrEmpty(connectionString))
                {
                    Trace("Attemping to configure publisher with connection string: " + connectionString);
                    m_deviceClient             = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
                    m_deviceClient.RetryPolicy = RetryPolicyType.Exponential_Backoff_With_Jitter;
                    m_deviceClient.OpenAsync().Wait();
                }
                else
                {
                    Trace("Device connection string not found in secure store.");
                }

                // get a list of persisted endpoint URLs and create a session for each.
                try
                {
                    // check if we have an env variable specifying the published nodes path, otherwise use current directory
                    string publishedNodesFilePath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "publishednodes.json";
                    if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("_GW_PNFP")))
                    {
                        publishedNodesFilePath = Environment.GetEnvironmentVariable("_GW_PNFP");
                    }

                    Trace("Attemping to load nodes file from: " + publishedNodesFilePath);
                    m_nodesLookups = JsonConvert.DeserializeObject <PublishedNodesCollection>(File.ReadAllText(publishedNodesFilePath));
                    Trace("Loaded " + m_nodesLookups.Count.ToString() + " nodes.");
                }
                catch (Exception ex)
                {
                    Trace("Nodes file loading failed with: " + ex.Message);
                }

                foreach (NodeLookup nodeLookup in m_nodesLookups)
                {
                    if (!m_endpointUrls.Contains(nodeLookup.EndPointURL))
                    {
                        m_endpointUrls.Add(nodeLookup.EndPointURL);
                    }
                }

                // connect to the other servers
                Trace("Attemping to connect to servers...");
                try
                {
                    List <Task> connectionAttempts = new List <Task>();
                    foreach (Uri endpointUrl in m_endpointUrls)
                    {
                        Trace("Connecting to server: " + endpointUrl);
                        connectionAttempts.Add(EndpointConnect(endpointUrl));
                    }

                    // Wait for all sessions to be connected
                    Task.WaitAll(connectionAttempts.ToArray());
                }
                catch (Exception ex)
                {
                    Trace("Exception: " + ex.ToString() + "\r\n" + ex.InnerException != null ? ex.InnerException.ToString() : null);
                }

                // subscribe to preconfigured nodes
                Trace("Attemping to subscribe to published nodes...");
                if (m_nodesLookups != null)
                {
                    foreach (NodeLookup nodeLookup in m_nodesLookups)
                    {
                        try
                        {
                            CreateMonitoredItem(nodeLookup);
                        }
                        catch (Exception ex)
                        {
                            Trace("Unexpected error publishing node: " + ex.Message + "\r\nIgnoring node: " + nodeLookup.EndPointURL.AbsoluteUri + ", " + nodeLookup.NodeID.ToString());
                        }
                    }
                }


                Task dequeueAndSendTask = null;
                var  tokenSource        = new CancellationTokenSource();
                var  token = tokenSource.Token;

                Trace("Creating task to send OPC UA messages in batches to IoT Hub...");
                try
                {
                    dequeueAndSendTask = Task.Run(() => DeQueueMessagesAsync(token), token);
                }
                catch (Exception ex)
                {
                    Trace("Exception: " + ex.ToString());
                }

                Trace("Publisher is running. Press enter to quit.");
                Console.ReadLine();

                foreach (Session session in m_sessions)
                {
                    session.Close();
                }

                //Send cancellation token and wait for last IoT Hub message to be sent.
                try
                {
                    tokenSource.Cancel();
                    dequeueAndSendTask.Wait();
                }
                catch (Exception ex)
                {
                    Trace("Exception: " + ex.ToString());
                }

                if (m_deviceClient != null)
                {
                    m_deviceClient.CloseAsync().Wait();
                }
            }
            catch (Exception e)
            {
                Trace(e, "Unhandled exception in Publisher, exiting!");
            }
        }
Beispiel #8
0
        /// <summary>
        /// Create module, throws if configuration is bad
        /// </summary>
        public void Create(Broker broker, byte[] configuration)
        {
            Trace("Opc.Ua.Publisher.Module: Creating...");

            m_broker = broker;

            string configString = Encoding.UTF8.GetString(configuration);

            // Deserialize from configuration string
            ModuleConfiguration moduleConfiguration = null;

            try
            {
                moduleConfiguration = JsonConvert.DeserializeObject <ModuleConfiguration>(configString);
            }
            catch (Exception ex)
            {
                Trace("Opc.Ua.Publisher.Module: Module config string " + configString + " could not be deserialized: " + ex.Message);
                throw;
            }

            m_configuration = moduleConfiguration.Configuration;
            m_configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);

            // update log configuration, if available
            if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("_GW_LOGP")))
            {
                m_configuration.TraceConfiguration.OutputFilePath = Environment.GetEnvironmentVariable("_GW_LOGP");
                m_configuration.TraceConfiguration.ApplySettings();
            }

            // get a list of persisted endpoint URLs and create a session for each.
            try
            {
                // check if we have an env variable specifying the published nodes path, otherwise use current directory
                string publishedNodesFilePath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "publishednodes.json";
                if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("_GW_PNFP")))
                {
                    publishedNodesFilePath = Environment.GetEnvironmentVariable("_GW_PNFP");
                }

                Trace("Opc.Ua.Publisher.Module: Attemping to load nodes file from: " + publishedNodesFilePath);
                m_nodesLookups = JsonConvert.DeserializeObject <PublishedNodesCollection>(File.ReadAllText(publishedNodesFilePath));
                Trace("Opc.Ua.Publisher.Module: Loaded " + m_nodesLookups.Count.ToString() + " nodes.");
            }
            catch (Exception ex)
            {
                Trace("Opc.Ua.Publisher.Module: Nodes file loading failed with: " + ex.Message);
            }

            foreach (NodeLookup nodeLookup in m_nodesLookups)
            {
                if (!m_endpointUrls.Contains(nodeLookup.EndPointURL))
                {
                    m_endpointUrls.Add(nodeLookup.EndPointURL);
                }
            }

            // start the server
            try
            {
                Trace("Opc.Ua.Publisher.Module: Starting server on endpoint " + m_configuration.ServerConfiguration.BaseAddresses[0].ToString() + "...");
                m_server.Start(m_configuration);
                Trace("Opc.Ua.Publisher.Module: Server started.");
            }
            catch (Exception ex)
            {
                Trace("Opc.Ua.Publisher.Module: Starting server failed with: " + ex.Message);
            }

            // check if we have an environment variable to register ourselves with IoT Hub
            if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("_HUB_CS")))
            {
                string ownerConnectionString = Environment.GetEnvironmentVariable("_HUB_CS");

                if ((m_configuration != null) && (!string.IsNullOrEmpty(m_configuration.ApplicationName)))
                {
                    Trace("Attemping to register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    string deviceConnectionString = IoTHubRegistration.RegisterDeviceWithIoTHub(m_configuration.ApplicationName, ownerConnectionString);
                    if (!string.IsNullOrEmpty(deviceConnectionString))
                    {
                        SecureIoTHubToken.Write(m_configuration.ApplicationName, deviceConnectionString);
                    }
                    else
                    {
                        Trace("Could not register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    }
                }
            }

            // try to configure our publisher component
            TryConfigurePublisherAsync().Wait();

            // connect to servers
            Trace("Opc.Ua.Publisher.Module: Attemping to connect to servers...");
            try
            {
                List <Task> connectionAttempts = new List <Task>();
                foreach (Uri endpointUrl in m_endpointUrls)
                {
                    Trace("Opc.Ua.Publisher.Module: Connecting to server: " + endpointUrl);
                    connectionAttempts.Add(EndpointConnect(endpointUrl));
                }

                // Wait for all sessions to be connected
                Task.WaitAll(connectionAttempts.ToArray());
            }
            catch (Exception ex)
            {
                Trace("Opc.Ua.Publisher.Module: Exception: " + ex.ToString() + "\r\n" + ex.InnerException != null ? ex.InnerException.ToString() : null);
            }

            Trace("Opc.Ua.Publisher.Module: Created.");
        }
Beispiel #9
0
        public static void Main(string[] args)
        {
            // check for OSX, which we don't support
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                throw new NotSupportedException("OSX is not supported by the Gateway App on .Net Core");
            }

            // patch IoT Hub module DLL name
            string gatewayConfigFile = "gatewayconfig.json";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Console.WriteLine("Target system is Linux.");
                File.WriteAllText(gatewayConfigFile, File.ReadAllText(gatewayConfigFile).Replace("iothub.dll", "libiothub.so"));
            }
            else
            {
                Console.WriteLine("Target system is Windows.");
                File.WriteAllText(gatewayConfigFile, File.ReadAllText(gatewayConfigFile).Replace("libiothub.so", "iothub.dll"));
            }
            Console.WriteLine(RuntimeInformation.OSDescription);

            // print target system info
            if (IsX64Process())
            {
                Console.WriteLine("Target system is 64-bit.");
            }
            else
            {
                Console.WriteLine("Target system is 32-bit.");
                throw new Exception("32-bit systems are currently not supported.");
            }

            // check if we got command line arguments to patch our gateway config file and register ourselves with IoT Hub
            if ((args.Length > 0) && !string.IsNullOrEmpty(args[0]))
            {
                string applicationName = args[0];
                File.WriteAllText(gatewayConfigFile, File.ReadAllText(gatewayConfigFile).Replace("<ReplaceWithYourApplicationName>", applicationName));
                Console.WriteLine("Gateway config file patched with application name: " + applicationName);

                // check if we also received an owner connection string to register ourselves with IoT Hub
                if ((args.Length > 1) && !string.IsNullOrEmpty(args[1]))
                {
                    string ownerConnectionString = args[1];

                    Console.WriteLine("Attemping to register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    string deviceConnectionString = IoTHubRegistration.RegisterDeviceWithIoTHub(applicationName, ownerConnectionString);
                    if (!string.IsNullOrEmpty(deviceConnectionString))
                    {
                        SecureIoTHubToken.Write(applicationName, deviceConnectionString);
                    }
                    else
                    {
                        Console.WriteLine("Could not register ourselves with IoT Hub using owner connection string: " + ownerConnectionString);
                    }
                }
                else
                {
                    Console.WriteLine("IoT Hub owner connection string not passed as argument, registration with IoT Hub abandoned.");
                }

                // try to read connection string from secure store and patch gateway config file
                Console.WriteLine("Attemping to read connection string from secure store with certificate name: " + applicationName);
                string connectionString = SecureIoTHubToken.Read(applicationName);
                if (!string.IsNullOrEmpty(connectionString))
                {
                    Console.WriteLine("Attemping to configure publisher with connection string: " + connectionString);
                    string[] parsedConnectionString = IoTHubRegistration.ParseConnectionString(connectionString, true);
                    if ((parsedConnectionString != null) && (parsedConnectionString.Length == 3))
                    {
                        string _IoTHubName = parsedConnectionString[0];
                        if (_IoTHubName.Contains("."))
                        {
                            _IoTHubName = _IoTHubName.Substring(0, _IoTHubName.IndexOf('.'));
                        }
                        File.WriteAllText(gatewayConfigFile, File.ReadAllText(gatewayConfigFile).Replace("<ReplaceWithYourIoTHubName>", _IoTHubName));
                        Console.WriteLine("Gateway config file patched with IoT Hub name: " + _IoTHubName);
                    }
                    else
                    {
                        throw new Exception("Could not parse persisted device connection string!");
                    }
                }
                else
                {
                    Console.WriteLine("Device connection string not found in secure store.");
                }
            }
            else
            {
                Console.WriteLine("Application name not passed as argument, patching gateway config file abandoned");
            }

            IntPtr gateway = GatewayInterop.CreateFromJson(gatewayConfigFile);

            if (gateway != IntPtr.Zero)
            {
                Console.WriteLine(".NET Core Gateway is running. Press enter to quit.");
                Console.ReadLine();
                GatewayInterop.Destroy(gateway);
            }
            else
            {
                Console.WriteLine(".NET Core Gateway failed to initialize. Please make sure you have published the GatewayApp.NetCore app to make sure the depend DLLs are available!");
            }
        }