static void DoReceives(CancellationToken ct, string iotHubConnectionString) { // Was cancellation already requested? if (ct.IsCancellationRequested == true) { Console.WriteLine("DoReceives was cancelled before it got started."); ct.ThrowIfCancellationRequested(); } var deviceClient = DeviceClient.CreateFromConnectionString(iotHubConnectionString, TransportType.Amqp); while (true) { //receive cloud messages var rcvTask = AzureIoTHub.ReceiveCloudToDeviceMessageAsync(deviceClient); rcvTask.Wait(ct); Console.WriteLine("Received message from cloud: {0}", rcvTask.Result); if (ct.IsCancellationRequested) { Console.WriteLine("Task DoReceives cancelled"); ct.ThrowIfCancellationRequested(); } } }
static void DoSends(CancellationToken ct) { // Was cancellation already requested? if (ct.IsCancellationRequested == true) { Console.WriteLine("DoSends was cancelled before it got started."); ct.ThrowIfCancellationRequested(); } long msgTime = 1473956534640; int iteration = 0; while (true) { //send device to cloud telemetry var deviceToCloudMessage = new DeviceTelemetryMessage { datestamp = DateTime.UtcNow, response = "environment", temperature = lastTemp, humidity = 28.7, pressure = 100912, message_id = Guid.NewGuid().ToString(), device_id = deviceId }; var messageString = JsonConvert.SerializeObject(deviceToCloudMessage); var sendTask = AzureIoTHub.SendDeviceToCloudMessageAsync(messageString, deviceToCloudMessage.message_id); sendTask.Wait(ct); Console.WriteLine("Sent Message to Cloud: {0}", messageString); ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(sendIntervalInSeconds));//wait before sending so we are not in a tight loop ++msgTime; } }
async public Task Display(IDeviceMessage sensor) { await AzureIoTHub.SendDeviceToCloudMessageAsync(sensor.MachineID, JsonConvert.SerializeObject(sensor, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore })); }
private void CheckIncomingCommand(Frame frame) { while (true) { string json = AzureIoTHub.ReceiveCloudToDeviceMessageAsync().Result; dynamic deserializeObject = JsonConvert.DeserializeObject(json); string command = deserializeObject.Type; frame.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (command.Equals("Timer")) { frame.Navigate(typeof(Timer), json); } else if (command.Equals("Count")) { frame.Navigate(typeof(Count), json); } else if (command.Equals("Location")) { frame.Navigate(typeof(Location), json); } }); } }
private async void Timer_Tick(object sender, object e) { if (livetemperature() >= 23) { TestPostMessage(livetemperature().ToString()); //Take photo and save into Intrusos if (webcam == null || !webcam.IsInitialized()) { // Initialize Webcam Helper webcam = new WebcamHelper(); await webcam.InitializeCameraAsync(); } currentIdPhotoFile = await webcam.CapturePhoto(); // Create or open the folder in which the Whitelist is stored StorageFolder whitelistFolder = await KnownFolders.PicturesLibrary.CreateFolderAsync(GeneralConstants.WhiteListFolderName, CreationCollisionOption.OpenIfExists); // Create a folder to store this specific user's photos StorageFolder currentFolder = await whitelistFolder.CreateFolderAsync("Intrusos", CreationCollisionOption.OpenIfExists); // Move the already captured photo the user's folder await currentIdPhotoFile.MoveAsync(currentFolder); } await Task.Run(async() => { await AzureIoTHub.SendTemperatureAsync(livetemperature()); }); }
private async void webView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args) { await AzureIoTHub.RegisterDirectMethodAsync( "SearchFuzzy", async delegate(string query) { System.Diagnostics.Debug.WriteLine($"Request for 'SearchFuzzy' is received."); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => await webView.InvokeScriptAsync("eval", new[] { $"document.getElementById('search-input').value = '{query}'; shouldChangeCamera = true; search(searchResultsHandler);" }) ); }); await AzureIoTHub.RegisterDirectMethodAsync( "ZoomIn", async delegate(string query) { System.Diagnostics.Debug.WriteLine($"Request for 'ZoomIn' is received."); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => await webView.InvokeScriptAsync("eval", new[] { $"plusZoomElement.click();" }) ); }); await AzureIoTHub.RegisterDirectMethodAsync( "ZoomOut", async delegate(string query) { System.Diagnostics.Debug.WriteLine($"Request for 'ZoomOut' is received."); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => await webView.InvokeScriptAsync("eval", new[] { $"minusZoomElement.click();" }) ); }); }
private static async void sendMessage() { double avgWindSpeed = 10; // m/s Random rand = new Random(); while (true) { double currentWindSpeed = avgWindSpeed + rand.NextDouble() * 4 - 2; var telemetryDataPoint = new { deviceId = "myFirstDevice", windSpeed = currentWindSpeed }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); //var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); await AzureIoTHub.SendDeviceToCloudMessageAsync(messageString); // HelloMessage.Text = String.Format("{0} > Sending message: {1}", DateTime.Now, messageString); // Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); Task.Delay(1000).Wait(); } // await AzureIoTHub.SendDeviceToCloudMessageAsync(); }
public async Task RecieveAlert() { string Alert = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); status.Text = Alert; await RecieveAlert(); }
private async Task CollectSensorData(IProgress <Measurement> progress) { using (ISenseHat senseHat = await SenseHatFactory.GetSenseHat()) { for (; ;) { try { senseHat.Sensors.HumiditySensor.Update(); senseHat.Sensors.PressureSensor.Update(); senseHat.Sensors.ImuSensor.Update(); var measurement = new Measurement() { Temperature = senseHat.Sensors.Temperature ?? 0, Humidity = senseHat.Sensors.Humidity ?? 0, Pressure = senseHat.Sensors.Pressure ?? 0, MagneticField = (Vector3)senseHat.Sensors.MagneticField, Gyroscope = (Vector3)senseHat.Sensors.Gyro, Acceleration = (Vector3)senseHat.Sensors.Acceleration }; progress.Report(measurement); await AzureIoTHub.SendDeviceToCloudMessageAsync(measurement); } catch (Exception e) { Debug.WriteLine("Exception: " + e.Message); } await Task.Delay(1000); } } }
public async Task RecieveAlert() { string value = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); RecieveMessageStatus.Text = value; if (value.Equals("Capture")) { ImageCapture(); } if (value.Equals("forward")) { moveforward(); } if (value.Equals("backward")) { movebackward(); } if (value.Equals("right")) { moveright(); } if (value.Equals("left")) { moveleft(); } if (value.Equals("stop")) { stop(); } await RecieveAlert(); }
private static void Main() { Console.WriteLine("Simulated device\n"); try { var deviceClient = DeviceClient.CreateFromConnectionString(AzureIoTHub.GetConnectionString(), TransportType.Mqtt); new DeviceSimulator(deviceClient).SendDeviceToCloudMessagesAsync(AzureIoTHub.deviceId); /* */ // UN-comment the code you want to execute new FileUploads().InitFileUpload(); UpdateFirmware(AzureIoTHub.deviceId); Console.ReadLine(); } catch (AggregateException ex) { foreach (var exception in ex.InnerExceptions) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", exception); } } catch (Exception) { //Some code here } }
private async Task ListenToIot() { string msg = string.Empty; while (true) { try { msg = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); //await AzureIoTHub.SendDeviceToCloudMessageAsync(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } if (msg.Contains("play")) { PlayMusic(); } else if (msg.Contains("stop")) { StopMusic(); } Debug.WriteLine(msg); } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); _pinDht = _gpio.OpenPin(DHT11_PIN, GpioSharingMode.Exclusive); _dht11 = new Dht11(_pinDht, GpioPinDriveMode.Input); _pinLed = _gpio.OpenPin(LED_PIN); _pinLed.SetDriveMode(GpioPinDriveMode.Output); _pinLed.Write(GpioPinValue.Low); _timer.Start(); _startedAt = DateTimeOffset.Now; // Send IoT device info (once). if (_sendToCloud) { try { await AzureIoTHub.SendDeviceToCloudMessageAsync(JsonConvert.SerializeObject(_deviceInfo)); _gridOffline.Visibility = Visibility.Collapsed; } catch (Exception ex) { Debug.WriteLine("Problem sending to IoT Hub: " + ex.Message.ToString()); _gridOffline.Visibility = Visibility.Visible; } } }
private async Task ReadAsync() { Task <UInt32> loadAsyncTask; uint ReadBufferLength = 1024; string MedValues = null; // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available dataReaderObject.InputStreamOptions = InputStreamOptions.Partial; // Create a task object to wait for data on the serialPort.InputStream loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(); UInt32 bytesRead = await loadAsyncTask; if (bytesRead > 0) { string pulseReading = dataReaderObject.ReadString(bytesRead) .Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Last().Trim(); MedValues = rcvdText.Text = $"Medical_IOT_PulseOximeter,John Doe,{pulseReading},17.438575,78.510194"; //,17.3971, 78.4903"; status.Text = "bytes read successfully!"; await AzureIoTHub.SendDeviceToCloudMessageAsync(MedValues); } await Task.Delay(TimeSpan.FromSeconds(3)); }
private void UpdateDevice_Click(object sender, RoutedEventArgs e) { AzureDevices SelectedDevice = (AzureDevices)DeviceList.SelectedItems[0]; if (TrueRadio.IsChecked.Value) { SelectedDevice.Status = true; } else { SelectedDevice.Status = false; } var index = DeviceList.Items.IndexOf(DeviceList.SelectedItem); list.RemoveAt(index); list.Insert(index, SelectedDevice); /* DeviceList.ItemsSource = null; * DeviceList.ItemsSource = list;*/ MyAzureClass myAzureClass = new MyAzureClass(); myAzureClass.UpdateRecordInTable(SelectedDevice); AzureIoTHub.SendDeviceToCloudMessageAsync(); }
public void Stop() { ena.Write(GpioPinValue.Low); enb.Write(GpioPinValue.Low); in1.Write(GpioPinValue.Low); in2.Write(GpioPinValue.Low); in3.Write(GpioPinValue.Low); in4.Write(GpioPinValue.Low); if (timerForward.IsRunning) { Debug.WriteLine("Tiempo hacia delante: " + timerForward.ElapsedMilliseconds); timerForward.Stop(); AzureIoTHub.SendDeviceToCloudMessageAsync((int)timerForward.ElapsedMilliseconds, "forward", true); } if (timerBacward.IsRunning) { Debug.WriteLine("Tiempo hacia atrás: " + timerBacward.ElapsedMilliseconds); timerBacward.Stop(); AzureIoTHub.SendDeviceToCloudMessageAsync((int)timerForward.ElapsedMilliseconds, "backward", true); } if (timerLeft.IsRunning) { Debug.WriteLine("Tiempo hacia izquierda: " + timerLeft.ElapsedMilliseconds); timerLeft.Stop(); AzureIoTHub.SendDeviceToCloudMessageAsync((int)timerForward.ElapsedMilliseconds, "left", false); } if (timerRight.IsRunning) { Debug.WriteLine("Tiempo hacia derecha: " + timerRight.ElapsedMilliseconds); timerRight.Stop(); AzureIoTHub.SendDeviceToCloudMessageAsync((int)timerForward.ElapsedMilliseconds, "right", false); } }
private async void SendButton_Click(object sender, RoutedEventArgs e) { AzureIoTHub.SendDeviceToCloudMessageAsync(); var message = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); Debug.WriteLine("Message: " + message); }
public MainPage() { this.InitializeComponent(); Task.Run( async() => { while (true) { var message = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { textBox.Text += Environment.NewLine + message; if (message.ToLower().Contains("alert")) { textBox1.IsEnabled = true; } else { textBox1.IsEnabled = false; } }); } } ); }
private static void Main() { Console.WriteLine("Simulated device\n"); DeviceClient deviceClient = null; try { deviceClient = DeviceClient.CreateFromConnectionString(AzureIoTHub.GetConnectionString(), TransportType.Mqtt); ExcuteDirectMethod(deviceClient); } catch (AggregateException ex) { foreach (var exception in ex.InnerExceptions) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", exception); } } catch (Exception) { //Some code here } RemoveMethodHandler(deviceClient); Console.ReadLine(); }
public async Task UploadFile(Windows.Storage.StorageFile Photofile) { var sourceData = new FileStream(@photoFile.Path, FileMode.Open); await sourceData.ReadAsync(new byte[1], 0, 1); AzureIoTHub.SendToBlobAsyncStream(photoFile, sourceData).Wait(); }
static void DoReceives(CancellationToken ct) { // Was cancellation already requested? if (ct.IsCancellationRequested == true) { Console.WriteLine("DoReceives was cancelled before it got started."); ct.ThrowIfCancellationRequested(); } while (true) { //receive cloud messages var rcvTask = AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); rcvTask.Wait(ct); Console.WriteLine("Received message from cloud: {0}", rcvTask.Result); // ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)); if (ct.IsCancellationRequested) { Console.WriteLine("Task DoReceives cancelled"); ct.ThrowIfCancellationRequested(); } } }
static void DoSends(CancellationToken ct, string iotHubConnectionString) { // Was cancellation already requested? if (ct.IsCancellationRequested == true) { Console.WriteLine("DoSends was cancelled before it got started."); ct.ThrowIfCancellationRequested(); } long msgTime = 1473956534640; var deviceClient = DeviceClient.CreateFromConnectionString(iotHubConnectionString, TransportType.Amqp); while (true) { //send device to cloud telemetry var deviceToCloudMessage = new DeviceTelemetryMessage { datestamp = DateTime.UtcNow, response = "environment", temperature = lastTemp, humidity = 28.7, pressure = 100912 }; var messageString = JsonConvert.SerializeObject(deviceToCloudMessage); var sendTask = AzureIoTHub.SendDeviceToCloudMessageAsync(deviceClient, messageString); sendTask.Wait(ct); Console.WriteLine("Sent Message to Cloud: {0}", messageString); ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));//wait before sending so we are not in a tight loop ++msgTime; } }
//private string CheckForStateValue(eState newState) //{ // String lightStatus; // switch (newState) // { // case eState.JustRight: // { // lightStatus = JustRightLightString; // } // break; // case eState.TooBright: // { // lightStatus = HighLightString; // } // break; // case eState.TooDark: // { // lightStatus = LowLightString; // } // break; // default: // { // lightStatus = "N/A"; // } // break; // } // return lightStatus; //} private async Task SendDeviceToCloudMessageAsync(string status, BMP280SensorData BMP280SensorData, MCP3008SensorData MCP3008SensorData) { ConferenceRoomDataPoint conferenceRoomDataPoint = new ConferenceRoomDataPoint() { DeviceId = deviceName, Time = DateTime.UtcNow.ToString("o"), RoomTemp = BMP280SensorData.Temperature.ToString(), RoomPressure = BMP280SensorData.Pressure.ToString(), RoomAlt = BMP280SensorData.Altitude.ToString(), }; if (status == "Occupied") { conferenceRoomDataPoint.Color = "Red"; } else { conferenceRoomDataPoint.Color = "Green"; } var jsonString = JsonConvert.SerializeObject(conferenceRoomDataPoint); //var jsonStringInBytes = new Message(Encoding.ASCII.GetBytes(jsonString)); await AzureIoTHub.SendDeviceToCloudMessageAsync(jsonString); Debug.WriteLine("{0} > Sending message: {1}", DateTime.UtcNow, jsonString); }
private void timer_Elapsed(object sender, ElapsedEventArgs e) { Task.Run(async() => { var message = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); }); }
public void Start() { _timer = new Timer(10 * 1000); // every 10 minutes _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); _timer.Start(); Task.Run(async() => { var message = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); }); // write code here that runs when the Windows Service starts up. }
public static async Task SendDeviceToCloudMessageAsync(string deviceID, string mesage) { var deviceClient = DeviceClient.CreateFromConnectionString(AzureIoTHub.GetDeviceConnectionString(deviceID), TransportType.Amqp); var str = mesage; var message = new Message(Encoding.ASCII.GetBytes(str)); await deviceClient.SendEventAsync(message); }
private async Task Send(string msg) { string dt = DateTime.Now.ToString(); string jsn = "{\"Time\":\"" + dt + "\"," + msg.Substring(1); Debug.WriteLine("Sending: " + jsn); await AzureIoTHub.SendDeviceToCloudMessageAsyncUseTPM(msg); }
private void DeviceStatusButton_PointerPressed(object sender, PointerRoutedEventArgs e) { MainDevice.Status = true; MyAzureClass myAzureClass = new MyAzureClass(); myAzureClass.UpdateRecordInTable(MainDevice); AzureIoTHub.SendDeviceToCloudMessageAsync(); Debug.WriteLine("Button Pressed"); }
public async void uda() { int ud = 3; this.InitializeComponent(); await AzureIoTHub.SendDeviceToCloudMessageAsync(ud.ToString()); //await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(luminozitate.ToString()); }
public async void listen() { while (true) { string cloudMessage = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); System.Diagnostics.Debug.WriteLine(cloudMessage); } }