Ejemplo n.º 1
0
        /// <summary>
        /// Generates the connection string.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <param name="devicekey">The devicekey.</param>
        /// <returns></returns>
        protected string GenerateDeviceConnectionString(string deviceId, string devicekey)
        { 
            var authenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, devicekey);
            var builder = Microsoft.Azure.Devices.Client.IotHubConnectionStringBuilder.Create(HostName, authenticationMethod);

            return builder.ToString();
        }
        /// <summary>
        /// Builds the IoT Hub connection string
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private string GetConnectionString()
        {
            string key = _device.PrimaryAuthKey;
            string deviceID = _device.DeviceID;
            string hostName = _device.HostName;

            var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(deviceID, key);
            return Client.IotHubConnectionStringBuilder.Create(hostName, authMethod).ToString();
        }
Ejemplo n.º 3
0
        public void HandleSnapshot(BusInfo bus)
        {
            var device = GetDevice(bus);

            Debug.Assert(device.Id == bus.VehicleId.ToString());

            var authMethod = new MADC.DeviceAuthenticationWithRegistrySymmetricKey(device.Id, device.Authentication.SymmetricKey.PrimaryKey);

            using (var client = MADC.DeviceClient.Create(_hubHostName, authMethod))
            {
                var msg = new MADC.Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bus)));

                client.OpenAsync().Wait();

                client.SendEventAsync(msg).Wait();
            }
        }
Ejemplo n.º 4
0
        public static async Task<string> SendDeviceToCloudInteractiveMessagesAsync(string deviceId)
        {

            if (deviceClient == null)
            {
                //deviceClient = DeviceClient.CreateFromConnectionString(connectionString, deviceId);
                var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey);

                //amqp not supported in universal app -> https://github.com/Azure/azure-iot-sdks/blob/master/doc/faq.md
                deviceClient = DeviceClient.Create(iotHubUri, authMethod, TransportType.Http1);
            }

            var interactiveMessageString = "Alert message!";
            var interactiveMessage = new Message(Encoding.ASCII.GetBytes(interactiveMessageString));
            interactiveMessage.Properties["messageType"] = "interactive";
            interactiveMessage.MessageId = Guid.NewGuid().ToString();

            await deviceClient.SendEventAsync(interactiveMessage);
            return interactiveMessageString;
        }
Ejemplo n.º 5
0
        //static string connectionString =
        //        "HostName=<yourhost>.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=<yourkey>";

        /// <summary>
        /// send a message to the azure iot hub
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="currentWindSpeed"></param>
        public static async Task<string> SendDeviceToCloudMessagesAsync(string deviceId, double currentWindSpeed)
        {
            if (deviceClient == null)
            {
                //deviceClient = DeviceClient.CreateFromConnectionString(connectionString, deviceId);
                var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey);

                //amqp not supported in universal app -> https://github.com/Azure/azure-iot-sdks/blob/master/doc/faq.md
                deviceClient = DeviceClient.Create(iotHubUri, authMethod, TransportType.Http1);
            }

            var telemetryDataPoint = new
            {
                deviceId = deviceId,
                windSpeed = currentWindSpeed
            };

            var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
            var message = new Message(Encoding.ASCII.GetBytes(messageString));

            await deviceClient.SendEventAsync(message);

            return messageString;
        }
        public void DeviceClient_IotHubConnectionStringBuilder_Test()
        {
            string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=";
            var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);
            Assert.IsNotNull(iotHubConnectionStringBuilder.HostName);
            Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId);
            Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod);
            Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKey);
            Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKeyName);
            Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessSignature);
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey);

            connectionString = "HostName=acme.azure-devices.net;CredentialType=SharedAccessSignature;DeviceId=device1;SharedAccessSignature=SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey";
            iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);
            Assert.IsNotNull(iotHubConnectionStringBuilder.HostName);
            Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId);
            Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod);
            Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKey);
            Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessSignature);
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken);

            connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=";
            iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);
            Assert.IsNotNull(iotHubConnectionStringBuilder.HostName);
            Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId);
            Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod);
            Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKey);
            Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKeyName);
            Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessSignature);
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey);

            connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;DeviceId=device1;SharedAccessSignature=SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey";
            iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);
            Assert.IsNotNull(iotHubConnectionStringBuilder.HostName);
            Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId);
            Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod);
            Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKey);
            Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKeyName);
            Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessSignature);
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken);

            try
            {
                iotHubConnectionStringBuilder.HostName = "adshgfvyregferuehfiuehr";
                Assert.Fail("Expected FormatException");
            }
            catch (FormatException)
            {               
            }

            iotHubConnectionStringBuilder.HostName = "acme.azure-devices.net";
            iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey("Device1", "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey);
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null);
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId=="Device1");

            iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithToken("Device2", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey");
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken);
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey");
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null);
            Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device2");

            iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithSharedAccessPolicyKey("Device3", "AllAccess", "KQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey);
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null);
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "KQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device3");

            iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithToken("Device4", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey");
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken);
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey");
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null);
            Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device4");

            IAuthenticationMethod authMethod = AuthenticationMethodFactory.CreateAuthenticationWithToken("Device5", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey");
            iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme1.azure-devices.net", authMethod);
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken);
            Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme1.azure-devices.net");
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey");
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null);
            Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device5");

            authMethod = new DeviceAuthenticationWithSharedAccessPolicyKey("Device3", "AllAccess", "KQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme2.azure-devices.net", authMethod);
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey);
            Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme2.azure-devices.net");
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null);
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "KQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device3");

            authMethod = new DeviceAuthenticationWithToken("Device2", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey");
            iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme3.azure-devices.net", authMethod);
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken);
            Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme3.azure-devices.net");
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey");
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null);
            Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device2");

            authMethod = new DeviceAuthenticationWithRegistrySymmetricKey("Device1", "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme4.azure-devices.net", authMethod);
            Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey);
            Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme4.azure-devices.net");
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null);
            Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device1");
        }
        public void X509Certificate_MutipleClientAuthMechanism()
        {
            string hostName = "acme.azure-devices.net";
            var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings();
            var transportSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings);
            var authMethod1 = new DeviceAuthenticationWithRegistrySymmetricKey("device1", "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            var deviceClient = DeviceClient.Create(hostName, authMethod1, new ITransportSettings[] { transportSetting });

            var cert = CertificateHelper.InstallCertificateFromFile(LocalCertFilename, LocalCertPasswordFile);
            var authMethod2 = new DeviceAuthenticationWithX509Certificate("device2", cert);
            var device2Client = DeviceClient.Create(hostName, authMethod2, new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 100) });
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            string DeviceConnectionString;
            string environmentConnectionString = Environment.GetEnvironmentVariable("IOTHUB_DEVICE_CONN_STR");

            if (!String.IsNullOrEmpty(environmentConnectionString))
            {
                DeviceConnectionString = environmentConnectionString;
            }
            else
            {
                var authMethod = new Microsoft.Azure.Devices.Client.DeviceAuthenticationWithRegistrySymmetricKey(DeviceID, PrimaryAuthKey);
                DeviceConnectionString = Microsoft.Azure.Devices.Client.IotHubConnectionStringBuilder.Create(HostName, authMethod).ToString();
            }

            try
            {
                Console.WriteLine("Checking for TransportType");
                var           websiteHostName = Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME");
                TransportType transportType   = websiteHostName == null ? TransportType.Mqtt : TransportType.Mqtt_WebSocket_Only;
                Console.WriteLine($"Use TransportType: {transportType.ToString()}");

                Console.WriteLine("Connecting to hub");
                Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, transportType);
                Client.SetDesiredPropertyUpdateCallback(OnDesiredPropertyChanged, null).Wait();
                // Register handlers for direct methods
                var method = Client.SetMethodHandlerAsync("InitiateFirmwareUpdate", OnInitiateFirmwareUpdate, null);
                method = Client.SetMethodHandlerAsync("Reboot", OnReboot, null);

                Console.WriteLine("Send reported properties to IoT Hub");
                Twin           reportedProperties = new Twin(DeviceID);
                TwinCollection reported           = reportedProperties.Properties.Reported;
                {
                    reported["Device"] = new ReportedDevicePropertiesClass()
                    {
                        DeviceState = "normal",
                        Location    = new LocaltionPropertiesClass()
                        {
                            Latitude  = 47.659159,
                            Longitude = -122.141515
                        }
                    };
                    reported["Conifg"] = new ConifgPropertiesClass()
                    {
                        TelemetryInterval    = 45,
                        TemperatureMeanValue = 56.7,
                    };
                    reported["System"] = new SystemPropertiesClass()
                    {
                        Manufacturer    = "Contoso Inc.",
                        FirmwareVersion = "2.22",
                        InstalledRAM    = "8 MB",
                        ModelNumber     = "DB-14",
                        Platform        = "Plat 9.75",
                        Processor       = "i3-9",
                        SerialNumber    = "SER99"
                    };
                    reported["Location"] = new LocaltionPropertiesClass()
                    {
                        Latitude  = 47.659159,
                        Longitude = -122.141515
                    };
                    reported["SupportedMethods"] = new TwinCollection();
                    {
                        var SupportedMethods = reported["SupportedMethods"];
                        SupportedMethods["Reboot"] = "Reboot the device";
                        SupportedMethods["InitiateFirmwareUpdate--FwPackageURI-string"] = "Updates device Firmware. Use parameter FwPackageURI to specifiy the URI of the firmware file";
                    }
                }
                Client.UpdateReportedPropertiesAsync(reported);

                Console.WriteLine("Sending device infomation to RM");
                var deviceTask = SendDeviceInfoAsync(cts.Token, async(object eventData) =>
                {
                    await SendEventAsync(Guid.NewGuid(), eventData);
                });
                deviceTask.Wait();

                var monitorTask = SendMonitorDataAsync(cts.Token, async(object eventData) =>
                {
                    await SendEventAsync(Guid.NewGuid(), eventData);
                });
            }
            catch (AggregateException ex)
            {
                foreach (Exception exception in ex.InnerExceptions)
                {
                    Console.WriteLine();
                    Console.WriteLine("Error in sample: {0}", exception);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine("Error in sample: {0}", ex.Message);
            }
            Console.WriteLine("Waiting for Events.  Press enter to exit...");

            Console.ReadLine();
            cts.Cancel();
            Console.WriteLine("Exiting...");
        }
Ejemplo n.º 9
0
 public bool SendMessagesAsync(Windows.Foundation.AsyncActionCompletedHandler handler)
 {
     int count = 0;
     lock (thisLock)
     {
         count = queue.Count;
     }
     if (count > 0)
     {
         Func<Task> action = async () =>
         {
             System.Collections.Generic.Queue<Message> q = new System.Collections.Generic.Queue<Message>();
             lock (thisLock)
             {
                 int i = 0;
                 foreach (DataPoint p in queue)
                 {
                     string s = HeartBeatText(p.t);
                     var telemetryDataPoint = new
                     {
                         ID = Access.DeviceID,
                         TIME = p.time,
                         MSG = s,
                         CC = p.cc,
                         ASDF = p.asdf,
                         PEAK = p.peak,
                         MAX0 = p.max0,
                         MAX1 = p.max1,
                         AVE0 = p.ave0,
                         AVE1 = p.ave1,
                         AVE = p.ave,
                         BEAT = p.beat,
                         NOAUDIO = p.noAudio,
                         AUDIO = p.audio
                     };
                     var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                     var message = new Message(Encoding.ASCII.GetBytes(messageString));
                     q.Enqueue(message);
                     if (++i == MAX_BATCH) break;
                 }
                 msgCount = Math.Min(queue.Count, MAX_BATCH);
             }
             var auth = new DeviceAuthenticationWithRegistrySymmetricKey(Access.DeviceID, Access.DeviceKey);
             DeviceClient deviceClient = DeviceClient.Create(Access.IoTHubUri, auth, TransportType.Http1);
             await deviceClient.OpenAsync();
             IAsyncAction a = deviceClient.SendEventBatchAsync(q);
             a.Completed = handler;
             await a;
             await deviceClient.CloseAsync();
         };
         task = Task.Factory.StartNew(action);
         return true;
     }
     else return false;
 }