private async Task ReceiveCommands(DeviceClient deviceClient) { Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; while (true) { try { receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage != null) { _callback(Encoding.ASCII.GetString(receivedMessage.GetBytes())); await deviceClient.CompleteAsync(receivedMessage); } // Note: In this sample, the polling interval is set to // 10 seconds to enable you to see messages as they are sent. // To enable an IoT solution to scale, you should extend this // interval. For example, to scale to 1 million devices, set // the polling interval to 25 minutes. // For further information, see // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging //await Task.Delay(TimeSpan.FromSeconds(10)); } catch { Debug.WriteLine("ReceiveCommands: Encountered an exception"); } } }
private async Task ReceiveCommands(DeviceClient deviceClient) { System.Diagnostics.Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; string messageData; int recoverTimeout=1000; while (true) { try { receivedMessage = await deviceClient.ReceiveAsync();// TimeSpan.FromSeconds(1)); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); System.Diagnostics.Debug.WriteLine(String.Format("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData)); await deviceClient.CompleteAsync(receivedMessage); } recoverTimeout = 1000; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); await Task.Delay(recoverTimeout); recoverTimeout *= 10; // increment timeout for connection recovery if(recoverTimeout>600000)//set a maximum timeout { recoverTimeout = 600000; } } } }
private async Task InitializeDeviceClient(string connectionString) { _deviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Http1); var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); DeviceClientPanel.Children.Add(new TextBlock() { Text = "Host: " + iotHubConnectionStringBuilder.HostName }); DeviceClientPanel.Children.Add(new TextBlock() { Text = "Device: " + iotHubConnectionStringBuilder.DeviceId }); Message receivedMessage; string messageData; while (true) { receivedMessage = await _deviceClient.ReceiveAsync(); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); var updateAccessKeyRequest = JsonConvert.DeserializeObject<UpdateAccessKeyRequest>(messageData); if (updateAccessKeyRequest != null) { DeviceClientPanel.Children.Add(new TextBlock() { Text = "Update Access Key received" }); UpdateConnectionString(updateAccessKeyRequest.AccessKey); await _deviceClient.CloseAsync(); _deviceClient = DeviceClient.CreateFromConnectionString(GetConnectionString(), TransportType.Http1); await _deviceClient.CompleteAsync(receivedMessage); } } } }
//Look here for details: https://azure.microsoft.com/en-us/develop/iot/ public static async Task ReceiveCommands(DeviceClient deviceClient) { try { System.Diagnostics.Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; string messageData; if (deviceClient != null) { //while (true) //{ receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(5)); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); System.Diagnostics.Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData); await deviceClient.CompleteAsync(receivedMessage); return; } //} } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Error from IoTHub: " + ex.Message.ToString()); } }
public IoTHubCommunication(Device device) { _client = DeviceClient.Create("cloudbrew.azure-devices.net", new DeviceAuthenticationWithRegistrySymmetricKey(device.Id.ToString(), device.Key), TransportType.Http1); Task.Run(async () => { while (true) { var message = await _client.ReceiveAsync(); if (message == null) continue; var messageContent = Encoding.ASCII.GetString(message.GetBytes()); InvokeOnMessage(new MessageEventArgs {Message = messageContent}); await _client.CompleteAsync(message); } }); }
private async Task ReceiveMessages() { while (true) { var msg = await deviceClient.ReceiveAsync(); if (msg != null) { lock (this) { receivedMessage = msg; if (C2DMessageReceived != null) { C2DMessageReceived(this, receivedMessage); } } } } }
static async Task ReceiveCommands(DeviceClient deviceClient) { Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; string messageData; while (true) { receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData); await deviceClient.CompleteAsync(receivedMessage); } await Task.Delay(TimeSpan.FromSeconds(10)); } }
// Receive messages from IoT Hub static async Task ReceiveCommands(DeviceClient deviceClient) { Console.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Microsoft.Azure.Devices.Client.Message receivedMessage; string messageData; while (true) { receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1)); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); writeToConsole(string.Format("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData), true); switch (messageData) { case "stop": { newCar.Stop(); await SendEvent(carClient, newCar, "Stopped the car"); writeToConsole(string.Format("Stopped car {0}", newCar.Id), true); break; } case "nail": { bool flattenedTire = false; int MAX_NUM_TIRES = 4; do { if (numflatTires == MAX_NUM_TIRES) { flattenedTire = true; break; } for (int i = 0; i < 3; i++) { int tireToFlatten = randomTire.Next(0, MAX_NUM_TIRES); if (!newCar.Tires[tireToFlatten].IsFlat()) { newCar.Tires[tireToFlatten].Flatten(); numflatTires++; await SendEvent(carClient, newCar, string.Format("Tire {0} was flattened", tireToFlatten.ToString())); flattenedTire = true; writeToConsole(string.Format("Tire {0} was flattened", tireToFlatten.ToString()), true); break; } } } while (flattenedTire != true); if (numflatTires == MAX_NUM_TIRES) { writeToConsole(string.Format("All tires are already flat"), true); flattenedTire = true; } break; } case "miles": { await SendEvent(carClient, newCar, string.Format("Odometer reading for car {0} is {1}", newCar.Id.ToString(), newCar.OdometerInMiles.ToString())); writeToConsole(string.Format("Odometer reading for car {0} is {1}", newCar.Id.ToString(), newCar.OdometerInMiles.ToString()), true); break; } case "replaceflat": { newCar.ReplaceFlat(); await SendEvent(carClient, newCar, "Flat replaced on car"); writeToConsole(string.Format("Flat replaced on car {0}", newCar.Id), true); break; } default: { newCar.Move(10); await SendEvent(carClient, newCar, string.Format("Hello from the car {0}", newCar.Id.ToString())); writeToConsole(string.Format("Hello from the car {0}", newCar.Id.ToString()), true); break; } } await deviceClient.CompleteAsync(receivedMessage); } } }
/// <summary> /// Connect /// Connect to Azure IoT Hub ans start the send and receive loops /// </summary> /// <returns></returns> public bool Connect() { try { // Create Azure IoT Hub Client and open messaging channel deviceClient = DeviceClient.CreateFromConnectionString(this.ConnectionString); deviceClient.OpenAsync(); IsConnected = true; // Create send and receive tasks CancellationToken ct = TokenSource.Token; Task.Factory.StartNew(async()=> { while (true) { if (SendTelemetryData) { // Create message to be sent D2CMessage[] dataToSend = new D2CMessage[Sensors.Count]; int index = 0; foreach (KeyValuePair<string, D2CMessage> sensor in Sensors) { // Update the values that sensor.Value.displayname = DisplayName; sensor.Value.location = Location; sensor.Value.timecreated = DateTime.UtcNow.ToString("o"); dataToSend[index++] = sensor.Value; } // Send message sendDeviceTelemetryData(dataToSend); } await Task.Delay(SendTelemetryFreq); if (ct.IsCancellationRequested) { // Cancel was called Debug.WriteLine("Sending task canceled"); break; } } }, ct); Task.Factory.StartNew(async() => { while (true) { // Receive message from Cloud (for now this is a pull because only HTTP is available for UWP applications) Message message = await deviceClient.ReceiveAsync(); if (message != null) { try { // Read message and deserialize C2DMessage command = DeSerialize(message.GetBytes()); // Invoke message received callback OnReceivedMessage(new ReceivedMessageEventArgs(command)); // We received the message, indicate IoTHub we treated it await deviceClient.CompleteAsync(message); } catch { // Something went wrong. Indicate the backend that we coudn't accept the message await deviceClient.RejectAsync(message); } } if (ct.IsCancellationRequested) { // Cancel was called Debug.WriteLine("Receiving task canceled"); break; } } }, ct); } catch (Exception e) { Debug.WriteLine("Error while trying to connect to IoT Hub: " + e.Message); deviceClient = null; return false; } return true; }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey)); timer = new Timer( async (x) => { Message message = await deviceClient.ReceiveAsync(); if (message != null) { GpioWorker.Process(Encoding.ASCII.GetString(message.GetBytes())); await deviceClient.CompleteAsync(message); message = null; } }, null, 0, 500 ); }
private void OnResuming(object sender, object e) { deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey)); timer = new Timer( async (x) => { Message message = await deviceClient.ReceiveAsync(); if (message != null) { GpioWorker.Process(Encoding.ASCII.GetString(message.GetBytes())); await deviceClient.CompleteAsync(message); message = null; } }, null, 0, 500 ); }
public async Task <Message> ReceiveAsync(TimeSpan timeout) { return(await _deviceClient.ReceiveAsync(timeout)); }
private async Task receiveCommands(DeviceClient deviceClient) { System.Diagnostics.Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; string messageData; int recoverTimeout = 1000; while (true) { try { receivedMessage = await deviceClient.ReceiveAsync();// TimeSpan.FromSeconds(1)); if (receivedMessage != null) { messageData = Encoding.UTF8.GetString(receivedMessage.GetBytes()); messages.Text = messageData; //Process incoming message processMessage(messageData); await deviceClient.CompleteAsync(receivedMessage); } recoverTimeout = 1000; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); await Task.Delay(recoverTimeout); recoverTimeout *= 10; // increment timeout for connection recovery if (recoverTimeout > 600000)//set a maximum timeout { recoverTimeout = 600000; } } } }
// Receive messages from IoT Hub static async void ReceiveCommands(DeviceClient deviceClient) { Message receivedMessage = null; string data; if (deviceClient != null) receivedMessage = await deviceClient.ReceiveAsync(); if(receivedMessage != null) { data = Encoding.ASCII.GetString(receivedMessage.GetBytes()); var otherData = JsonConvert.DeserializeObject<CommandPayload>(data); if (!string.IsNullOrEmpty(otherData.Message)) _nightMode = otherData.Mode; _receivedCommand = data; await deviceClient.CompleteAsync(receivedMessage); } else { //receivedCommand = "No Command"; } }