public static async void SendData(Object telemetryDataPoint, string deviceKey) { deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(App.deviceName, deviceKey)); while (true) { var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); await deviceClient.SendEventAsync(message); } }
public static async void SendDeviceToCloudMessagesAsync(string deviceId, object data) { //double avgWindSpeed = 10; // m/s //Random rand = new Random(); while (true) { //double currentWindSpeed = avgWindSpeed + rand.NextDouble() * 4 - 2; var telemetryDataPoint = new { deviceId = deviceId, //windSpeed = currentWindSpeed value = data }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); await deviceClient.SendEventAsync(message); //Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); //Thread.Sleep(1000); } }
private static async void SendDeviceToCloudMessagesAsync() { var weatherDataprovider = await SimulatedWeatherSensorProvider.Create(); for (int i = 0; i < 288; i++) { double currentHumidity = weatherDataprovider.GetHumidity(); double currentTemperature = weatherDataprovider.GetTemperature(); double currentWindSpeed = weatherDataprovider.GetWindSpeed(); var telemetryDataPoint = new { time = DateTime.Now.ToString(), deviceId = deviceId, currentHumidity = currentHumidity, currentTemperature = currentTemperature, currentWindSpeed = currentWindSpeed }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); await deviceClient.SendEventAsync(message); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); await Task.Delay(500); } }
void SendToIoTHubAsBatch(Microsoft.Azure.Devices.Client.Message message) { long currMessageSizeInBytes = message.GetBytes().LongLength; if (bufferedSizeInBytes + currMessageSizeInBytes >= maxBatchSizeInBytes) { FlushIoTHubBuffer(); } sendBuffer.Add(message); bufferedSizeInBytes += currMessageSizeInBytes; }
/* * private static async void SendDeviceToCloudMessagesAsync() * { * double avgWindSpeed = 10; // m/s * Random rand = new Random(); * * while (true) * { * double currentWindSpeed = avgWindSpeed + rand.NextDouble() * 4 - 2; * * var telemetryDataPoint = new * { * windSpeed = currentWindSpeed * }; * var messageString = JsonConvert.SerializeObject(telemetryDataPoint); * var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); * //message.Properties["messageType"] = "interactive"; * //message.MessageId = Guid.NewGuid().ToString(); * * await deviceClient.SendEventAsync(message); * Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); * * Task.Delay(10000).Wait(); * } * } */ private static async void SendDeviceToCloudMessagesAsync(string messageString) { var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); //message.Properties["messageType"] = "interactive"; //message.MessageId = Guid.NewGuid().ToString(); await deviceClient.SendEventAsync(message); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); Task.Delay(10000).Wait(); }
private async void main(IBackgroundTaskInstance taskInstance) { var def = taskInstance.GetDeferral(); Microsoft.Azure.Devices.Client.Message message = await deviceClient.ReceiveAsync(); string name = message.Properties["name"]; screen.SetText(name); def.Complete(); }
private async void SendDeviceToCloudMessagesAsync(string msg) { // Set deviceId to RbHeader JObject jo_message = JsonConvert.DeserializeObject<JObject>(msg); jo_message["RbHeader"]["SourceDeviceId"] = comboBoxDeviceId.Text; jo_message["RbHeader"]["MessageSeqno"] = "1"; jo_message["RbHeader"]["SendDateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); msg = JsonConvert.SerializeObject(jo_message); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(msg)); await deviceClient.SendEventAsync(message); }
private async Task SendDeviceToCloudMessagesAsync(Device device, string deviceId) { string iotHubUri = _connectionstring.Split(';') .First(x => x.StartsWith("HostName=", StringComparison.InvariantCultureIgnoreCase)) .Replace("HostName=", "").Trim(); if (device == null) { ServiceEventSource.Current.ServiceMessage(Context, "Device '{0}' doesn't exist.", deviceId); } var deviceClient = DeviceClient.Create( iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, device.Authentication.SymmetricKey.PrimaryKey)); List <object> events = new List <object>(); for (int i = 0; i < 10; ++i) { var body = new { Timestamp = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(i)) }; events.Add(body); } Microsoft.Azure.Devices.Client.Message message; var serializer = new JsonSerializer(); using (var stream = new MemoryStream()) { using (var streamWriter = new StreamWriter(stream)) { using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter)) { serializer.Serialize(jsonWriter, events); } } message = new Microsoft.Azure.Devices.Client.Message(stream.GetBuffer()); message.Properties.Add("DeviceID", deviceId); message.Properties.Add("Temparature", _temperature == 0 ? "50" : _temperature.ToString()); message.Properties.Add("FanSpeed", "256"); message.Properties.Add("IsOnline", "true"); //message.Properties.Add("GatewayId", "1234"); --> SiteId (RegistrationMessage) await deviceClient.SendEventAsync(message); ServiceEventSource.Current.ServiceMessage(Context, $"Sent message: {Encoding.UTF8.GetString(stream.GetBuffer())}"); } }
private static async void ReceiveC2dAsync() { Console.WriteLine("\nReceiving cloud to device messages from service"); while (true) { Microsoft.Azure.Devices.Client.Message receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage == null) { continue; } string opStr = Encoding.ASCII.GetString(receivedMessage.GetBytes()); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Received message: {0}", opStr); Console.ResetColor(); await deviceClient.CompleteAsync(receivedMessage); if (opStr.StartsWith("GPS")) { SendDeviceToCloudMessagesAsync(devPos); } if (opStr.StartsWith("SET ID")) { int idx = opStr.IndexOf("="); monitorId = opStr.Substring(idx + 1); SendDeviceToCloudMessagesAsync("OK"); } if (opStr.StartsWith("SET URL")) { int idx = opStr.IndexOf("="); monitorUrl = opStr.Substring(idx + 1); SendDeviceToCloudMessagesAsync("OK"); } if (opStr.StartsWith("BUZZ ON")) { BuzzControl(true); SendDeviceToCloudMessagesAsync("OK"); } if (opStr.StartsWith("BUZZ OFF")) { BuzzControl(false); SendDeviceToCloudMessagesAsync("OK"); } } }
Microsoft.Azure.Devices.Client.Message MakeMessage(string devId, int colorVal, int messageCount) { var m = new { DevID = devId, ColorVal = colorVal, MessageCount = messageCount }; var messageString = JsonConvert.SerializeObject(m); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); return(message); }
private static Message GetStateMessage(out string messageString) { // Create JSON message var stateMessage = new { currentObject = _currentObject }; messageString = JsonConvert.SerializeObject(stateMessage); var message = new Message(Encoding.ASCII.GetBytes(messageString)); return(message); }
/// <summary> /// Sends a D2C message containing the deviceId in the message payload /// </summary> /// <param name="dc"></param> /// <param name="index"></param> private void SendMessage(DeviceClient dc, long index) { try { Microsoft.Azure.Devices.Client.Message msg = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(_prefix + index)); dc.SendEventAsync(msg); Console.WriteLine($"Sent message to {_prefix}{index}"); } catch (Exception e) { Console.WriteLine($"SendMessage Error: {e.Message}"); } }
private async void SendDeviceToCloud(WriteLine writeLine) { GetStateMessage(out var messageString); var message = new Message(Encoding.ASCII.GetBytes(messageString)); // Add references to what method this is message.Properties.Add("Method", $"{_currentDevice.Hub.Name}.{_currentDevice.Name}.GetSelectedObject"); // Send the telemetry message await _sDeviceClient.SendEventAsync(message); writeLine($"{DateTime.Now} > Sending message: {messageString}"); }
// Async method to send simulated telemetry private static async Task SendDeviceToCloudMessagesAsync() { ContinueLoop = true; OnDeviceStatusUpdate?.Invoke("IoT Hub Telemetry - Device sending messages."); while (ContinueLoop) { Azure_IoTHub_Sensors.TelemetryDataPoint telemetryDataPoint; if (Azure_IoTHub_Sensors.Weather.CurrentWeather.DoAsync) { telemetryDataPoint = await Azure_IoTHub_Sensors.Weather.CurrentWeather.GetWeatherAsync(); } else { telemetryDataPoint = Azure_IoTHub_Sensors.Weather.CurrentWeather.GetWeather(); } MessageString = JsonConvert.SerializeObject(telemetryDataPoint); Message = new Message(Encoding.ASCII.GetBytes(MessageString)); //Message.UserId = Azure_IoTHub_Connections.MyConnections.IoTHubName; Message.Properties.Add("temperatureAlert", (telemetryDataPoint.temperature > 30) ? "true" : "false"); Message.Properties.Add("humidityAlert", (telemetryDataPoint.humidity > 80) ? "true" : "false"); Message.Properties.Add("pressureAlert", (telemetryDataPoint.pressure > 1010) ? "true" : "false"); Azure_IoTHub_Telemetry.SyntheticIoTMessage iotmessage = new Azure_IoTHub_Telemetry.SyntheticIoTMessage(Message); MessageString = iotmessage.Serialise(); System.Diagnostics.Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, MessageString); SetDeviceSentMsg?.Invoke(string.Format("{0} > Sending message: {1}", DateTime.Now, MessageString)); // Send the telemetry message if (!IsDeviceStreaming) { await s_deviceClient.SendEventAsync(Message); Delay = 1000 * Azure_IoTHub_Connections.MyConnections.TelemetryDelayBtwReadings; await Task.Delay(Delay); if (!ContinueLoop) { OnDeviceStatusUpdate?.Invoke("Cancelled Telemetry - Device end"); } } else { ContinueLoop = false; } } }
private static async Task SendDeviceToCloudMessagesAsync(string deviceId, string tenant) { string iotHubUri = connectionString.Split(';') .First(x => x.StartsWith("HostName=", StringComparison.InvariantCultureIgnoreCase)) .Replace("HostName=", "").Trim(); Device device = devices.FirstOrDefault(x => x.Id == deviceId); if (device == null) { Console.WriteLine("Device '{0}' doesn't exist.", deviceId); } DeviceClient deviceClient = DeviceClient.Create( iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, device.Authentication.SymmetricKey.PrimaryKey)); List <object> events = new List <object>(); for (int i = 0; i < 10; ++i) { var body = new { Timestamp = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(i)) }; events.Add(body); } Microsoft.Azure.Devices.Client.Message message; JsonSerializer serializer = new JsonSerializer(); using (MemoryStream stream = new MemoryStream()) { using (StreamWriter streamWriter = new StreamWriter(stream)) { using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter)) { serializer.Serialize(jsonWriter, events); } } message = new Microsoft.Azure.Devices.Client.Message(stream.GetBuffer()); message.Properties.Add("Insight Application UID", tenant); message.Properties.Add("Device ID", deviceId); await deviceClient.SendEventAsync(message); Console.WriteLine($"Sent message: {Encoding.UTF8.GetString(stream.GetBuffer())}"); } }
/// <summary> /// Sends a device to cloud message /// </summary> private static void SendD2CMessage() { var d2CMessage = new D2CMessage { Humidity = "Low", Temprature = 12.5F }; var payload = JsonConvert.SerializeObject(d2CMessage); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(payload)); _iotDevice.SendEventAsync(message).Wait(); }
// Sending thread - sends D2C messages to IoT Hub private static async Task SendD2CMessageAsync(Device device, string text) { try { DeviceClient client = CreateDeviceClient(_appSettings.IoTHubUrl, device.Id, device.Authentication.SymmetricKey.SecondaryKey); var msg = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(text)); msg.Properties.Add("ClientTime", DateTime.UtcNow.ToString()); Logger.Info($"[{device.Id}]Sending {text}..."); await client.SendEventAsync(msg); } catch (Exception exp) { Logger.Error($"[{device.Id}]Exception while calling SendD2CMessageAsync():[{exp.Message}]"); } }
public async Task SendEventAsync <T>(T item, string messageType) { var json = JsonConvert.SerializeObject(item); var bytes = Encoding.UTF8.GetBytes(json); var message = new Message(bytes); message.Properties.Add("messageType", messageType); message.Properties.Add("correlationId", Guid.NewGuid().ToString()); message.Properties.Add("parentCorrelationId", Guid.NewGuid().ToString()); message.Properties.Add("createdDateTime", DateTime.UtcNow.ToString("u", DateTimeFormatInfo.InvariantInfo)); message.Properties.Add("deviceId", deviceName); await deviceClient.SendEventAsync(message); }
async Task Send(DeviceClient client, SensorRefViewModel viewModel, float value) { var bytes = Encoding.UTF8.GetBytes($"{value}"); var eventMessage = new Microsoft.Azure.Devices.Client.Message(bytes); eventMessage.Properties.Add("DigitalTwins-Telemetry", "1.0"); eventMessage.Properties.Add("DigitalTwins-SensorHardwareId", $"{viewModel.HardwareId}"); eventMessage.Properties.Add("CreationTimeUtc", DateTime.UtcNow.ToString("o", System.Threading.Thread.CurrentThread.CurrentCulture)); eventMessage.Properties.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); eventMessage.Properties.Add($"x-type", viewModel.Name); eventMessage.Properties.Add($"x-value", $"{value}"); await client.SendEventAsync(eventMessage); }
void TransmitEvent(string datapoint) { Microsoft.Azure.Devices.Client.Message message; try { message = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(datapoint)); _deviceClient.SendEventAsync(message); } catch (Exception ex) { System.Diagnostics.Trace.TraceError(ex.Message); } }
[HttpGet] public async Task <ActionResult> SendMessage(string id, string key, int value) { var telemetryDataPoint = new { deviceId = id, telemetry = value }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Message(Encoding.ASCII.GetBytes(messageString)); var deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(id, key)); await deviceClient.SendEventAsync(message); Response.StatusCode = 200; // OK = 200 return(null); }
private async Task SendWorker(CancellationToken cancellationToken) { INetworkPacket networkPacket = null; while (!cancellationToken.IsCancellationRequested) { try { if (!_queue.TryDequeue(out networkPacket)) { //await Task.Delay(100); continue; } var correlationId = Guid.NewGuid(); switch (networkPacket) { case PushDataPacket pushDataPacket: { var data = _payloadSerializer.Serialize(pushDataPacket.Payload); var message = new Microsoft.Azure.Devices.Client.Message(data); message.CorrelationId = correlationId.ToString(); message.Properties["EventId"] = correlationId.ToString(); message.Properties["CorrelationId"] = correlationId.ToString(); message.Properties["DeviceId"] = pushDataPacket.Eui; message.Properties["ProtocolName"] = "Lora Packet Forwarder"; message.Properties["ProtocolVersion"] = pushDataPacket.ProtocolVersion.ToString(); message.Properties["MessageType"] = pushDataPacket.MessageType.ToString(); message.CreationTimeUtc = DateTime.UtcNow; _logger.Info($"Sending PushDataPacket to IoT Hub by deviceid '{_deviceId}'", GetType().Name); await _device.Send(message); } break; } } catch (BrokenCircuitException ex) { _logger.Error($"Circuit breaker open -> An error occured while sending a message to IoT Hub by deviceid '{_deviceId}'. Discarding message", GetType().Name, ex); } catch (Exception ex) { _logger.Error($"An error occured while sending a message to IoT Hub by deviceid '{_deviceId}'", GetType().Name, ex); } } }
public async Task <int> SendStringToHub(string str) { try { var message = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(str)); await deviceClient.SendEventAsync(message); return(1); } catch (Exception ex) { return(0); } }
private async void M_t_Tick(object sender, EventArgs e) { Microsoft.Azure.Devices.Client.Message message = createMessage(); //Add properties for routing if (rnd.NextDouble() > 0.8) { message.Properties.Add("direction", "eventhub"); } if (rnd.NextDouble() > 0.9) { message.Properties.Add("status", "error"); } await m_dc.SendEventAsync(message); }
private async void cmd05SendTelemetryAlert_Click(object sender, RoutedEventArgs e) { if (m_t == null || m_dc == null) { return; } Microsoft.Azure.Devices.Client.Message message = createMessage(); //Add properties for routing message.Properties.Add("alert", "1"); await m_dc.SendEventAsync(message); Debug.WriteLine("ALERT"); }
static async Task ProcessMessagesAsync(Message message, CancellationToken token) { try{ string msgBody = Encoding.UTF8.GetString(message.Body); if (string.IsNullOrEmpty(msgBody)) { throw new ArgumentNullException("Message body is null or empty"); } // Check if this is a schedule notification string timestamp = DateTime.Now.ToString("dd/MM/yy hh:mm:ss"); if (ScheduleUpdateEventSchema.IsValid(msgBody)) { ScheduleData eventData = JsonConvert.DeserializeObject <ScheduleData>(msgBody); // Remove expired events eventData.Schedule = ServiceBusClient.FilterAppointments(eventData); msgBody = JsonConvert.SerializeObject(eventData); byte[] messageBytes = Encoding.UTF8.GetBytes(msgBody); IoT.Message pipeMessage = new IoT.Message(messageBytes); await ioTHubModuleClient.SendEventAsync("ScheduleOutput", pipeMessage); Console.WriteLine($"{timestamp} sucessfully handling ScheduleOutput message as {msgBody}"); // Check if this is sensort notification } else if (NotificationEventSchema.IsValid(msgBody)) { //TODO: process events from sensors //await ioTHubModuleClient.SendEventAsync("SensorsOutput", pipeMessage); Console.WriteLine($"{timestamp} sucessfully handling SensorsOutput message {msgBody}"); } else { // Process the message Console.WriteLine($"Unknown message format: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{msgBody}"); throw new ArgumentException("Unknown message format"); } }catch (Exception ex) { Console.WriteLine($"Error processing message: {ex.Message} {ex.StackTrace}"); }finally{ // Complete the message so that it is not received again. // This can be done only if the subscriptionClient is opened in ReceiveMode.PeekLock mode (which is default). await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); } }
private async Task ReadAsync() { var mfrc = new Mfrc522(); await mfrc.InitIOAsync(); await ResetAsync(); while (true) { try { if (mfrc.IsTagPresent()) { Uid uid = mfrc.ReadUid(); if (uid.IsValid) { await CheckingAsync(uid); DataBadge badge = new DataBadge { Orario = DateTime.Now, Id = uid.FullUid, Posizione = "Villafranca" }; _pinBlueLed.SetDriveMode(GpioPinDriveMode.Output); _pinBlueLed.Write(GpioPinValue.High); var messageString = JsonConvert.SerializeObject(badge); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); message.Properties.Add("DeviceId", DeviceId); await _client.SendEventAsync(message); } else { await ErrorReadAsync(); } mfrc.HaltTag(); } } catch (Exception ex) { await _client.CloseAsync(); var e = ex; } } }
/// <summary> /// This method is called whenever the module is sent a message from the EdgeHub. /// It just pipe the messages without any change. /// It prints all the incoming messages. /// </summary> static async Task <MessageResponse> PipeMessage(Message message, object userContext) { try { int counterValue = Interlocked.Increment(ref counter); var moduleClient = userContext as ModuleClient; if (moduleClient == null) { throw new InvalidOperationException("UserContext doesn't contain " + "expected values"); } byte[] messageBytes = message.GetBytes(); string messageString = Encoding.UTF8.GetString(messageBytes); Console.WriteLine($"Received message: {counterValue}, Body: [{messageString}]"); var libraryModule = "LibraryModule"; var deviceId = System.Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID"); // var resultFromServiceClient = await CallModuleUsingServiceClient(deviceId, libraryModule); var resultFromModuleClient = await CallModuleUsingModuleClient(deviceId, libraryModule, moduleClient); var resultFromWebApi = await CallWebApiModule(); Console.WriteLine($"API result: {resultFromWebApi}"); if (!string.IsNullOrEmpty(messageString)) { var pipeMessage = new Microsoft.Azure.Devices.Client.Message(messageBytes); foreach (var prop in message.Properties) { pipeMessage.Properties.Add(prop.Key, prop.Value); } // pipeMessage.Properties.Add("resultFromServiceClient", resultFromServiceClient); pipeMessage.Properties.Add("resultFromModuleClient", resultFromModuleClient); await moduleClient.SendEventAsync("output1", pipeMessage); Console.WriteLine("Received message sent"); } return(MessageResponse.Completed); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(MessageResponse.None); } }
private async void SendDeviceToCloudMessagesAsync(Bmp180SensorData sensorData) { var messageString = JsonConvert.SerializeObject(new WeatherDTO { // bestAccuracyLocationName dateTime = LastUpdated, temperature = sensorData.Temperature, pressure = sensorData.Pressure, altitude = sensorData.Altitude, latitude = LocationManager.currentlocation.Position.Latitude, longitude = LocationManager.currentlocation.Position.Longitude, }); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); await deviceClient.SendEventAsync(message); }
public async Task PurgeIoTHubMessagesAsync(DeviceClient deviceClient) { while (true) { Microsoft.Azure.Devices.Client.Message receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); if (receivedMessage == null) { // all messages purged break; } // purge message await deviceClient.CompleteAsync(receivedMessage).ConfigureAwait(false); } }
public void SendMessageToAzureIoTHub(string message) { if (myDev != null) { try { var EventMessage = new Microsoft.Azure.Devices.Client.Message(System.Text.Encoding.UTF8.GetBytes(message)); myDev.SendEventAsync(EventMessage); // send message } catch (Exception ex) { Debug.WriteLine("Error:/n" + ex.Message); } } }
public async Task Send(Microsoft.Azure.Devices.Client.Message message) { await _retryPolicy.ExecuteAsync(async() => { await _circuitBreakerPolicy.ExecuteAsync(async() => { if (_deviceClient == null) { throw new DeviceNotInitiatedException(_deviceId); } await _deviceClient.SendEventAsync(message); }); }); }
public override void Run() { Trace.Write("starting"); var deviceKey = GetOrAddDeviceAsync().Result; string deviceConnectionString = String.Format("{0};DeviceId={1};DeviceKey={2}", Properties.Settings.Default.IotHubConnectionString, Properties.Settings.Default.TestDeviceName, deviceKey); var client = DeviceClient.CreateFromConnectionString(deviceConnectionString); var TwoMonthsAgo = DateTime.Now.AddMonths(-2); var r = new Random(); foreach (var td in this.GetTestTraps()) { var m = new EventModel { TrapId = Guid.Parse(td.TrapId), Location = td.Location, Building = td.Building }; var current = new DateTime(TwoMonthsAgo.Year, TwoMonthsAgo.Month, 1); var switched = false; while (current < DateTime.UtcNow) { m.Time = current; m.Type = (byte)(switched ? 2 : 1); var msg = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(m))); client.SendEventAsync(msg).Wait(); switched = !switched; var samplePeriod = r.Next(45, 2880); current = current.AddMinutes(samplePeriod); } } Trace.Write("Completed"); }
private static async Task SendDeviceToCloudMessagesAsync(string deviceId, string tenant) { string iotHubUri = connectionString.Split(';') .First(x => x.StartsWith("HostName=", StringComparison.InvariantCultureIgnoreCase)) .Replace("HostName=", "").Trim(); Device device = devices.FirstOrDefault(x => x.Id == deviceId); if (device == null) { Console.WriteLine("Device '{0}' doesn't exist.", deviceId); } DeviceClient deviceClient = DeviceClient.Create( iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, device.Authentication.SymmetricKey.PrimaryKey)); List<object> events = new List<object>(); for (int i = 0; i < 10; ++i) { var body = new { Timestamp = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(i)) }; events.Add(body); } Microsoft.Azure.Devices.Client.Message message; JsonSerializer serializer = new JsonSerializer(); using (MemoryStream stream = new MemoryStream()) { using (StreamWriter streamWriter = new StreamWriter(stream)) { using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter)) { serializer.Serialize(jsonWriter, events); } } message = new Microsoft.Azure.Devices.Client.Message(stream.GetBuffer()); message.Properties.Add("TenantID", tenant); message.Properties.Add("DeviceID", deviceId); await deviceClient.SendEventAsync(message); Console.WriteLine($"Sent message: {Encoding.UTF8.GetString(stream.GetBuffer())}"); } }
/// <summary> /// Sends an event to IoT Hub using the provided eventId GUID /// </summary> /// <param name="device"></param> /// <param name="eventId"></param> /// <param name="eventData"></param> /// <returns></returns> public async Task SendEventAsync(Guid eventId, dynamic eventData) { try { byte[] bytes; string objectType = EventSchemaHelper.GetObjectType(eventData); var objectTypePrefix = _configurationProvider.GetConfigurationSettingValue("ObjectTypePrefix"); if (!string.IsNullOrWhiteSpace(objectType) && !string.IsNullOrEmpty(objectTypePrefix)) { eventData.ObjectType = objectTypePrefix + objectType; } // sample code to trace the raw JSON that is being sent //string rawJson = JsonConvert.SerializeObject(eventData); //Trace.TraceInformation(rawJson); bytes = _serializer.SerializeObject(eventData); var message = new Microsoft.Azure.Devices.Client.Message(bytes); message.Properties["EventId"] = eventId.ToString(); await AzureRetryHelper.OperationWithBasicRetryAsync(async () => { try { await _deviceClient.SendEventAsync(message); } catch (Exception ex) { _logger.LogError( "{0}{0}*** Exception: SendEventAsync ***{0}{0}EventId: {1}{0}Event Data: {2}{0}Exception: {3}{0}{0}", "\n",//Console.Out.NewLine, eventId, eventData, ex); } }); } catch (Exception ex) { _logger.LogError("{0}{0}*** Exception: Serialization error ***{0}{0}EventId: {1}{0}Event Data: {2}{0}Exception: {3}{0}{0}", "\n",//Console.Out.NewLine, eventId, eventData, ex); } }
// Create a message and send it to IoT Hub. static async Task SendEvent(DeviceClient deviceClient, Car CurrentCar, VehicleTireReading TireData) { try { string jsonData = JsonConvert.SerializeObject(TireData); Microsoft.Azure.Devices.Client.Message eventMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(jsonData)); eventMessage.Properties.Add("messagetype", "TLM"); await deviceClient.SendEventAsync(eventMessage); Console.WriteLine("Sent Data for Vehicle={0};ReadingId={1}", CurrentCar.Id, TireData.ReadingId); } catch (Exception ex) { Console.WriteLine("An error occured writing to event hub" + ex.ToString()); } }