public async Task RiceviDatiAsync() { while (true) { Microsoft.Azure.Devices.Client.Message persona = await _client.ReceiveAsync(); // Se non arrivano messaggi nell'ultimo minuto (default value) il messaggio risulta NULL. if (persona == null) { continue; } // Le operazioni sul messaggio dovranno avere la logica di IDEMPOTENZA. // L'esecuzione dell'azione potrebbe fallire e il messaggio potrebbe essere ripristinato try { string messaggio = Encoding.ASCII.GetString(persona.GetBytes()); _pinBlueLed.SetDriveMode(GpioPinDriveMode.Output); _pinBlueLed.Write(GpioPinValue.Low); if (messaggio == null) { _pinRedLed.SetDriveMode(GpioPinDriveMode.Output); _pinRedLed.Write(GpioPinValue.High); await ErrorReadAsync(); } else { _pinGreenLed.SetDriveMode(GpioPinDriveMode.Output); _pinGreenLed.Write(GpioPinValue.High); Person personaPresente = JsonConvert.DeserializeObject <Person>(messaggio); if (personaPresente != null) { await SuccesReadAsync(personaPresente); } else { await ErrorReadAsync(); } if (!string.IsNullOrEmpty(personaPresente.Uri)) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PersonImage.Source = new BitmapImage(new Uri(personaPresente.Uri)); }); } await ResetAsync(); } await _client.CompleteAsync(persona); // sblocco il messaggio e notifico che è stato ricevuto correttamente } catch (Exception) { await _client.AbandonAsync(persona); } await ResetAsync(); } }
private async void CommunicateAsync(ThreadInput threadInput, string hostName, string deviceId, string deviceKey, string queueStorageConnString) { try { string loopsStr = textBoxLoops.Text; int loops = 0; if (!int.TryParse(loopsStr, out loops)) { loops = -1; } int loopCounter = 0; int increment = 0; int startValue = 0; int endValue = 0; string templateMessage = threadInput.Message; string message; List <ValueGenerator> valueGenList = new List <ValueGenerator>(); foreach (var ope in threadInput.ReplaceOperatorList) { if (ope.Mode.ToLower() == "random" || ope.Mode.ToLower() == "addition") { increment = int.Parse(ope.Increment); if (!int.TryParse(ope.StartValue, out startValue)) { startValue = 0; } if (!int.TryParse(ope.EndValue, out endValue)) { endValue = 0; } if (ope.Mode.ToLower() == "addition") { int range = (endValue - startValue + 1) / threadInput.ThreadCount; startValue = startValue + range * threadInput.ThreadNo; endValue = startValue + range - 1; } var valueGen = new ValueGenerator(ope.Id, ope.Mode, increment, startValue, endValue); valueGenList.Add(valueGen); } } using (var deviceClient = DeviceClient.Create(hostName, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey))) { while (true) { message = templateMessage; if (stopFlag) { lock (lockObject) { ThreadResult trStop = new ThreadResult(); trStop.DeviceId = deviceId; trStop.ThroughputPer60Sec = 0; trStop.IsEnabled = false; dictionaryOfThreadResult[deviceId] = trStop; --threadCount; } return; } if (threadInput.ParamDateTimeValue != string.Empty) { if (message.Contains(threadInput.ParamDateTimeId)) { if (threadInput.ParamDateTimeValue.ToLower() == "datetime.now") { message = message.Replace(threadInput.ParamDateTimeId, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); } else { message = message.Replace(threadInput.ParamDateTimeId, threadInput.ParamDateTimeValue); } } } // Replace $$xxx$$ parameter int size = valueGenList.Count; for (int i = 0; i < size; i++) { message = valueGenList[i].ReplaceValueInMessage(message); } var msg = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(message)); DateTime dt1 = DateTime.Now; // Send msg to IoT Hub await deviceClient.SendEventAsync(msg); // Receive msg int loopCount = 0; int maxLoopCount = 100; if (queueStorageConnString == null || queueStorageConnString == string.Empty) { // ------------------------------------ // Receive msg from IoT Hub // ------------------------------------ while (true) { Microsoft.Azure.Devices.Client.Message receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage == null) { ++loopCount; if (loopCount >= maxLoopCount) { break; } } else { string messageContent = Encoding.UTF8.GetString(receivedMessage.GetBytes()); await deviceClient.CompleteAsync(receivedMessage); break; } } } else { // ------------------------------------ // Receive msg from Queue Storage // ------------------------------------ // If communicate with the deviceId at first, Cloud Robotics FX creates the queue. // So need to wait for a second if (loopCounter == 0) { Thread.Sleep(1000); } CloudStorageAccount storageAccount = CloudStorageAccount.Parse(queueStorageConnString); CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference(deviceId); while (true) { CloudQueueMessage queueMessage = await queue.GetMessageAsync(); if (queueMessage == null) { ++loopCount; if (loopCount >= maxLoopCount) { break; } Thread.Sleep(50); } else { string receivedMessage = queueMessage.AsString; await queue.DeleteMessageAsync(queueMessage); break; } } } DateTime dt2 = DateTime.Now; TimeSpan ts = dt2 - dt1; int milliSec = ts.Seconds * 1000 + ts.Milliseconds; double throuput = 60 * 1000 / milliSec; if (loopCount >= maxLoopCount) { throuput = 0; } ThreadResult tr = new ThreadResult(); tr.DeviceId = deviceId; tr.ThroughputPer60Sec = (int)Math.Round(throuput, 0); tr.UpdateTime = dt2; tr.IsEnabled = true; tr.ExceptionMessage = string.Empty; lock (lockObject) { dictionaryOfThreadResult[deviceId] = tr; } ++loopCounter; if (loops != -1 && loopCounter >= loops) { stopLoadTest(); } } } } catch (Exception ex) { ThreadResult tr = new ThreadResult(); tr.DeviceId = deviceId; tr.ThroughputPer60Sec = 0; tr.UpdateTime = DateTime.Now; tr.IsEnabled = false; tr.ExceptionMessage = ex.ToString(); lock (lockObject) { dictionaryOfThreadResult[deviceId] = tr; } throw; } }
private async void ReceiveC2dAsync() { while (deviceClient != null) { try { Microsoft.Azure.Devices.Client.Message receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage == null) { continue; } textBoxOutput.Text += string.Format("Received message: {0}", Encoding.UTF8.GetString(receivedMessage.GetBytes())); textBoxOutput.Text += Environment.NewLine; await deviceClient.CompleteAsync(receivedMessage); } catch (Exception ex) { if (deviceClient != null) { throw ex; } } } }