public static async Task SendSingleMessageModuleAndVerifyAsync(ModuleClient moduleClient, string deviceId) { EventHubTestListener testListener = await EventHubTestListener.CreateListener(deviceId).ConfigureAwait(false); try { string payload; string p1Value; Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value); await moduleClient.SendEventAsync(testMessage).ConfigureAwait(false); bool isReceived = await testListener.WaitForMessage(deviceId, payload, p1Value).ConfigureAwait(false); Assert.IsTrue(isReceived, "Message is not received."); } finally { await testListener.CloseAsync().ConfigureAwait(false); } }
private void SendIotHubMessage(string messageJson, string schema) { var message = new Message(Encoding.UTF8.GetBytes(messageJson)) { CreationTimeUtc = DateTime.UtcNow, MessageSchema = schema }; Task msgTask = moduleClient.SendEventAsync(message); msgTask.Wait(); if (msgTask.IsCompletedSuccessfully) { Console.WriteLine(" {1}--Sent: {0}", messageJson, DateTime.Now); } else { throw new ApplicationException("Failed to send IoT Hub message"); } }
static async Task SendEventAsync(ModuleClient client, Guid batchId, string trackingId, long messageId) { var random = new Random(); var bufferPool = new BufferPool(); using (Buffer data = bufferPool.AllocBuffer(Settings.Current.MessageSizeInBytes)) { // generate some bytes random.NextBytes(data.Data); // build message var messageBody = new { data = data.Data }; var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageBody))); message.Properties.Add("sequenceNumber", messageId.ToString()); message.Properties.Add("batchId", batchId.ToString()); message.Properties.Add("trackingId", trackingId); await client.SendEventAsync(Settings.Current.OutputName, message); } }
public async Task EmitMessage() { if (MessageIndex >= Messages.Count) { MessageIndex = 0; } Log.Information($"Emitting telemetry message {MessageIndex}"); var message = Messages[MessageIndex++]; message.Timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString(); var json = JsonConvert.SerializeObject(message, Formatting.Indented); using (var iotMessage = new Message(Encoding.UTF8.GetBytes(json.Replace("NaN", "")))) { await ModuleClient.SendEventAsync("telemetry", iotMessage); } }
private static async Task RequestTimeMessage(ModuleClient moduleClient, ManualResetEventSlim resetEvent, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { try { resetEvent.Reset(); var message = new Message { CorrelationId = DateTime.UtcNow.ToString("O") }; await moduleClient.SendEventAsync("GetTimeMessage", message); resetEvent.Wait(cancellationToken); } catch (Exception ex) { LogException(ex); } } }
private static async Task MessageReceivedAsync(object sender, MqttApplicationMessageReceivedEventArgs eventArgs) { var info = $"Timestamp: {DateTime.Now:O} | Topic: {eventArgs.ApplicationMessage.Topic} | Payload: {Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)} | QoS: {eventArgs.ApplicationMessage.QualityOfServiceLevel}"; Console.WriteLine($"Message: {info}"); var payload = Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload); try { string topic = eventArgs.ApplicationMessage.Topic; DeviceConfig deviceConfig = Devices.Find(d => d.DataTopic.Equals(topic)); string dataBuffer = "Unkown format"; if (deviceConfig.Schema.Equals("DefaultEngine")) { var messageBody = JsonConvert.DeserializeObject <MessageBody>(payload); if (messageBody.Machine.Temperature >= Temp_Threshold) { Console.WriteLine("Alert: over Temp_Threshold"); await PublishMQTTMessageAsync(deviceConfig, messageBody.TimeCreated.ToLongTimeString(), "MQTTClient"); } dataBuffer = JsonConvert.SerializeObject(messageBody); } var message = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(dataBuffer)); //TODO: package sous forme de propriété // MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); // ITransportSettings[] settings = { mqttSetting }; // ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); // await ioTHubModuleClient.OpenAsync(); await ioTHubModuleClient.SendEventAsync("output1", message); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
// Async method to send simulated telemetry internal async Task SendDeviceToCloudMessagesAsync(ModuleClient moduleClient, string deviceId, string moduleId, ILogger logger) { // Initial telemetry values int counter = 1; string logPrefix = "data".BuildLogPrefix(); string messageString = string.Empty; using (logger.BeginScope($"{logPrefix}::{ModuleSettings.ArtifactId}::MEASURED DATA")) { while (true) { //Randomize data messageString = await _telemetryMessagingService.GetRandomizedMessageAsync(deviceId, moduleId); var message = new Message(Encoding.UTF8.GetBytes(messageString)); message.Properties.Add("messageType", "data"); // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. //message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); message.ContentType = "application/json"; message.ContentEncoding = "utf-8"; // Send the tlemetry message await moduleClient.SendEventAsync(message); counter++; logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Sent message: {messageString}."); logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::COUNTER: {counter}."); if (_stopProcessing) { logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::STOP PROCESSING."); break; } await Task.Delay(_telemetryInterval * 1000); } } }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); ITransportSettings[] settings = { mqttSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); string messageString = "Hello from the EdgeHelloWorldSender"; while (true) { var eventMessage = new Message(Encoding.UTF8.GetBytes(messageString)); await ioTHubModuleClient.SendEventAsync("EdgeHelloWorldSenderOutput", eventMessage); Console.WriteLine($"Sent message: {messageString} to EdgeHelloWorldReceiver"); } }
static async Task SendMessageToHub(Message message) { try { if (_ioTHubModuleClient == null) { _consoleLogger.LogCritical($"SendMessageToHub: ModuleClient doesn't exist"); return; } await _ioTHubModuleClient.SendEventAsync("output1", message); _consoleLogger.LogTrace("Hub message was sent successfully"); return; } catch (Exception e) { _consoleLogger.LogCritical("SendMessageToHub caught an exception: {0}", e); } }
/// <summary> /// Send a Telemetry message with the Module Client to IoT Hub to create the AAD Identity /// </summary> /// <param name="moduleClient"></param> /// <param name="operationType"></param> /// <returns></returns> public async Task RequestAADOperation(OperationTypeEnum operationType) { //Just ask for the creation of the module identity string payloadJsonString = JsonConvert.SerializeObject(new { OperationType = operationType }); _logger.LogInformation($"Sending Telemetry message to request a new identity:\n{payloadJsonString}"); byte[] payload = Encoding.UTF8.GetBytes(payloadJsonString); var message = new Message(payload); message.ContentType = "application/json"; message.ContentEncoding = "utf-8"; //ad an application specific property to mark this telemetry message as an AAD Module Identity Operation //this will be used for the filtering / routing of the message to the appriopriate component on the cloud //to handle such kind of request message.Properties.Add(AADModuleIdentityOperationMessage.TelemetryTypePropertyName, AADModuleIdentityOperationMessage.TelemetryTypeValue); await _moduleClient.SendEventAsync("AADModuleIdentityOpOutput", message); }
/// <summary> /// This method is called whenever the Filter module is sent a message from the EdgeHub. /// It filters the messages based on the temperature value in the body of the messages, /// and the temperature threshold set via config. /// It prints all the incoming messages. /// </summary> static async Task <MessageResponse> PrintAndFilterMessages(Message message, object userContext) { int counterValue = Interlocked.Increment(ref counter); var userContextValues = userContext as Tuple <ModuleClient, ModuleConfig>; if (userContextValues == null) { throw new InvalidOperationException("UserContext doesn't contain " + "expected values"); } ModuleClient moduleClient = userContextValues.Item1; ModuleConfig moduleModuleConfig = userContextValues.Item2; byte[] messageBytes = message.GetBytes(); string messageString = Encoding.UTF8.GetString(messageBytes); Console.WriteLine($"Received message: {counterValue}, Body: [{messageString}]"); // Get message body, containing the Temperature data var messageBody = JsonConvert.DeserializeObject <MessageBody>(messageString); if (messageBody != null && messageBody.Machine.Temperature > moduleModuleConfig.TemperatureThreshold) { Console.WriteLine($"Temperature {messageBody.Machine.Temperature} " + $"exceeds threshold {moduleModuleConfig.TemperatureThreshold}"); var filteredMessage = new Message(messageBytes); foreach (KeyValuePair <string, string> prop in message.Properties) { filteredMessage.Properties.Add(prop.Key, prop.Value); } filteredMessage.Properties.Add("MessageType", "Alert"); await moduleClient.SendEventAsync("alertOutput", filteredMessage).ConfigureAwait(false); } return(MessageResponse.Completed); }
public static async Task SendDataToAzure(string text) { //var text = "{\"info\":\"RPI SerreManagment Working\"}"; var msg = new Message(Encoding.UTF8.GetBytes(text)); try { if (_strconn == null) { await _deviceClient.SendEventAsync(msg); } else { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(_strconn, TransportType.Http1); await deviceClient.SendEventAsync(msg); } } catch (Exception ex) { Debug.WriteLine($"Error posting on Azure Iot Hub: {ex.Message}"); } }
private static async Task SendPhoto(ModuleClient ioTHubModuleClient, CancellationToken token) { if (Storage == null) { return; } CloudStorageAccount account = CloudStorageAccount.Parse(Storage); Console.WriteLine($"Connecting to {account.BlobEndpoint}"); CloudBlobClient blobClient = account.CreateCloudBlobClient(); // Creazione del container Console.WriteLine("Preparing blob container"); CloudBlobContainer cloudBlobContainer = blobClient.GetContainerReference("photos"); await cloudBlobContainer.CreateIfNotExistsAsync(BlobContainerPublicAccessType.Blob, new BlobRequestOptions(), null, token); var client = new HttpClient(); string photoUri; // Download dell'immagine Console.WriteLine("Loading photo"); using (Stream source = await client.GetStreamAsync("https://picsum.photos/1024/768")) { CloudBlockBlob blobReference = cloudBlobContainer.GetBlockBlobReference(Guid.NewGuid().ToString() + ".jpg"); blobReference.Properties.ContentType = "image/jpeg"; // Upload sullo storage Console.WriteLine("Uploading photo"); await blobReference.UploadFromStreamAsync(source); photoUri = blobReference.Uri.ToString(); } // Invio dell'URI byte[] data = Encoding.UTF8.GetBytes(photoUri); var message = new Message(data); await ioTHubModuleClient.SendEventAsync("photo", message, token); }
/// <summary> /// Message loop that simulates people entering the store. /// </summary> /// <param name="cancellationToken">The cancellation,token for gracefully handling cancellation.</param> private static async Task MessageLoopAsync(CancellationToken cancellationToken) { int retryCount = 0; while (!cancellationToken.IsCancellationRequested) { // simulate customer SensorNotification notification = await _customersSimulation.SimulateCustomerAsync(cancellationToken); // prevent event from being sent if module has not yet been initialized properly (desired property) if (!notification.IsInitialized) { Log("Sensor module not yet initialized properly. Skipping event publication."); continue; } try { Log("Customer entered. Sending message ..."); string messageString = JsonConvert.SerializeObject(notification); var message = new Message(Encoding.UTF8.GetBytes(messageString)); // send event await _moduleClient.SendEventAsync("sensorOutput", message); Log($"Message sent: {messageString}"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); retryCount++; if (retryCount == 10) { break; } } } }
internal async Task SendDeviceToCloudErrorAsync(ModuleClient moduleClient, string deviceId, string moduleId, int interval, ILogger logger) { int counter = 1; string logPrefix = "error".BuildLogPrefix(); string messageString = string.Empty; using (logger.BeginScope($"{logPrefix}::{ModuleSettings.ArtifactId}::ERROR MESSAGE (SENT BY THE DEVICE)")) { while (true) { messageString = await _errorMessagingService.GetRandomizedMessageAsync(deviceId, moduleId); var message = new Message(Encoding.ASCII.GetBytes(messageString)); message.Properties.Add("messagetype", "error"); // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. message.ContentType = "application/json"; message.ContentEncoding = "utf-8"; // Send the tlemetry message await moduleClient.SendEventAsync(message); counter++; logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Sent message: {messageString}."); logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::COUNTER: {counter}."); if (_stopProcessing) { logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::STOP PROCESSING."); break; } await Task.Delay(interval * 1000); } } }
// Kevin static void OnTimedEvent(Object source, ElapsedEventArgs e) { // if we have machines to target work on Console.WriteLine("onTimedEvent()"); if (targetMachines != null) { // simple value "machinename:URL:parser;machinename2:URL2:parser" string[] machines = targetMachines.Split(";"); foreach (string machine in machines) { Console.WriteLine("processing: " + machine); string[] machinedata = machine.Split(":"); string machineName = machinedata[0]; string machineURL = machinedata[1]; string machineParser = machinedata[2]; string returnedData = getData(machineName, machineURL, machineParser).Result.ToString(); Console.WriteLine("response was: " + returnedData); dynamic message = new JObject(); message.machineName = machineName; message.machineURL = machineURL; message.machineParser = machineParser; message.data = returnedData; message.processed = DateTime.UtcNow.ToString(); Message ioTMessage = new Message(Encoding.UTF8.GetBytes(message.ToString())); ioTMessage.Properties.Add("processedUTC", DateTime.UtcNow.ToString()); ioTHubModuleClient.SendEventAsync("output1", ioTMessage).Wait(); Console.WriteLine("sent message: " + message.ToString()); } Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime); } else { Console.WriteLine("Error: set the \"targetMachines\" TWIN property"); } }
//private static async Task SendSimulationData(DeviceClient deviceClient) private static async Task SendSimulationData(ModuleClient deviceClient) { while (true) { try { if (desiredPropertiesData.SendData) { counter++; if (counter == 1) { // first time execution needs to reset the data factory IsReset = true; } var messageBody = TemperatureDataFactory.CreateTemperatureData(counter, generationPolicy, IsReset); IsReset = false; var messageString = JsonConvert.SerializeObject(messageBody); var messageBytes = Encoding.UTF8.GetBytes(messageString); var message = new Message(messageBytes); message.ContentEncoding = "utf-8"; message.ContentType = "application/json"; await deviceClient.SendEventAsync("temperatureOutput", message); //await deviceClient.SendEventAsync(message); Console.WriteLine($"\t{DateTime.UtcNow.ToShortDateString()} {DateTime.UtcNow.ToLongTimeString()}> Sending message: {counter}, Body: {messageString}"); } await Task.Delay(TimeSpan.FromSeconds(desiredPropertiesData.SendInterval)); } catch (Exception ex) { Console.WriteLine($"[ERROR] Unexpected Exception {ex.Message}"); Console.WriteLine($"\t{ex.ToString()}"); } } }
private static async Task OutputErrorRouteMessage(string status, string result, ModuleClient moduleClient) { var outputMessage = new OutputMessage { Status = status, Result = result, }; var messageJson = JsonConvert.SerializeObject(outputMessage); var messageBytes = Encoding.UTF8.GetBytes(messageJson); using (var pipeMessage = new Message(messageBytes)) { pipeMessage.ContentType = "application/json"; pipeMessage.ContentEncoding = "utf-8"; await moduleClient.SendEventAsync("Exception", pipeMessage); Console.WriteLine($"Received message '{status}','{result}' sent"); CompensateThrottle(result); } }
public static async Task <bool> SendSqlData(List <TemperatureData> temperatureData) { var success = false; try { var serializedData = JsonConvert.SerializeObject(temperatureData); byte[] messageBytes = Encoding.ASCII.GetBytes(serializedData); var message = new Message(messageBytes); await ioTHubModuleClient.SendEventAsync("output1", message); Console.WriteLine(DateTime.Now.ToString() + " -- Sent message: " + serializedData); success = true; } catch (Exception ex) { Console.WriteLine(ex.Message); } return(success); }
static async Task <bool> SendMessage(string p_messageString, Message message, ModuleClient p_moduleclient) { bool resultbool = false; if (!string.IsNullOrEmpty(p_messageString)) { var messageBytes = Encoding.UTF8.GetBytes(p_messageString); var pipeMessage = new Message(messageBytes); pipeMessage.ContentEncoding = "utf-8"; pipeMessage.ContentType = "application/json"; // foreach (var prop in message.Properties) foreach (var prop in pipeMessage.Properties) { pipeMessage.Properties.Add(prop.Key, prop.Value); } await p_moduleclient.SendEventAsync("output1", pipeMessage); resultbool = true; } return(resultbool); }
static async void GenMessage( ModuleClient client, Random random, Guid batchId, BufferPool bufferPool) { using (Buffer data = bufferPool.AllocBuffer(Settings.Current.MessageSizeInBytes)) { // generate some bytes random.NextBytes(data.Data); // build message var messageBody = new { data = data.Data, }; var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageBody))); message.Properties.Add("sequenceNumber", Interlocked.Increment(ref MessageIdCounter).ToString()); message.Properties.Add("batchId", batchId.ToString()); await client.SendEventAsync(Settings.Current.OutputName, message).ConfigureAwait(false); } }
static async Task SendEventAsync(ModuleClient client, Guid batchId, string trackingId, long messageId) { var random = new Random(); var bufferPool = new BufferPool(); using (Buffer data = bufferPool.AllocBuffer(Settings.Current.MessageSizeInBytes)) { // generate some bytes random.NextBytes(data.Data); // build message var messageBody = new { data = data.Data }; var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageBody))); message.Properties.Add(TestConstants.Message.SequenceNumberPropertyName, messageId.ToString()); message.Properties.Add(TestConstants.Message.BatchIdPropertyName, batchId.ToString()); message.Properties.Add(TestConstants.Message.TrackingIdPropertyName, trackingId); // sending the result via edgeHub await client.SendEventAsync(Settings.Current.OutputName, message); Logger.LogInformation($"Sent message successfully: sequenceNumber={messageId}"); } }
async static void TimerCallback(object state) { // Get sensor value sensor.Value = sensor.GetValue(); // Send value to Decoder JObject decodedMessage = await DecodeMessage(Encoding.UTF8.GetBytes(sensor.Value.ToString()), 1, configuration.Decoder); // Send data upstream. var outMessage = new Message(Encoding.UTF8.GetBytes(decodedMessage.ToString())); try { await ioTHubModuleClient.SendEventAsync("output1", outMessage); Console.WriteLine("Message sent to output1: " + decodedMessage.ToString()); } catch (Exception ex) { Console.WriteLine("Error sending message to output1: " + ex.ToString()); } Console.WriteLine("Done. \n"); }
static async Task <MessageResponse> SendMessage(ModuleClient moduleClient) { var body = new MessageBody() { TimeCreated = DateTime.UtcNow, Machine = new Machine() { Pressure = 1, Temperature = 1 }, Ambient = new Ambient() { Humidity = 1, Temperature = 1 } }; var msg = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(body))); await moduleClient.SendEventAsync("output1", msg); return(MessageResponse.Completed); }
public async Task SendMessage(object messageBody) { var jsonMessage = JsonConvert.SerializeObject(messageBody); var messageBytes = Encoding.UTF8.GetBytes(jsonMessage); using (var message = new Message(messageBytes)) { // Set message body type and content encoding for routing using decoded body values. message.ContentEncoding = "utf-8"; message.ContentType = "application/json"; foreach (var property in Properties) { message.Properties.Add(property); } await _ioTHubModuleClient.SendEventAsync(Name, message); var size = CalculateSize(messageBytes, Properties); Console.WriteLine($"Message with size {size} bytes sent."); } }
public static async Task <MessageResponse> FilterMessagesAsync(Message message, object userContext) { try { ModuleClient moduleClient = (ModuleClient)userContext; var filteredMessage = Filter(message); if (filteredMessage != null) { await moduleClient.SendEventAsync("output1", filteredMessage).ConfigureAwait(false); } // Indicate that the message treatment is completed. return(MessageResponse.Completed); } catch (AggregateException ex) { foreach (Exception exception in ex.InnerExceptions) { Console.WriteLine(); Console.WriteLine($"Error in sample: {exception}"); } // Indicate that the message treatment is not completed. return(MessageResponse.Abandoned); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine($"Error in sample: {ex}"); // Indicate that the message treatment is not completed. return(MessageResponse.Abandoned); } }
private async Task LedState(bool active) { if (active) { //controller.Write(ledBlue, PinValue.High); //controller.Write(ledRed, PinValue.High); controller.Write(ledGreen, PinValue.High); } else { controller.Write(ledBlue, PinValue.Low); controller.Write(ledRed, PinValue.Low); controller.Write(ledGreen, PinValue.Low); } var ledStatus = new { ledStatus = IsActive }; var message = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(ledStatus); using (var pipeMessage = new Message(message)) { await ioTHubModuleClient.SendEventAsync("output", pipeMessage); Console.WriteLine($"Led actived: {active}"); } }
static async Task <int> Main(string[] args) { try { // // Parse options // Options = new AppOptions(); Options.Parse(args); if (Options.ShowList) { } if (Options.Exit) { return(-1); } if (string.IsNullOrEmpty(Options.FileName)) { throw new ApplicationException("Please use --file to specify which file to use"); } // // Init module client // if (Options.UseEdge) { Log.WriteLine($"{AppOptions.AppName} module starting."); await BlockTimer("Initializing Azure IoT Edge", async() => await InitEdge()); } cts = new CancellationTokenSource(); AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel(); Console.CancelKeyPress += (sender, cpe) => cts.Cancel(); // // Load model // MLModel model = null; Console.WriteLine($"Loading model from: '{Options.ModelPath}', Exists: '{File.Exists(Options.ModelPath)}'"); await BlockTimer($"Loading modelfile '{Options.ModelPath}' on the {(Options.UseGpu ? "GPU" : "CPU")}", async() => { var d = Directory.GetCurrentDirectory(); var path = d + "\\" + Options.ModelPath; StorageFile modelFile = await AsAsync(StorageFile.GetFileFromPathAsync(path)); model = await MLModel.CreateFromStreamAsync(modelFile); }); do { // // Open file // var rows = new List <DataRow>(); try { using (var fs = new StreamReader(Options.FileName)) { // I just need this one line to load the records from the file in my List<CsvLine> rows = new CsvHelper.CsvReader(fs).GetRecords <DataRow>().ToList(); Console.WriteLine($"Loaded {rows.Count} row(s)"); } } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine(rows); // // Main loop // foreach (var row in rows) { // // Evaluate model // var inputShape = new long[2] { 1, 4 }; var inputFeatures = new float[4] { row.Temperature, row.Pressure, row.Humidity, row.ExternalTemperature }; MLModelVariable result = null; var evalticks = await BlockTimer("Running the model", async() => { result = await model.EvaluateAsync(new MLModelVariable() { Variable = TensorFloat.CreateFromArray(inputShape, inputFeatures) }); }); // // Print results // var message = new MessageBody { result = result.Variable.GetAsVectorView().First() }; message.metrics.evaltimeinms = evalticks; var json = JsonConvert.SerializeObject(message); Log.WriteLineRaw($"Recognized {json}"); // // Send results to Edge // if (Options.UseEdge) { var eventMessage = new Message(Encoding.UTF8.GetBytes(json)); await ioTHubModuleClient.SendEventAsync("resultsOutput", eventMessage); // Let's not totally spam Edge :) await Task.Delay(500); } Console.WriteLine("Waiting 1 second..."); Thread.Sleep(1000); } }while (Options.RunForever && !cts.Token.IsCancellationRequested); } catch (Exception ex) { Console.WriteLine(ex); return(-1); } return(0); }
/// <summary> /// Module behavior: /// Sends data periodically (with default frequency of 5 seconds). /// Data trend: /// - Machine Temperature regularly rises from 21C to 100C in regularly with jitter /// - Machine Pressure correlates with Temperature 1 to 10psi /// - Ambient temperature stable around 21C /// - Humidity is stable with tiny jitter around 25% /// Method for resetting the data stream. /// </summary> static async Task SendEvents( ModuleClient moduleClient, int messageCount, SimulatorParameters sim, CancellationTokenSource cts) { int count = 1; double currentTemp = sim.MachineTempMin; double normal = (sim.MachinePressureMax - sim.MachinePressureMin) / (sim.MachineTempMax - sim.MachineTempMin); while (!cts.Token.IsCancellationRequested && (SendUnlimitedMessages(messageCount) || messageCount >= count)) { if (Reset) { currentTemp = sim.MachineTempMin; Reset.Set(false); } if (currentTemp > sim.MachineTempMax) { currentTemp += Rnd.NextDouble() - 0.5; // add value between [-0.5..0.5] } else { currentTemp += -0.25 + (Rnd.NextDouble() * 1.5); // add value between [-0.25..1.25] - average +0.5 } if (sendData) { var tempData = new MessageBody { Machine = new Machine { Temperature = currentTemp, Pressure = sim.MachinePressureMin + ((currentTemp - sim.MachineTempMin) * normal), }, Ambient = new Ambient { Temperature = sim.AmbientTemp + Rnd.NextDouble() - 0.5, Humidity = Rnd.Next(24, 27) }, TimeCreated = DateTime.UtcNow }; string dataBuffer = JsonConvert.SerializeObject(tempData); var eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer)); eventMessage.Properties.Add("sequenceNumber", count.ToString()); eventMessage.Properties.Add("batchId", BatchId.ToString()); Console.WriteLine($"\t{DateTime.Now.ToLocalTime()}> Sending message: {count}, Body: [{dataBuffer}]"); await moduleClient.SendEventAsync("temperatureOutput", eventMessage); count++; } await Task.Delay(messageDelay, cts.Token); } if (messageCount < count) { Console.WriteLine($"Done sending {messageCount} messages"); } }
private async Task UpstreamFromBlob(string container, ModuleClient moduleClient) { Console.WriteLine("***"); Console.WriteLine($"Upstream from Blob: {container}"); int count = 1; CloudStorageAccount storageAccount = null; CloudBlobContainer cloudBlobContainer = null; // Check whether the connection string can be parsed. if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount)) { try { CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); cloudBlobContainer = cloudBlobClient.GetContainerReference(container); if (!(await cloudBlobContainer.ExistsAsync())) { await cloudBlobContainer.CreateIfNotExistsAsync(); } BlobContinuationToken blobContinuationToken = null; do { var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken); // Get the value of the continuation token returned by the listing call. blobContinuationToken = results.ContinuationToken; foreach (IListBlobItem item in results.Results) { if (!shouldUpstream) { break; } if (item.GetType() == typeof(CloudBlockBlob)) { CloudBlockBlob blob = (CloudBlockBlob)item; Console.WriteLine(await blob.DownloadTextAsync()); var body = await blob.DownloadTextAsync(); if (!string.IsNullOrEmpty(body)) { var messageBytes = Encoding.UTF8.GetBytes(body); if (IsLimitsReached(messageBytes)) { shouldUpstream = false; } else { var message = new Message(messageBytes); message.ContentEncoding = "utf-8"; message.ContentType = "application/json"; if (container == anomalyContainer) { message.Properties.Add("IsAnomaly", "True"); } await moduleClient.SendEventAsync("output1", message); Console.WriteLine($"Message sent {count}: {body}"); count++; } } } } } while (blobContinuationToken != null && shouldUpstream); } catch (StorageException ex) { Console.WriteLine($"Error returned from the service: {ex}"); } } }