configuring real time tags as events in Azure IoT Hub

Bashar Sadeq 0 Reputation points
2023-01-30T05:31:44.49+00:00

I am using an IoT device called "eWon Flexy" to push the real time data directly to Azure IoT, which can be retrieved by Cloud BI called "AVEVA InSight".

the hardware is connected to Azure. the AVEVA InSight is connected to Azure. but AVEVA InSight is unable to retrieve messages from Azure.

I opened a case with AVEVA, they said; Message should be in the below format.

{

'TagName': “[[tagname]]',

'EventTime': “[[time in UTC]]',

'Quality': “[[Good/Questionable/Bad]]',

'Value': “[[pv]]'

}

the challenge is: the IoT publisher doesn't have a place to write any scripts, so I suppose I should write the below script in Azure. the questions is : Where shall I write it?


Example: C# code to generate messages
using System;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
using System.Text;
 
namespace EventHubToInsight
{
    class Program
    {
        private const string connectionString = '[YOUR KEY]';
        private const string eventHubName = '[YOUR HUB NAME]';
 
 
        static async Task Main()
        {
            while (true)
            {
                await using (var producerClient = new EventHubProducerClient(connectionString, eventHubName))
                {
                    var rand = new System.Random();
                    var insightMessage = new
                    {
                        TagName = 'Random21',
                        EventTime = DateTime.UtcNow, // Time should always be in UTC
                        Quality = 'Good', // Supported qualities are: Good, Questionable or Bad
                        Value = rand.NextDouble().ToString()
                    }
                    // Create a batch of events
                    using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
                    var msg = Newtonsoft.Json.JsonConvert.SerializeObject(insightMessage);
                    // Add events to the batch. An event is a represented by a collection of bytes and metadata.
                    eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(msg)));
                    await producerClient.SendAsync(eventBatch);
                }
                System.Threading.Thread.Sleep(2000);
            }
        }
    }
}


using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
using System.Text;
namespace EventHubToInsight
{
{
private const string connectionString = '[YOUR KEY]';
private const string eventHubName = '[YOUR HUB NAME]';
static async Task Main()
{
while (true)
{
await using (var producerClient = new EventHubProducerClient(connectionString, eventHubName))
{
var insightEvent = new
{
EventId = Guid.NewGuid(), // own id can be passed here
Quality = 'Good',
EventTime = DateTime.UtcNow, // Time should always be in UTC
MyComment = 'Some description',
MyLocation = 'Some location'
};
// Create a batch of events
using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
var msg = Newtonsoft.Json.JsonConvert.SerializeObject(insightEvent);
var eventData = new EventData(Encoding.UTF8.GetBytes(msg));
eventData.Properties.Add('isEvent', true); // This is required when sending events
eventBatch.TryAdd(eventData);
await producerClient.SendAsync(eventBatch);
}
System.Threading.Thread.Sleep(2000);
}
}
}
}

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,127 questions
{count} votes

1 answer

Sort by: Most helpful
  1. LeelaRajeshSayana-MSFT 13,471 Reputation points
    2023-03-29T14:28:52.0133333+00:00

    Hello Bashar, greetings! Welcome to Microsoft Q&A forum. Thank you for posting the question. We would be glad to assist you on this issue.

    Could you please help us understand your workflow here. You have stated that you are using an IoT device called "eWon Flexy" to push the real time data directly to Azure IoT. The code sample you have provided uses EventHubProducerClient which is used to push data the Event Hub and not IoT Hub. Is there another part of the application that uses DeviceClient and pushes data to the Azure IoT Hub. Ideally, you would want the data to be pushed to IoT Hub and then routed to Event Hub using Message Routing Please let us know if you are trying to use this approach.

    Looking at the information provided by AVEVA, the data propably needs to be in JSON format. If you were using a Device client SDK to send the data to IoT Hub, you would need to include the Encoding type as UTF8 and Content type as application/json before you deliver the message. Please refer the below code to find an example using Device Client

    using System.Text;
    using Microsoft.Azure.Devices.Client;
    using Newtonsoft.Json;
    
    namespace HelloWorld
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                Console.WriteLine("Hello World!");
                string deviceKey1 = "<DeviceKey>";
                string deviceId1 = "<DeviceName>";
                string iotHubHostName = "<HostName>";
                var deviceAuthentication1 = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId1, deviceKey1);          
                DeviceClient deviceClient1 = DeviceClient.Create(iotHubHostName, deviceAuthentication1, TransportType.Mqtt);
                Random Rand = new Random();
    
                var _messageId1 = 1;
                string[] channel = { "Channel", "Function" };
    
                while (true)
                {
                    double currentTemperature = 20 + Rand.NextDouble() * 15;
                    double currentHumidity = 60 + Rand.NextDouble() * 20;
    
                    var telemetryDataPoint1 = new
                    {
                        messageId = _messageId1++,
                        deviceId = deviceId1,
                        source = channel[Rand.Next(0,2)],
                        temperature = currentTemperature,
                        humidity = currentHumidity
                    };
                    string messageString = JsonConvert.SerializeObject(telemetryDataPoint1);
                    Message message = new Message(Encoding.ASCII.GetBytes(messageString));
                    message.ContentEncoding = "utf-8"; 
                    message.ContentType = "application/json";
                    message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false");
    
                    await deviceClient1.SendEventAsync(message);
                    Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
                   
                   
                    await Task.Delay(10000);
                }
                
            }
        }
    }
    
    

    Let us know if the above share information is useful. Please do not hesitate to reach out to us if you have any additional questions on this.

    0 comments No comments