private void Start()
 {
     try
     {
         deviceClient = DeviceClient.Create(Properties.AzureSettings.Default.Host,
                                            new DeviceAuthenticationWithRegistrySymmetricKey(Properties.AzureSettings.Default.DeviceId,
                                                                                             Properties.AzureSettings.Default.AccessKey), TransportType.Mqtt);
     }
     catch { ErrorText = "Error: Can't create cloud client"; }
     SendTimer.Start();
     CloudButtonContent = "Stop";
 }
Beispiel #2
0
    /// <summary>
    /// attempt to create a device client with the user credentials stored in the tpm
    /// </summary>
    public void initializeWithProvisionedDevice()
    {
        TpmDevice myDevice = new TpmDevice(0);
        string    hubUri   = myDevice.GetHostName();

        devID = myDevice.GetDeviceId();
        string sasToken = myDevice.GetSASToken();

        deviceClient = DeviceClient.Create(hubUri,
                                           AuthenticationMethodFactory.CreateAuthenticationWithToken(devID, sasToken),
                                           TransportType.Amqp);
    }
Beispiel #3
0
 public MainPage()
 {
     this.InitializeComponent();
     StatusNormalBrush = StatusIndicator.Fill;
     if (!TryInitGPIO().Result)
     {
         WriteMessage("GPIO initialization failed").Wait();
     }
     deviceClient = DeviceClient.Create(HubEndpoint,
                                        AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt_WebSocket_Only);
     deviceClient.SetMethodHandlerAsync("ToggleLED", new MethodCallback(ToggleLEDMethod), null);
 }
Beispiel #4
0
        public IoTHub()
        {
            string connectionStringIoT = GetIoTConnectionString();
            string eventHubName        = ConfigurationManager.AppSettings["EventHubName"];
            string iotHubUri           = ConfigurationManager.AppSettings["IotHubUri"];

            registryManager = RegistryManager.CreateFromConnectionString(connectionStringIoT);

            AddDeviceAsync().Wait();

            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey));
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            registryManager = RegistryManager.CreateFromConnectionString(connectionString);
            AddDeviceAsync().Wait();
            Console.ReadLine();
            Console.WriteLine(deviceKey);
            Console.WriteLine("Simulated device\n");
            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey), Microsoft.Azure.Devices.Client.TransportType.Mqtt);

            SendDeviceToCloudMessagesAsync();
            Console.ReadLine();
        }
Beispiel #6
0
        public async Task ProvisioningDeviceClient_ValidRegistrationId_Register_Ok(
            string transportType,
            string securityType,
            X509EnrollmentType?x509EnrollmentType,
            TransportFallbackType?transportFallback,
            bool setCustomProxy,
            string proxyServerAddress = null)
        {
            using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, transportFallback))
                using (SecurityProvider security = await CreateSecurityProviderFromName(securityType, x509EnrollmentType).ConfigureAwait(false))
                {
                    _verboseLog.WriteLine("Creating device");

                    if (ImplementsWebProxy(transportType, transportFallback) && setCustomProxy)
                    {
                        transport.Proxy = (proxyServerAddress != null) ? new WebProxy(proxyServerAddress) : null;
                    }

                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                        s_globalDeviceEndpoint,
                        Configuration.Provisioning.IdScope,
                        security,
                        transport);

                    var cts = new CancellationTokenSource(PassingTimeoutMiliseconds);

                    _log.WriteLine("ProvisioningDeviceClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false);

                    Assert.IsNotNull(result);
                    _log.WriteLine($"{result.Status} (Error Code: {result.ErrorCode}; Error Message: {result.ErrorMessage})");
                    _log.WriteLine($"ProvisioningDeviceClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    Assert.AreEqual(ProvisioningRegistrationStatusType.Assigned, result.Status);
                    Assert.IsNotNull(result.AssignedHub);
                    Assert.IsNotNull(result.DeviceId);

                    Client.IAuthenticationMethod auth = CreateAuthenticationMethodFromSecurityProvider(security, result.DeviceId);

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, GetDeviceTransportType(transportType, transportFallback)))
                    {
                        _log.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync().ConfigureAwait(false);

                        _log.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(
                            new Client.Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                        _log.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync().ConfigureAwait(false);
                    }
                }
        }
Beispiel #7
0
 public void sendMessage()
 {
     try
     {
         DeviceClient deviceClient = DeviceClient.Create(iotHubHostName, new DeviceAuthenticationWithRegistrySymmetricKey(_deviceId, _deviceKey));
         sendCloudToDeviceMessageAsync(deviceClient, _deviceId, _messageString);
     }
     catch (Exception e)
     {
         log.Fatal(e.ToString());
     }
 }
Beispiel #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Simulated device\n");
            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey));

            SendDeviceToCloudMessagesAsync();
            ReceiveC2dAsync();

            SendDeviceToCloudInteractiveMessagesAsync();

            Console.ReadLine();
        }
Beispiel #9
0
        public DataProcessor()
        {
            System.Threading.TimerCallback cb = new System.Threading.TimerCallback(ProcessData);
            _timerDbLog = new System.Threading.Timer(cb, null, _dbLogTimerDueTime, _dbLogTimerPeriod);
            InitDataTable();

            System.Threading.TimerCallback cba = new System.Threading.TimerCallback(SendToAzure);
            _timerAzure = new System.Threading.Timer(cba, null, _azureTimerDueTime, _azureTimerPeriod);

            _deviceClient = DeviceClient.Create(_iotHubUri,
               AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(_deviceId, _deviceKey), TransportType.Http1);
        }
Beispiel #10
0
        static private DeviceClient CreateDeviceClient(string deviceId, string deviceKey)
        {
#if false
            //AMQP (default)
            return(DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey),
                                       Microsoft.Azure.Devices.Client.TransportType.Amqp_WebSocket_Only));
#else
            //HTTPS
            return(DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey),
                                       Microsoft.Azure.Devices.Client.TransportType.Http1));
#endif
        }
Beispiel #11
0
        static void Main()
        {
            var myDevice = GetOrCreateDevice();
            var client   = DeviceClient.Create("azure-iot-demo.azure-devices.net",
                                               new DeviceAuthenticationWithRegistrySymmetricKey(myDevice.Id.ToString(), myDevice.Key),
                                               TransportType.Amqp);

            SendDummyUpdates(client);
            ListenForCommands(client);
            Console.ReadLine();
            client.CloseAsync().Wait();
        }
Beispiel #12
0
        public static void Main(string[] args)
        {
            // Register Device with Azure
            registryManager = RegistryManager.CreateFromConnectionString(connectionString);
            RegisterDeviceAsync().Wait();

            Console.WriteLine("Simulated device\n");
            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey));

            SendDeviceToCloudMessagesAsync();
            Console.ReadLine();
        }
Beispiel #13
0
        static async void SendDeviceToCloudMessagesAsync()
        {
            var deviceClient = DeviceClient.Create(iotHubUri,
                                                   AuthenticationMethodFactory.
                                                   CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey),
                                                   TransportType.Http1);

            var str     = "Hello, Cloud!";
            var message = new Message(Encoding.ASCII.GetBytes(str));

            await deviceClient.SendEventAsync(message);
        }
Beispiel #14
0
        public MainPage()
        {
            this.InitializeComponent();
            var key = AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(Config.Default.DeviceName, Config.Default.DeviceKey);

            deviceClient = DeviceClient.Create(Config.Default.IotHubUri, key, TransportType.Http1);
            init();
            CancellationTokenSource t = new CancellationTokenSource();

            startMessageReceiver(t.Token);
            Logger.LogReceived += log;
        }
Beispiel #15
0
        public MainPage()
        {
            this.InitializeComponent();
            this.Loaded += MainPage_Loaded;

            // Chose a temperature provider
            //temperatureProvider = new FezHatTemperatureProvider(); // GHI FEZ HAT
            //temperatureProvider = new FezCreamTemperatureProvider(4); // GHI FEZ Cream with TempHumidSI70 socket
            temperatureProvider = new RandomTemperatureProvider(); // Use the random provider, if no temperature sensor is connected

            deviceClient = DeviceClient.Create("<IOTHUB_HOSTNAME>", new DeviceAuthenticationWithRegistrySymmetricKey("<DEVICE_ID>", "<PRIMARY_KEY>"));
        }
Beispiel #16
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Simulated Bowl \n");
            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt);
            var twin = await deviceClient.GetTwinAsync();

            maxDoses = Convert.ToDouble(twin.DesiredProperty("dosesCounter"));

            if (twin.IsReportedPropertyEmpty("dosesCounter"))
            {
                doses = maxDoses;
                Console.WriteLine($"Doses {doses}");
            }
            else
            {
                doses = Convert.ToDouble(twin.ReportedProperty("dosesCounter"));
            }


            while (true)
            {
                Console.WriteLine($"Doses {doses}");
                Console.WriteLine($"[enter command (type 'i' for instructions)]");
                string input = Console.ReadLine();
                switch (input.ToLower())
                {
                case "cat wants to eat":
                    await CatEats(deviceClient);

                    break;

                case "add dose":
                    await AddDose(deviceClient);

                    break;

                case "refill":
                    await Refill(deviceClient);

                    break;

                case "i":
                    Console.WriteLine("- cat wants to eat: a dose gets eaten");
                    Console.WriteLine("- add dose: add a dose");
                    Console.WriteLine("- refill: restore doses quantity");
                    break;

                default:
                    Console.WriteLine("Syntax error");
                    break;
                }
            }
        }
Beispiel #17
0
        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) });
        }
        public static async Task RunSample()
        {
            // Replace the following type with SecurityClientTpm() to use a real TPM2.0 device.
            Console.WriteLine("Starting TPM simulator.");
            SecurityClientTpmSimulator.StartSimulatorProcess();

            using (var security = new SecurityClientTpmSimulator(RegistrationId))
                using (var transport = new ProvisioningTransportHandlerHttp())
                {
                    // Note that the TPM simulator will create a NVChip file containing the simulated TPM state.
                    Console.WriteLine("Extracting endorsement key.");
                    string base64EK = Convert.ToBase64String(security.GetEndorsementKey());

                    Console.WriteLine(
                        "In your Azure Device Provisioning Service please go to 'Manage enrollments' and select " +
                        "'Individual Enrollments'. Select 'Add' then fill in the following:");

                    Console.WriteLine("\tMechanism: TPM");
                    Console.WriteLine($"\tRegistration ID: {RegistrationId}");
                    Console.WriteLine($"\tEndorsement key: {base64EK}");
                    Console.WriteLine("\tDevice ID: iothubtpmdevice1 (or any other valid DeviceID)");
                    Console.WriteLine();
                    Console.WriteLine("Press ENTER when ready.");
                    Console.ReadLine();

                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(s_idScope, security, transport);

                    Console.Write("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync();

                    Console.WriteLine($"{result.Status}");
                    Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        return;
                    }

                    var auth = new DeviceAuthenticationWithTpm(result.DeviceId, security);

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt))
                    {
                        Console.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync();

                        Console.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage")));

                        Console.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync();
                    }
                }
        }
Beispiel #19
0
        public MainPage()
        {
            this.InitializeComponent();

            deviceClient   = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("GrovePiSoundSensor", deviceKey), TransportType.Http1);
            soundsensor    = DeviceFactory.Build.SoundSensor(Pin.AnalogPin0);
            lcd            = DeviceFactory.Build.RgbLcdDisplay().SetText("Hello").SetBacklightRgb(0, 0, 255);
            timer          = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(5000);
            timer.Tick    += Timer_Tick;
            timer.Start();
        }
Beispiel #20
0
        static async void SendDeviceToCloudMessagesAsync()
        {
            string iotHubUri = "BuchRaspberryHub.azure-devices.net";
            string deviceId  = "MeinRaspberry";
            string deviceKey = "<Key>";

            var deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1);

            string  str     = String.Format("Temperatur um {0} : {1} Grad Celsius", DateTime.Now, GetTemperature());
            Message message = new Message(Encoding.ASCII.GetBytes(str));
            await deviceClient.SendEventAsync(message);
        }
        public async Task RunAsync()
        {
            Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}");

            // Register the Device with DPS
            Console.Write("ProvisioningClient RegisterAsync . . . ");
            DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

            Console.WriteLine($"Device Registration Status: {result.Status}");
            Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
            deviceId = result.DeviceId;

            // Verify Device Registration Status
            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'");
            }

            // Create x509 DeviceClient Authentication
            Console.WriteLine("Creating X509 DeviceClient authentication.");
            var auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (security as SecurityProviderX509).GetAuthenticationCertificate());


            Console.WriteLine("Simulated Device. Ctrl-C to exit.");
            using (iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp))
            {
                // Explicitly open DeviceClient to communicate with Azure IoT Hub
                Console.WriteLine("DeviceClient OpenAsync.");
                await iotClient.OpenAsync().ConfigureAwait(false);


                // TODO 1: Setup OnDesiredPropertyChanged Event Handling to receive Desired Properties changes
                Console.WriteLine("Connecting SetDesiredPropertyUpdateCallbackAsync event handler...");
                await iotClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false);


                // TODO 2: Load Device Twin Properties since device is just starting up
                Console.WriteLine("Loading Device Twin Properties...");
                var twin = await iotClient.GetTwinAsync().ConfigureAwait(false);

                // Use OnDesiredPropertyChanged event handler to set the loaded Device Twin Properties (re-use!)
                await OnDesiredPropertyChanged(twin.Properties.Desired, null);


                // Start reading and sending device telemetry
                Console.WriteLine("Start reading and sending device telemetry...");
                await SendDeviceToCloudMessagesAsync(iotClient);

                // Explicitly close DeviceClient
                Console.WriteLine("DeviceClient CloseAsync.");
                await iotClient.CloseAsync().ConfigureAwait(false);
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Simulated device\n");
            deviceClient             = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey), TransportType.Mqtt);
            deviceClient.ProductInfo = "HappyPath_Simulated-CSharp";
            SendDeviceToCloudMessagesAsync();


            ReceiveC2DAsync();

            Console.ReadLine();
        }
        //// This function create a device with x509 cert and send a message to the iothub on the transport specified.
        //// It then verifies the message is received at the eventHubClient.
        internal async Task SendSingleMessageX509(Client.TransportType transport)
        {
            // TODO: Update Jenkins Config
            string endpoint = Configuration.IoTHub.EventHubString;

            if (endpoint.IsNullOrWhiteSpace())
            {
                return;
            }

            Tuple <string, string> deviceInfo = TestUtil.CreateDeviceWithX509(DevicePrefix, hostName, registryManager);

            EventHubClient    eventHubClient;
            PartitionReceiver eventHubReceiver = await CreateEventHubReceiver(deviceInfo.Item1).ConfigureAwait(false);

            X509Certificate2 cert = Configuration.IoTHub.GetCertificateWithPrivateKey();

            var auth         = new DeviceAuthenticationWithX509Certificate(deviceInfo.Item1, cert);
            var deviceClient = DeviceClient.Create(deviceInfo.Item2, auth, transport);

            try
            {
                await deviceClient.OpenAsync().ConfigureAwait(false);

                string         payload;
                string         p1Value;
                Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value);
                await deviceClient.SendEventAsync(testMessage).ConfigureAwait(false);

                bool      isReceived = false;
                Stopwatch sw         = new Stopwatch();
                sw.Start();
                while (!isReceived && sw.Elapsed.Minutes < 1)
                {
                    var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5)).ConfigureAwait(false);

                    isReceived = VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value);
                }

                sw.Stop();

                Assert.IsTrue(isReceived, "Message is not received.");
            }
            finally
            {
                await deviceClient.CloseAsync().ConfigureAwait(false);

                await eventHubReceiver.CloseAsync().ConfigureAwait(false);

                await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false);
            }
        }
Beispiel #24
0
        private async Task SendDeviceToCloudMessagesAsync(Device device, string deviceId)
        {
            string iotHubUri = _connectionstring.Split(';')
                               .First(x => x.StartsWith("HostName=", StringComparison.InvariantCultureIgnoreCase))
                               .Replace("HostName=", "").Trim();

            if (device == null)
            {
                ServiceEventSource.Current.ServiceMessage(Context, "Device '{0}' doesn't exist.", deviceId);
            }

            var deviceClient = DeviceClient.Create(
                iotHubUri,
                new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, device.Authentication.SymmetricKey.PrimaryKey));

            List <object> events = new List <object>();

            for (int i = 0; i < 10; ++i)
            {
                var body = new
                {
                    Timestamp = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(i))
                };

                events.Add(body);
            }

            Microsoft.Azure.Devices.Client.Message message;
            var serializer = new JsonSerializer();

            using (var stream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(stream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        serializer.Serialize(jsonWriter, events);
                    }
                }

                message = new Microsoft.Azure.Devices.Client.Message(stream.GetBuffer());
                message.Properties.Add("DeviceID", deviceId);
                message.Properties.Add("Temparature", _temperature == 0 ? "50" : _temperature.ToString());
                message.Properties.Add("FanSpeed", "256");
                message.Properties.Add("IsOnline", "true");
                //message.Properties.Add("GatewayId", "1234"); --> SiteId (RegistrationMessage)

                await deviceClient.SendEventAsync(message);

                ServiceEventSource.Current.ServiceMessage(Context, $"Sent message: {Encoding.UTF8.GetString(stream.GetBuffer())}");
            }
        }
Beispiel #25
0
        public async Task ProvisioningDeviceClient_ValidRegistrationId_Register_Ok(
            string transportType,
            string securityType,
            X509EnrollmentType?x509EnrollmentType,
            TransportFallbackType?transportFallback)
        {
            if (!ConfigurationFound())
            {
                _log.WriteLine("Provisioning test configuration not found. Result inconclusive.");
                return;
            }

            using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, transportFallback))
                using (SecurityProvider security = CreateSecurityProviderFromName(securityType, x509EnrollmentType))
                {
                    _verboseLog.WriteLine("Creating device");

                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                        s_globalDeviceEndpoint,
                        Configuration.Provisioning.IdScope,
                        security,
                        transport);

                    var cts = new CancellationTokenSource(PassingTimeoutMiliseconds);

                    _log.WriteLine("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false);

                    Assert.IsNotNull(result);
                    _log.WriteLine($"{result.Status} (Error Code: {result.ErrorCode}; Error Message: {result.ErrorMessage})");
                    _log.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    Assert.AreEqual(ProvisioningRegistrationStatusType.Assigned, result.Status);
                    Assert.IsNotNull(result.AssignedHub);
                    Assert.IsNotNull(result.DeviceId);

                    Client.IAuthenticationMethod auth = CreateAuthenticationMethodFromSecurityProvider(security, result.DeviceId);

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, Client.TransportType.Mqtt_Tcp_Only))
                    {
                        _log.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync().ConfigureAwait(false);

                        _log.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(
                            new Client.Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                        _log.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync().ConfigureAwait(false);
                    }
                }
        }
Beispiel #26
0
        private async Task UploadFileGranularAsync(Stream source, string filename, Http1TransportSettings fileUploadTransportSettings, bool useX509auth = false)
        {
            using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(
                      Logger,
                      _devicePrefix,
                      useX509auth?TestDeviceType.X509 : TestDeviceType.Sasl).ConfigureAwait(false);

            DeviceClient deviceClient;
            var          clientOptions = new ClientOptions()
            {
                FileUploadTransportSettings = fileUploadTransportSettings
            };

            X509Certificate2 cert = null;
            DeviceAuthenticationWithX509Certificate x509Auth = null;

            if (useX509auth)
            {
                cert     = s_selfSignedCertificate;
                x509Auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert);

                deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, x509Auth, Client.TransportType.Http1);
            }
            else
            {
                deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, Client.TransportType.Http1, clientOptions);
            }

            var fileUploadSasUriRequest = new FileUploadSasUriRequest()
            {
                BlobName = filename
            };

            using (deviceClient)
            {
                FileUploadSasUriResponse fileUploadSasUriResponse = await deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest).ConfigureAwait(false);

                var  blob       = new CloudBlockBlob(fileUploadSasUriResponse.GetBlobUri());
                Task uploadTask = blob.UploadFromStreamAsync(source);
                await uploadTask.ConfigureAwait(false);

                var notification = new FileUploadCompletionNotification
                {
                    CorrelationId = fileUploadSasUriResponse.CorrelationId,
                    IsSuccess     = uploadTask.IsCompleted
                };

                await deviceClient.CompleteFileUploadAsync(notification).ConfigureAwait(false);
            }

            x509Auth?.Dispose();
        }
Beispiel #27
0
        static void Main(string[] args)
        {
            var deviceId = "aircraft101";

            Console.WriteLine("Simulated device => {0} \n", deviceId);

            //deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceThumbprint));
            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithX509Certificate(deviceId, new X509Certificate2("sample.pfx", "password here")));

            //SendDeviceToCloudMessagesAsync(deviceId);
            SendDeviceToCloudWithCriticalMessagesAsync(deviceId);
            Console.ReadLine();
        }
Beispiel #28
0
        private async Task Reset()
        {
            _device = await _registryManager.GetDeviceAsync(_deviceId);

            if (_device == null)
            {
                _logger.Warning($"Could not find device '{_deviceId}' registered in IoT Hub", GetType().Name);

                return;
            }

            _deviceClient = DeviceClient.Create(_iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(_deviceId, _device.Authentication.SymmetricKey.PrimaryKey), Microsoft.Azure.Devices.Client.TransportType.Amqp);
        }
Beispiel #29
0
        // Initialize the device client instance using symmetric key based authentication, over Mqtt protocol
        //(TCP, with fallback over Websocket) and setting the ModelId into ClientOptions.
        // This method also sets a connection status change callback, that will get triggered any time the device's
        //connection status changes.
        private static DeviceClient InitializeDeviceClient(string hostname,
                                                           IAuthenticationMethod authenticationMethod)
        {
            var options = new ClientOptions   {
                ModelId = ModelId,
            };
            DeviceClient deviceClient = DeviceClient.Create(hostname, authenticationMethod, TransportType.Mqtt, options);

            deviceClient.SetConnectionStatusChangesHandler((status, reason) => {
                s_logger.LogDebug($"Connection status change registered - status={status}, reason={reason}.");
            });
            return(deviceClient);
        }
Beispiel #30
0
        private static void Main(string[] args)
        {
            string DeviceId  = ConfigurationManager.AppSettings["DeviceId"];
            string DeviceKey = ConfigurationManager.AppSettings["DeviceKey"];
            string IotHubUri = ConfigurationManager.AppSettings["IotHubUri"];

            Console.WriteLine("Simulated device\n");
            _deviceClient = DeviceClient.Create(IotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt);

            SendDeviceToCloudMessagesAsync();
            ReceiveC2dAsync();
            Console.ReadLine();
        }