/// <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); }
/// <summary> /// Try to configure our Publisher settings /// </summary> public static async Task TryConfigurePublisherAsync() { // read connection string from secure store and configure publisher, if possible if ((m_configuration != null) && (!string.IsNullOrEmpty(m_configuration.ApplicationName))) { Trace("Opc.Ua.Publisher.Module: Attemping to read connection string from secure store with certificate name: " + m_configuration.ApplicationName); string connectionString = SecureIoTHubToken.Read(m_configuration.ApplicationName); if (!string.IsNullOrEmpty(connectionString)) { Trace("Opc.Ua.Publisher.Module: Attemping to configure publisher with connection string: " + connectionString); string[] parsedConnectionString = IoTHubRegistration.ParseConnectionString(connectionString, true); if ((parsedConnectionString != null) && (parsedConnectionString.Length == 3)) { // note: IoTHub name can't be changed during runtime in the GW IoTHub module string _IoTHubName = parsedConnectionString[0]; m_deviceName = parsedConnectionString[1]; m_accessKey = parsedConnectionString[2]; Trace("Opc.Ua.Publisher.Module: Publisher configured for device: " + m_deviceName); // try to connect to IoT Hub using (HttpClient httpClient = new HttpClient()) { httpClient.BaseAddress = new UriBuilder { Scheme = "https", Host = _IoTHubName }.Uri; string sharedAccessToken = IoTHubRegistration.GenerateSharedAccessToken(string.Empty, Convert.FromBase64String(m_accessKey), _IoTHubName, 60000); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", sharedAccessToken); // send an empty d2c message HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/devices/" + m_deviceName + "/messages/events" + IoTHubRegistration._IoTHubAPIVersion); HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false); if (response.StatusCode != HttpStatusCode.NoContent) { throw new Exception("Opc.Ua.Publisher.Module: Could not connect to IoT Hub. Response: " + response.ToString()); } } } else { throw new Exception("Opc.Ua.Publisher.Module: Publisher configuration failed!"); } } else { Trace("Opc.Ua.Publisher.Module: Connection string not found in secure store."); } } }
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) { // 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!"); } }