private void sendMessage() { while (true) { if (ctsForStart.IsCancellationRequested) { return; } if (sensorController.lockState) { continue; } sensorController.lockState = true; GroveMessage groveMessage = sensorController.GetSensorValue(); sensorController.lockState = false; groveMessage.DeviceId = deviceId; var messageSerialized = JsonConvert.SerializeObject(groveMessage); var encodedMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageSerialized)); try { iotClient.SendDeviceToCloudMessagesAsync(encodedMessage).Wait(); } catch (Exception e) { Debug.WriteLine(e.Message); } SendMessageLoger(messageSerialized); Task.Delay(sendMessageDelay).Wait(); } }
public async Task CleanupC2DDeviceQueueAsync(string deviceId) { try { using (var client = Microsoft.Azure.Devices.Client.DeviceClient.CreateFromConnectionString(Configuration.IoTHubConnectionString + $";DeviceId={deviceId}", Microsoft.Azure.Devices.Client.TransportType.Amqp)) { Microsoft.Azure.Devices.Client.Message msg = null; Console.WriteLine($"Cleaning up messages for device {deviceId}"); do { msg = await client.ReceiveAsync(TimeSpan.FromSeconds(10)); if (msg != null) { Console.WriteLine($"Found message to cleanup for device {deviceId}"); await client.CompleteAsync(msg); } }while (msg != null); } Console.WriteLine($"Finished cleaning up messages for device {deviceId}"); } catch (Exception ex) { Console.WriteLine($"Problem while cleaning up messages for device {deviceId}"); Console.WriteLine(ex.ToString()); } }
private async void buttonSendConfirmation_Click(object sender, RoutedEventArgs e) { await testDevice.ComfirmReceivedMessageAsync(currentReceivedMessage); currentReceivedMessage = null; buttonSendConfirmation.IsEnabled = false; SetActionStatistics("SendC2DConfirmation:Device", 0); }
private void SendButtonEvent() { bool lastButtonState = false; while (true) { if (ctsForStart.IsCancellationRequested) { break; } Task.Delay(1).Wait(); if (sensorController.lockState) { continue; } sensorController.lockState = true; bool buttonState = false; try { buttonState = sensorController.GetButtonValue(); } catch (Exception e) { Debug.WriteLine(e.Message); } sensorController.lockState = false; if (buttonState != lastButtonState) { if (buttonState) { ButtonEvent buttonEvent = new ButtonEvent(); buttonEvent.Click = true; buttonEvent.DeviceId = deviceId; buttonEvent.Timestamp = DateTime.Now.ToString(); var messageSerialized = JsonConvert.SerializeObject(buttonEvent); var encodedMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageSerialized)); try { iotClient.SendDeviceToCloudMessagesAsync(encodedMessage).Wait(); } catch (Exception e) { Debug.WriteLine(e.Message); } SendMessageLoger(messageSerialized); } else { // on to off } Task.Delay(50).Wait(); } lastButtonState = buttonState; } }
private static string OnDeviceRecvTextIO(string msgIn, out Microsoft.Azure.Devices.Client.Message message) { message = null; //Perform device side processing here. Eg read sensors. string msgOut = msgIn; switch (DeviceAction) { case 0: msgOut = msgIn; break; case 1: msgOut = msgIn.ToUpper(); break; case 2: switch (msgIn.Substring(0, 3).ToLower()) { case "tem": msgOut = "45 C"; break; case "pre": msgOut = "1034.0 hPa"; break; case "hum": msgOut = "67%"; break; default: msgOut = "Invalid request"; break; } break; case 3: Azure_IoTHub_Telemetry.SimulatedDevice.Configure(Azure_IoTHub_Connections.MyConnections.DeviceConnectionString, true, Azure_IoTHub_DeviceStreaming.DeviceStreamingCommon.device_transportType, false); msgOut = Azure_IoTHub_DeviceStreaming.DeviceStreamingCommon.DeviceInSimuatedDeviceModeStrn + Azure_IoTHub_Telemetry.SimulatedDevice.Run().GetAwaiter().GetResult(); message = SimulatedDevice.Message; break; case 4: msgOut = "Coming. Not yet implemented. This is a pace holder for now."; break; } Console.WriteLine(msgIn); Console.WriteLine(msgOut); System.Diagnostics.Debug.WriteLine(msgIn); System.Diagnostics.Debug.WriteLine(msgOut); return(msgOut); }
private string OnDeviceRecvTextIO(string msgIn, out Microsoft.Azure.Devices.Client.Message message) { DeviceAction = AzureConnections.MyConnections.DeviceAction; message = null; //Perform device side processing here. Eg read sensors. string msgOut = msgIn; switch (DeviceAction) { case 0: msgOut = msgIn; break; case 1: msgOut = msgIn.ToUpper(); break; case 2: switch (msgIn.Substring(0, 3).ToLower()) { case "tem": msgOut = "45 C"; break; case "pre": msgOut = "1034.0 hPa"; break; case "hum": msgOut = "67%"; break; default: msgOut = "Invalid request"; break; } break; case 3: SimulatedDevice_ns.SimulatedDevice.Configure(AzureConnections.MyConnections.DeviceConnectionString, true, AzIoTHubDeviceStreams.DeviceStreamingCommon.device_transportType, false); msgOut = AzIoTHubDeviceStreams.DeviceStreamingCommon.DeiceInSimuatedDeviceModeStrn + SimulatedDevice_ns.SimulatedDevice.Run().GetAwaiter().GetResult(); message = SimulatedDevice.Message; break; case 4: msgOut = AzSensors.Sensors.ProcessMsgRecvdByDevice(msgIn); break; } System.Diagnostics.Debug.WriteLine(msgIn); System.Diagnostics.Debug.WriteLine(msgOut); return(msgOut); }
private async Task PushMessagesAsync( IImmutableList <Gateway> gateways, TelemetryClient telemetryClient, CancellationToken cancellationToken) { var devices = (from g in gateways from d in g.Devices select new { Gateway = g, Device = d }).ToArray(); while (!cancellationToken.IsCancellationRequested) { var deviceComposite = devices[NextDeviceIndex()]; var payload = CreateMessagePayload( deviceComposite.Gateway.Name, deviceComposite.Device.Name); using (var message = new Microsoft.Azure.Devices.Client.Message(payload) { ContentEncoding = "utf-8", ContentType = "application/json" }) { var timeoutSource = new CancellationTokenSource(_messageTimeout); var combinedSource = CancellationTokenSource.CreateLinkedTokenSource( cancellationToken, timeoutSource.Token); try { await deviceComposite.Device.Client.SendEventAsync( message, combinedSource.Token); Interlocked.Increment(ref _messageCount); } catch (Exception ex) { telemetryClient.TrackException(ex); Interlocked.Increment(ref _errorCount); } } } }
public void SendMessageToCloud(string messageString) { var eventJsonBytes = Encoding.UTF8.GetBytes(messageString); var clientMessage = new Microsoft.Azure.Devices.Client.Message(eventJsonBytes) { ContentEncoding = "utf-8", ContentType = "application/json" }; // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. var messageProperties = clientMessage.Properties; messageProperties.Add("deviceId", this.deviceId); // Send the telemetry message this._DeviceClient.SendMessageAsync(messageString).Wait(); }
public DeserializableCommand(Microsoft.Azure.Devices.Client.Message message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } Debug.Assert( !string.IsNullOrEmpty(message.LockToken), "message.LockToken is a null reference or empty string."); _lockToken = message.LockToken; byte[] messageBytes = message.GetBytes(); // this needs to be saved if needed later, because it can only be read once from the original Message string jsonData = Encoding.UTF8.GetString(messageBytes); _commandHistory = JsonConvert.DeserializeObject <CommandHistory>(jsonData); }
private async Task receiveMessageAsync(String iotHubUri, String iotHubConnectString) { while (true) { if (ctsForStart.IsCancellationRequested) { return; } Microsoft.Azure.Devices.Client.Message message = await iotClient.ReceiveC2dAsync(); if (message == null) { continue; } Debug.WriteLine("Received message: " + Encoding.ASCII.GetString(message.GetBytes())); } }
public static async Task StoreMessageAsync([EdgeHubTrigger("input1")] DeviceMessage input, ILogger logger) { var inputMessage = Encoding.UTF8.GetString(input.GetBytes()); if (string.IsNullOrEmpty(inputMessage)) { logger.LogInformation("Received empty message!"); return; } logger.LogInformation($"Received message: {inputMessage}"); var message = ParseMessage(inputMessage); var messageData = ParseData(message.Data); var measurementData = new List <string>(); foreach (var measurement in messageData.Contents) { foreach (var data in measurement.Data) { foreach (var value in data.Values) { measurementData.Add($"('{message.Id}','{message.Source}','{message.Type}','{message.SpecVersion}','{message.DataContentType}','{measurement.HwId}','{value.Address}','{value.Value}','{data.SourceTimestamp}')"); } } } var insertStatement = $"INSERT INTO dbo.PowerMeasurements VALUES {String.Join(",", measurementData)};"; using (var connection = new SqlConnection(DatabaseConnection)) { connection.Open(); using (var cmd = new SqlCommand(insertStatement, connection)) { var rows = await cmd.ExecuteNonQueryAsync(); logger.LogInformation($"{rows} rows were updated"); } } }
public DeserializableCommand(Microsoft.Azure.Devices.Client.Message message, JsonSerialize serializer) { if (message == null) { throw new ArgumentNullException("message"); } if (serializer == null) { throw new ArgumentNullException("serializer"); } Debug.Assert( !string.IsNullOrEmpty(message.LockToken), "message.LockToken is a null reference or empty string."); _lockToken = message.LockToken; byte[] messageBytes = message.GetBytes(); // this needs to be saved if needed later, because it can only be read once from the original Message _command = serializer.DeserializeObject <dynamic>(messageBytes); }
private string OnDeviceRecvTextIO(string msgIn, out Microsoft.Azure.Devices.Client.Message message) { string res = AzSensors.Weather.GetWeather().GetAwaiter().GetResult(); message = null; //Perform device side processing here. Eg read sensors. string msgOut = msgIn; switch (DeviceAction) { case 0: msgOut = msgIn; break; case 1: msgOut = msgIn.ToUpper(); break; case 2: string[] msg = msgIn.Split(new char[] { '-', ' ' }); if ((msg.Length > 1) || (msg[0].ToLower() == "help")) { switch (msg[0].ToLower().Substring(0, 3)) { case "set": msgOut = "Invalid request. Try Help"; if (msg.Length > 2) { int val; bool bval; if (int.TryParse(msg[2], out val)) { switch (msg[1].Substring(0, 3).ToLower()) { case "sta": state = val; msgOut = "setVal: OK"; break; case "tog": toggle = val > 0 ? true : false; msgOut = "setVal: OK"; break; default: msgOut = "Invalid request. Try Help"; break; } } else if (bool.TryParse(msg[2], out bval)) { switch (msg[1].Substring(0, 3).ToLower()) { case "tog": toggle = bval; msgOut = "setbVal: OK"; break; } } } break; case "get": switch (msg[1].ToLower().Substring(0, 3)) { case "tem": msgOut = "45 C"; break; case "pre": msgOut = "1034.0 hPa"; break; case "hum": msgOut = "67%"; break; case "sta": msgOut = string.Format("state = {0}", state); break; case "tog": msgOut = string.Format("toggle = {0}", toggle); break; default: msgOut = "Invalid request. Try Help"; break; } break; case "hel": msgOut = "Only first three characters of each word required.\r\nget: temperature,pressure,humidity,state,toggle,help\r\nset :state <int value>,toggle <0|1> (true|false)"; break; default: msgOut = "Invalid request. Try Help"; break; } } break; case 21: //Old 2 case switch (msgIn.Substring(0, 3).ToLower()) { case "tem": msgOut = "45 C"; break; case "pre": msgOut = "1034.0 hPa"; break; case "hum": msgOut = "67%"; break; default: msgOut = "Invalid request"; break; } break; case 3: msgOut = AzIoTHubDeviceStreams.DeviceStreamingCommon.DeiceInSimuatedDeviceModeStrn + SimulatedDevice_ns.SimulatedDevice.Run().GetAwaiter().GetResult(); message = SimulatedDevice_ns.SimulatedDevice.Message; break; case 4: msgOut = "Not implemented for desktop.\r\nTry with Win 10 IoT-Core (eg RPI) running UWP_BGAppAzDeviceStream_Device, as in GitHub Repository:\r\nhttps://github.com/djaus2/AziothubDeviceStreaming"; break; } Task.Run(async() => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { tbDeviceMsgIn.Text = msgIn; tbDeviceMsgOut.Text = msgOut; }); }); return(msgOut); }
private string OnDeviceRecvTextIO(string msgIn, out Microsoft.Azure.Devices.Client.Message message) { message = null; //Perform device side processing here. Eg read sensors. string msgOut = msgIn; switch (DeviceAction) { case 0: msgOut = msgIn; break; case 1: msgOut = msgIn.ToUpper(); break; case 2: string[] msg = msgIn.Split(new char[] { '-', ' ' }); if ((msg.Length > 1) || (msg[0].ToLower() == "help")) { switch (msg[0].ToLower().Substring(0, 3)) { case "set": msgOut = "Invalid request. Try Help"; if (msg.Length > 2) { if (int.TryParse(msg[2], out int val)) { switch (msg[1].Substring(0, 3).ToLower()) { case "sta": state = val; msgOut = "setVal: OK"; break; case "tog": toggle = val > 0 ? true : false; msgOut = "setVal: OK"; break; default: msgOut = "Invalid request. Try Help"; break; } } else if (bool.TryParse(msg[2], out bool bval)) { switch (msg[1].Substring(0, 3).ToLower()) { case "tog": toggle = bval; msgOut = "setbVal: OK"; break; } } } break; case "get": switch (msg[1].ToLower().Substring(0, 3)) { case "tem": msgOut = "45 C"; break; case "pre": msgOut = "1034.0 hPa"; break; case "hum": msgOut = "67%"; break; case "sta": msgOut = string.Format("state = {0}", state); break; case "tog": msgOut = string.Format("toggle = {0}", toggle); break; default: msgOut = "Invalid request. Try Help"; break; } break; case "hel": msgOut = "Only first three characters of each word required.\r\nget: temperature,pressure,humidity,state,toggle,help\r\nset :state <int value>,toggle <0|1> (true|false)"; break; default: msgOut = "Invalid request. Try Help"; break; } } else { msgOut = "try " + msgIn + " help"; } break; case 21: //Old 2 case switch (msgIn.Substring(0, 3).ToLower()) { case "tem": msgOut = "45 C"; break; case "pre": msgOut = "1034.0 hPa"; break; case "hum": msgOut = "67%"; break; default: msgOut = "Invalid request"; break; } break; case 3: msg = msgIn.Split(new char[] { '-', ' ' }); if (((msg.Length > 1) && (msg[0].ToLower() == "get")) || (msg.Length > 0)) { switch (msg[0].ToLower().Substring(0, 3)) { case "set": if (int.TryParse(msg[1], out int index)) { msgOut = "OK"; switch (index) { case 0: Azure_IoTHub_Sensors.Weather.CurrentWeather = null; msgOut = "Cleared"; break; case 1: Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_Fixed(); break; case 2: Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_Random(); break; case 3: Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_FromCities(); break; case 4: Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_FromHardware(); break; default: Azure_IoTHub_Sensors.Weather.CurrentWeather = null; msgOut = "Invalid option. Cleared."; break; } } break; case "get": msgOut = Azure_IoTHub_Sensors.TelemetryDataPoint.Prefix + Azure_IoTHub_Sensors.Weather.CurrentWeather?.ToString(); break; default: msgOut = "Help\r\nset 0|1|2|3|4 Choose the weather class.\r\n0=clear,1=Fixed values,2=random values,\r\n3=Rotating from cities,4=From Arduino device\r\nget Get the weather from the weather class chosen"; break; } } else { msgOut = "try " + msgIn + " help"; } //message = Azure_IoTHub_Telemetry.SimulatedDevice.Message; break; case 4: msgOut = "Not implemented for desktop.\r\nTry with Win 10 IoT-Core (eg RPI) running UWP_BGAppAzDeviceStream_Device, as in GitHub Repository:\r\nhttps://github.com/djaus2/AziothubDeviceStreaming"; break; } Task.Run(async() => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { tbDeviceMsgOut.Text = msgOut; }); }); return(msgOut); }
private static string OnDeviceRecvTextIO(string msgIn, out Microsoft.Azure.Devices.Client.Message message) { message = null; //Perform device side processing here. Eg read sensors. string msgOut = msgIn; switch (Settings._Settings.DeviceAction) { case 0: msgOut = msgIn; break; case 1: msgOut = msgIn.ToUpper(); break; case 2: switch (msgIn.Substring(0, 3).ToLower()) { case "tem": msgOut = "45 C"; break; case "pre": msgOut = "1034.0 hPa"; break; case "hum": msgOut = "67%"; break; default: msgOut = "Invalid request"; break; } break; case 3: //Azure_IoTHub_Telemetry.SimulatedDevice.Configure( // Azure_IoTHub_Connections.MyConnections.DeviceConnectionString, true, // Azure_IoTHub_DeviceStreaming.DeviceStreamingCommon.device_transportType, false); //msgOut = Azure_IoTHub_DeviceStreaming.DeviceStreamingCommon.DeviceInSimuatedDeviceModeStrn + Azure_IoTHub_Telemetry.SimulatedDevice.Run().GetAwaiter().GetResult(); //message = SimulatedDevice.Message; string [] msg = msgIn.Split(new char[] { '-', ' ' }); if (((msg.Length > 1) && (msg[0].ToLower() == "get")) || (msg.Length > 0)) { switch (msg[0].ToLower().Substring(0, 3)) { case "set": if (int.TryParse(msg[1], out int index)) { msgOut = "OK"; switch (index) { case 0: Azure_IoTHub_Sensors.Weather.CurrentWeather = null; msgOut = "Cleared"; break; case 1: Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_Fixed(); break; case 2: Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_Random(); break; case 3: Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_FromCities(); break; case 4: Azure_IoTHub_Sensors.Weather.CurrentWeather = new Azure_IoTHub_Sensors.Weather_FromHardware(); break; default: Azure_IoTHub_Sensors.Weather.CurrentWeather = null; msgOut = "Invalid option. Cleared."; break; } } break; case "get": msgOut = Azure_IoTHub_Sensors.TelemetryDataPoint.Prefix + Azure_IoTHub_Sensors.Weather.CurrentWeather?.ToString(); break; default: msgOut = "Help\r\nset 0|1|2|3|4 Choose the weather class.\r\n0=clear,1=Fixed values,2=random values,\r\n3=Rotating from cities,4=From Arduino device\r\nget Get the weather from the weather class chosen"; break; } } else { msgOut = "try " + msgIn + " help"; } //message = Azure_IoTHub_Telemetry.SimulatedDevice.Message; break; break; case 4: msgOut = "Coming. Not yet implemented. This is a pace holder for now."; break; } Console.WriteLine(msgIn); Console.WriteLine(msgOut); System.Diagnostics.Debug.WriteLine(msgIn); System.Diagnostics.Debug.WriteLine(msgOut); return(msgOut); }
private void TestDevice_C2DMessageReceived(object sender, Microsoft.Azure.Devices.Client.Message receivedMessage) { buttonSendConfirmation.IsEnabled = true; currentReceivedMessage = receivedMessage; }
private async Task RunSvcAsync() { string errorMsg = ""; string updateMsg = ""; using (cancellationTokenSourceManual = new CancellationTokenSource()) { ClientWebSocket stream = null; try { DeviceStreamRequest deviceStreamRequest = new DeviceStreamRequest( streamName: "TestStream" ); updateMsg = "Starting Svc TestStream"; UpdateStatus(updateMsg); cancellationTokenSourceManual.Token.Register(() => { _serviceClient?.CloseAsync(); _serviceClient?.Dispose(); }); DeviceStreamResponse result = await _serviceClient.CreateStreamAsync(_deviceId, deviceStreamRequest).ConfigureAwait(false); updateMsg = string.Format("Svc Stream response received: Name={0} IsAccepted={1}", deviceStreamRequest.StreamName, result.IsAccepted); UpdateStatus(updateMsg); if (result.IsAccepted) { using (cancellationTokenSourceTimeout = new CancellationTokenSource(DeviceStreamingCommon.DeviceTimeout)) { try { using (stream = await DeviceStreamingCommon.GetStreamingDeviceAsync(result.Url, result.AuthorizationToken, cancellationTokenSourceTimeout.Token).ConfigureAwait(false)) { updateMsg = "Stream is open."; UpdateStatus(updateMsg); bool keepAlive = false; MsgOutWaitHandle = new AutoResetEvent(true); do { //Nb: Not waited on first entry as waiting for msgOut, which we already have. updateMsg = "Stream is open. Waiting for msg to send."; UpdateStatus(updateMsg); MsgOutWaitHandle.WaitOne(); updateMsg = "Sending msg."; UpdateStatus(updateMsg); bool caught = false; try { MsgOut = SvcCurrentSettings.ProcessMsgOut(MsgOut, SvcCurrentSettings.KeepAlive, SvcCurrentSettings.ResponseExpected, DevKeepListening, DevAutoStart); } catch (NotImplementedException) { errorMsg += "DeviceCurrentSettings not properly implemented"; keepAlive = false; caught = true; } if (!caught) { await SendMsg(stream, MsgOut, cancellationTokenSourceTimeout); updateMsg = "Sent msg."; UpdateStatus(updateMsg); if (this.SvcCurrentSettings.ResponseExpected) { byte[] receiveBuffer = new byte[1024]; System.ArraySegment <byte> ReceiveBuffer = new ArraySegment <byte>(receiveBuffer); var receiveResult = await stream.ReceiveAsync(ReceiveBuffer, cancellationTokenSourceTimeout.Token).ConfigureAwait(false); MsgIn = Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count); string subStrn = AzIoTHubDeviceStreams.DeviceStreamingCommon.DeiceInSimuatedDeviceModeStrn; int subStrnLen = subStrn.Length; if (MsgIn.Length >= subStrnLen) { if (MsgIn.Substring(0, subStrnLen) == subStrn) { MsgIn = MsgIn.Substring(subStrnLen); AzIoTHubModules.SyntheticIoTMessage iotHubMessage = AzIoTHubModules.SyntheticIoTMessage.Deserialize(MsgIn); Microsoft.Azure.Devices.Client.Message message = iotHubMessage.ToMessage(); Microsoft.Azure.EventHubs.EventData eventData = AzIoTHubModules.SyntheticIoTMessage.ToEventData(message); MsgIn = AzIoTHubModules.SyntheticIoTMessage.EventData_ToString(eventData); } } keepAlive = false; if (SvcCurrentSettings != null) { keepAlive = this.SvcCurrentSettings.KeepAlive; } try { if (OnRecvdTextD != null) { OnRecvdTextD(MsgIn); } } catch (Exception exx) { errorMsg += "OnRecvdTextD not properly implemented: " + exx.Message; keepAlive = false; } updateMsg = string.Format("Svc Received stream data: {0}", MsgIn); UpdateStatus(updateMsg); } MsgOutWaitHandle.Reset(); } } while (keepAlive); MsgOutWaitHandle = null; updateMsg = "Closing Svc Socket"; UpdateStatus(updateMsg); await stream.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationTokenSourceTimeout.Token).ConfigureAwait(false); stream = null; } } catch (Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Hub connection failure"); errorMsg = "Hub connection failure"; } catch (Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Device not found"); errorMsg = "Device not found"; } catch (TaskCanceledException) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Task cancelled"); errorMsg = "Task cancelled"; } catch (OperationCanceledException) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Operation cancelled"); errorMsg = "Operation cancelled"; } catch (Exception ex) { if ((bool)cancellationTokenSourceManual?.IsCancellationRequested) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Cancelled."); errorMsg = "Cancelled"; } else if ((bool)cancellationTokenSourceTimeout?.IsCancellationRequested) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Timed Out."); errorMsg = "Timed Out"; } else if (!ex.Message.Contains("Timed out")) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): " + ex.Message); errorMsg = ex.Message; } else { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Timed out"); errorMsg = "Timed Out"; } } } } } catch (Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Hub connection failure"); errorMsg += " Hub connection failure"; } catch (Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Device not found"); errorMsg += " Device not found"; } catch (TaskCanceledException) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Task cancelled"); errorMsg += " Task cancelled"; } catch (OperationCanceledException) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Operation cancelled"); errorMsg += " Operation cancelled"; } catch (Exception ex) { if ((bool)cancellationTokenSourceManual?.IsCancellationRequested) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Cancelled."); errorMsg += " Cancelled"; } else if ((bool)cancellationTokenSourceTimeout?.IsCancellationRequested) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Timed Out."); errorMsg += " Timed Out"; } else if (!ex.Message.Contains("Timed out")) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): " + ex.Message); errorMsg += " " + ex.Message; } else { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Timed out"); errorMsg += " Timed Out"; } }; if (stream != null) { if (stream.CloseStatus != WebSocketCloseStatus.NormalClosure) { updateMsg = "Aborting Svc Socket as is errant or cancelled: " + errorMsg; UpdateStatus(updateMsg); stream.Abort(); updateMsg = "Aborted Svc Socket as was errant or cancelled:" + errorMsg; UpdateStatus(updateMsg); } else { updateMsg = "Socket closed normally: " + errorMsg; UpdateStatus(updateMsg); } stream = null; } else { updateMsg = "Socket closed Normally: " + errorMsg; UpdateStatus(updateMsg); } deviceStream_Svc = null; MsgOutWaitHandle = null; cancellationTokenSourceTimeout = null; } }
private async Task sendMessage(string deviceId, string commonKey, string iotHub, int messageCount, JObject payLoad, int messageDelaySeconds, Boolean randomize) { Microsoft.Azure.Devices.Client.DeviceClient deviceClient; string connectionString = "HostName=" + iotHub + ";DeviceId=" + deviceId + ";SharedAccessKey=" + commonKey; deviceClient = Microsoft.Azure.Devices.Client.DeviceClient.CreateFromConnectionString(connectionString); //Command timeout. Default is 240 seconds deviceClient.OperationTimeoutInMilliseconds = 30000; //30 second timeout //Set retry policy for sending messages (default is NoRetry) deviceClient.SetRetryPolicy(new Microsoft.Azure.Devices.Client.ExponentialBackoff( retryCount: int.MaxValue, minBackoff: TimeSpan.FromSeconds(1), maxBackoff: TimeSpan.FromSeconds(60), deltaBackoff: TimeSpan.FromSeconds(2))); Random random = new Random(); int messageCounter = 1; while (messageCounter <= messageCount) { if (randomize) { int delaySeconds = random.Next(messageDelaySeconds * 1000); payLoad["LOADTEST-delaySeconds"] = delaySeconds / 1000; System.Threading.Thread.Sleep(delaySeconds); } else { System.Threading.Thread.Sleep(messageDelaySeconds * 1000); } payLoad["LOADTEST-counter"] = messageCounter; payLoad["LOADTEST-generationTimeUTC"] = DateTime.UtcNow.ToString(); payLoad["LOADTEST-origionatingHost"] = Environment.MachineName; Byte[] messageByte = System.Text.Encoding.UTF8.GetBytes(payLoad.ToString()); Microsoft.Azure.Devices.Client.Message message = new Microsoft.Azure.Devices.Client.Message(messageByte); message.ContentEncoding = "utf-8"; message.ContentType = "application/json"; try { await deviceClient.SendEventAsync(message); Console.WriteLine("Device: " + deviceId + " sent msg " + payLoad.ToString()); Microsoft.Azure.Devices.Client.Message receivedMessage = await deviceClient.ReceiveAsync(new TimeSpan(0, 0, 1)); if (receivedMessage != null) { string jsonMessage = System.Text.Encoding.ASCII.GetString(receivedMessage.GetBytes()); Console.WriteLine("Device: " + deviceId + " received msg " + jsonMessage); } messageCounter++; } catch (Exception) { } } await deviceClient.CloseAsync(); }
private static void Main(string[] args) { // Get secrets var devEnvironmentVariable = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT"); var isDevelopment = string.IsNullOrEmpty(devEnvironmentVariable) || devEnvironmentVariable.ToLower() == "development"; string secretsPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\UserSecrets\9a735c2c-ec7a-4c5a-936e-7210fc978f5d", "secrets.json"); var secrets = JsonConvert.DeserializeObject <UserSecrets>(File.ReadAllText(secretsPath)); // Do everything else int val = 0; string systemName = "aSystem"; string rabbitMQServerName = "garage"; string userName = "******"; string password = "******"; var duhh1 = AesCng.Create(); CngProvider provider = new CngProvider("dumdum"); var random = new Random(); UInt32 key = random.NextUInt32(); UInt32 iv = random.NextUInt32(); (var cipherText, var signature) = SimpleCBC.Encode("Hi", key, iv, 2); var sig = BitConverter.GetBytes(signature); var duhh = System.Text.Encoding.UTF8.GetString(cipherText); var message = SimpleCBC.Decode(cipherText, key, iv, 2); var errorTag = new MessageTagValue("Severity", "Error"); var infoTag = new MessageTagValue("Severity", "Info"); var debugTag = new MessageTagValue("Severity", "Debug"); using var serverPublicInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-server.pub"); using var serverPrivateInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-server.priv", "abc"); using var coordinatorPublicInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-coordinator.pub"); using var coordinatorPrivateInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-coordinator.priv", "monkey123"); using var client1PublicInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-client1.pub"); using var client1PrivateInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-client1.priv", "abc"); using var client2PublicInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-client2.pub"); using var client2PrivateInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-client2.priv", "abc"); using var client3PublicInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-client3.pub"); using var client3PrivateInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-client3.priv", "abc"); //using var pushoverPublicInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-pushoverClient.pub"); //using var pushoverPrivateInfo = MessageClientIdentity.ImportFromFile(@"Keys\system-pushoverClient.priv", "abc"); Console.WriteLine(serverPublicInfo.IdentityHash); Console.WriteLine(client1PublicInfo.IdentityHash); Console.WriteLine(client2PublicInfo.IdentityHash); Console.WriteLine(client3PublicInfo.IdentityHash); var xbeeModule = new XBeeNetworkGatewayModule("COM8", new SerialPortParameters(115200, 8, StopBits.One, Parity.None, Handshake.None)); var coordinatorModule = new TrustCoordinatorModule(TimeSpan.FromMinutes(1)); var server = new MessageClientConfigurationBuilder() .RabbitMQCredentials(userName, password) .RabbitMQServerHostName(rabbitMQServerName) .Identity(coordinatorPrivateInfo) .AddClientIdentity(client1PublicInfo) .AddClientIdentity(client2PublicInfo) .AddClientIdentity(client3PublicInfo) //.AddClientIdentity(pushoverPublicInfo) .AutoDeleteQueuesOnClose(true) .QueuesAreDurable(false) .AddModule(coordinatorModule) .AddModule(xbeeModule) .CreateMessageClient(); #if false var server = new MessageServerConfigurationBuilder() .RabbitMQCredentials(userName, password) .RabbitMQServerHostName(rabbitMQServerName) .Identity(serverPrivateInfo) .AddClientIdentity(client1PublicInfo) .AddClientIdentity(client2PublicInfo) .AddClientIdentity(client3PublicInfo) //.AddClientIdentity(pushoverPublicInfo) .AutoDeleteQueuesOnClose(true) .QueuesAreDurable(false) .CreateMessageServer(); #endif server.MessageReceived += (sender, e) => { e.Response = MessageResponse.Ack; if (e.MessageEnevelope.Message.GetType() == typeof(XBeeFromXBeeMessage)) { var tempMessage = (XBeeFromXBeeMessage)e.MessageEnevelope.Message; Log.Verbose($"{tempMessage.XBeeSourceAddress}: {tempMessage.RawData}"); } }; server.AsynchronousException += Client_AsynchronousException; System.Timers.Timer sendTimer = new System.Timers.Timer(1000) { AutoReset = true }; sendTimer.Elapsed += (sender, e) => { IntMessage message = new IntMessage(val); string tag = val % 2 == 0 ? "even" : "odd"; server.WriteToSubscriptionQueues(message, true, new MessageTagValue("duhh", tag), errorTag, infoTag); val++; //server.BroacastToAllClients(message); }; Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() //.WriteTo.DistributedWorkersSink(server) .WriteTo.Console() .CreateLogger(); //Log.Verbose($"Server public string: {serverInfo.PublicKey.PublicKeyToString()}"); server.Connect(TimeSpan.FromSeconds(20)); sendTimer.Start(); //Thread.Sleep(30000); var odd = new MessageTagValue("duhh", "odd"); var even = new MessageTagValue("duhh", "even"); var never = new MessageTagValue("duhh", "never"); #if false var pushoverModule = new PushoverModule(secrets.PushoverAppApiKey, secrets.PushoverUserKey); pushoverModule.AddTransform <IntMessage>(t => { if (t.Payload % 10 == 0) { return(null); // (t.Payload.ToString()); } return(null); }); #endif // TODO: Not all configuration options return the right configuration builder type #if false var pushoverClient = new PushoverMessageClientConfigurationBuilder() .PushoverAppApiKey(secrets.PushoverAppApiKey) .PushoverUserKey(secrets.PushoverUserKey) .RabbitMQCredentials(userName, password) .RabbitMQServerHostName(rabbitMQServerName) .ServerIdentity(serverPublicInfo) .Identity(pushoverPrivateInfo) .AutoDeleteQueuesOnClose(true) .QueuesAreDurable(false) .CreateMessageClient(); pushoverClient.AddTransform <IntMessage>(t => { if (t.Payload % 10 == 0) { return(null); // (t.Payload.ToString()); } return(null); }); pushoverClient.AsynchronousException += Client_AsynchronousException; pushoverClient.Connect(20000); #endif AzureIoTModule iotModule = new AzureIoTModule(secrets.AzureIoTHubConnectionString); iotModule.ForwardMessageToIoTHubTransform = (me) => { return(null); if (me.Message.GetType() == typeof(XBeeFromXBeeMessage)) { var xBeeMessage = (XBeeFromXBeeMessage)me.Message; var iotMessage = new Microsoft.Azure.Devices.Client.Message(); var tempData = xBeeMessage.GetJObject()["Data"]; iotMessage.Properties.Add("Refrigerator Temperature", tempData[0]["Refrigerator"].ToString()); iotMessage.Properties.Add("Freezer Temperature", tempData[1]["Freezer"].ToString()); return(iotMessage); } return(null); }; MessageClient client1 = new MessageClientConfigurationBuilder() .RabbitMQCredentials(userName, password) .RabbitMQServerHostName(rabbitMQServerName) .TrustCoordinatorIdentity(coordinatorPublicInfo) .Identity(client1PrivateInfo) .AutoDeleteQueuesOnClose(true) .QueuesAreDurable(false) //.AddModule(pushoverModule) .AddModule(iotModule) .CreateMessageClient(); xbeeModule.OpenXBee(); client1.AsynchronousException += Client_AsynchronousException; client1.MessageReceived += (sender, e) => { e.Response = MessageResponse.Ack; if (e.MessageEnevelope.Message.GetType() == typeof(IntMessage)) { Console.WriteLine($"Client 1: Message Payload: {((IntMessage)e.MessageEnevelope.Message).Value}."); } }; client1.Connect(TimeSpan.FromSeconds(10), odd, new XBeeReceivedDataTag()); client1.BeginFullWorkConsume(true); MessageClient client2 = new MessageClientConfigurationBuilder() .RabbitMQCredentials(userName, password) .RabbitMQServerHostName(rabbitMQServerName) .TrustCoordinatorIdentity(coordinatorPublicInfo) .Identity(client2PrivateInfo) .AutoDeleteQueuesOnClose(true) .QueuesAreDurable(false) .CreateMessageClient(); client2.AsynchronousException += Client_AsynchronousException; client2.MessageReceived += (sender, e) => { e.Response = MessageResponse.Ack; if (e.MessageEnevelope.Message.GetType() == typeof(IntMessage)) { Console.WriteLine($"Client 2: Message Payload: {((IntMessage)e.MessageEnevelope.Message).Value}."); } else if (e.MessageEnevelope.Message.GetType() == typeof(XBeeFromXBeeMessage)) { var tempMessage = (XBeeFromXBeeMessage)e.MessageEnevelope.Message; Console.WriteLine($"Client 2 XBee ({tempMessage.XBeeSourceAddress}): {tempMessage.RawData}"); } }; client2.Connect(TimeSpan.FromSeconds(10), even, new XBeeReceivedDataTag()); //client2.BeginFullWorkConsume(true); #if false MessageClient client3 = new MessageClientConfiguration() .RabbitMQCredentials(userName, password) .RabbitMQServer(rabbitMQServerName) .ServerInfo(serverInfo) .ClientInfo(client3Info) .AutoDeleteQueuesOnClose(true) .QueuesAreDurable(false) .CreateMessageClient(); client3.MessageReceived += (sender, e) => { e.Response = MessageResponse.Ack; Console.WriteLine($"Client 3: Message Payload: {((IntMessage)e.MessageEnevelope.Message).Payload}."); }; client3.BeginFullWorkConsume(true); #endif // //client3.Connect(TimeSpan.FromSeconds(10)); var serialPort = new XBeeRemoteSerialPort(xbeeModule, new SerializableXBeeAddress(new XBee64BitAddress("0013A20041AE9E32"))); Log.Information("Dumdum"); Console.ReadKey(); }
/// <summary> /// Publish MQTT message /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) { // Get id of device var deviceId = e.Topic.Split('/')[2]; if (e.Message.Length < 200) { // ignore rogue messages return; } WriteLine("MQTT handling uplink"); // Create or get device var device = await AddDeviceAsync(deviceId); if (!_whiteList.Accept(deviceId)) { WriteLine($"Device {deviceId} is not whitelisted"); return; } if (device.Status != DeviceStatus.Enabled) { WriteLine($"Device {deviceId} disabled"); return; } // Convert message to json var jsonText = Encoding.UTF8.GetString(e.Message); dynamic jsonObject = JsonConvert.DeserializeObject(jsonText); var counter = jsonObject.counter?.ToString(); var deviceMessage = jsonObject.payload_fields?.ToString(); if (string.IsNullOrEmpty(deviceMessage)) { WriteLine($"Device {deviceId} seen"); return; } var metadata = jsonObject.metadata; var frequency = metadata?.frequency?.ToString(); var gateway = metadata?.gateways?[0]; var gatewayEui = gateway?.gtw_id?.ToString(); var latitude = gateway?.latitude?.ToString(); var longitude = gateway?.longitude?.ToString(); var rssi = gateway?.rssi?.ToString(); // construct message for IoT Hub dynamic iotHubMessage = JsonConvert.DeserializeObject(deviceMessage); if (_addGatewayInfo) { iotHubMessage.ttnCounter = jsonObject.counter ?? -1; iotHubMessage.ttnGatewayEui = gateway?.gtw_id?.ToString(); iotHubMessage.ttnGatewayLat = gateway?.latitude ?? 0.0; iotHubMessage.ttnGatewayLon = gateway?.longitude ?? 0.0; iotHubMessage.ttnGatewayFreq = metadata?.frequency ?? 0.0; iotHubMessage.ttnGatewayRssi = gateway?.rssi ?? 0; } var iotHubMessageString = JsonConvert.SerializeObject(iotHubMessage); Write($"{DateTime.Now:HH:mm:ss} Message received ({counter}/{deviceId}/{gatewayEui}/{latitude}/{longitude}/{frequency}/{rssi}): {iotHubMessageString}"); // create device client var key = (_deviceKeyKind == "Primary") ? device.Authentication.SymmetricKey.PrimaryKey : device.Authentication.SymmetricKey.SecondaryKey; var deviceClient = _deviceClientList.GetDeviceClient(deviceId, key); // send message var message = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(iotHubMessageString)); await deviceClient.SendEventAsync(message); WriteLine("-IoT Hub message sent"); }
public IoTHubMessageReceivedEventArgs(Microsoft.Azure.Devices.Client.Message message) : base() { }