Exemplo n.º 1
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.");
        }
Exemplo n.º 2
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.");
            }
        }
Exemplo n.º 3
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!");
            }
        }