Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
EventHub json serialization
async void Main()
{
var mf = MessagingFactory.CreateFromConnectionString("***");
var eventHubClient = mf.CreateEventHubClient("test");
Random rnd = new Random();
Parallel.For(1, 11, deviceId =>
{
for(int cnt = 0; cnt < 100; cnt++)
{
Console.WriteLine ("Sending event nr {1} for device {0}", cnt, deviceId);
var reading = new TelemetryInfo{ DeviceId = "Device" + deviceId.ToString(), ErrorReading = false, MainValue = 30 * rnd.NextDouble(), Timestamp = DateTime.UtcNow, Type =TelemetryType.Temperature };
EventData msg = new EventData(Encoding.UTF8.GetBytes(reading.ToCsv()));
eventHubClient.Send(msg);
Thread.Sleep(TimeSpan.FromSeconds(2));
}
}
);
}
public class TelemetryInfo
{
public bool ErrorReading { get; set; }
public DateTime Timestamp { get; set; }
public string DeviceId { get; set; }
public TelemetryType Type { get; set; }
public Dictionary<string, object> ExtendedData { get; set; }
public object MainValue { get; set; }
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
public string ToCsv()
{
var telemetryBuilder = new StringBuilder();
telemetryBuilder.AppendLine("DeviceId;MainValue;Timestamp;Type;ErrorReading");
telemetryBuilder.AppendLine(string.Format("{0};{1};{2};{3};{4}", this.DeviceId, this.MainValue, this.Timestamp, this.Type, this.ErrorReading));
return telemetryBuilder.ToString();
}
}
public enum TelemetryType
{
Temperature = 0,
SwitchStatus = 1,
LightStatus = 2,
CurtainStatus = 3,
Weight = 4,
Distance = 5,
Daylight = 6,
WaterLevel = 7
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.