Esempio n. 1
0
        private void TimerCallBack(object state)
        {
            try
            {
                // Check the value of the Sensor.
                // Temperature in Celsius is returned as a double type.  Convert it to string so we can print it.
                sensor.Measure();
                string sensortemp = sensor.TemperatureInFahrenheit.ToString();
                // Same for Humidity.
                string sensorhum = sensor.Humidity.ToString();

                // Print all of the values to the debug window.
                System.Diagnostics.Debug.WriteLine("Temp is " + sensortemp + " F.  And the Humidity is " + sensorhum + "%. ");

                /* UI updates must be invoked on the UI thread */
                var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Text_Temperature.Text = "Temperature: " + sensortemp + "F";
                    Text_Humidity.Text    = "Humidity: " + sensorhum + "%";
                });

                SendDeviceToCloudMessageAsync(Convert.ToInt32(sensor.Humidity), Convert.ToInt32(sensor.TemperatureInCelsius));
            }
            catch (Exception ex)
            {
                // If you want to see the exceptions uncomment the following:
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
        async void Publish()
        {
            if (dht11 == null || deviceClient == null)
            {
                return;
            }

            double temperature, humidity;

            try {
                publishLed.ChangeState(SensorStatus.On);

                dht11.Measure();

                temperature = dht11.TemperatureInCelsius;
                humidity    = dht11.Humidity;

                if (double.IsNaN(temperature) || double.IsNaN(humidity))
                {
                    return;
                }

                var content = new Message(telemetry.ToJson(temperature, light.SensorValue() * 100 / 1023, 0, humidity));

                await deviceClient.SendEventAsync(content);
            }
            catch { telemetry.Exceptions++; }

            publishLed.ChangeState(SensorStatus.Off);
        }
Esempio n. 3
0
        private void Dt_Tick(object sender, object e)
        {
            sensor.Measure();
            double sensortemp = sensor.TemperatureInCelsius;

            lcc.addToChart(new DateModel(sensortemp, DateTime.Now));
        }
Esempio n. 4
0
        private async Task SyncToAzure()
        {
            var DeviceConnectionString = "NithinsPI.azure-devices.net";
            var DeviceId  = "NithinsPI";
            var DeviceKey = "3/Di9ndJYFzf5JphzW8YzRM7HebOhKoUGoqmK6Xh/cY=";

            var device = DeviceClient.Create(DeviceConnectionString, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey),
                                             TransportType.Amqp);

            IDHTTemperatureAndHumiditySensor sensor = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin4, DHTModel.Dht11);

            while (true)
            {
                sensor.Measure();
                string sensortemp = sensor.TemperatureInCelsius.ToString();
                string sensorhum  = sensor.Humidity.ToString();

                var telemetry = new Telemetry
                {
                    Temperature = sensortemp,
                    Humidity    = sensorhum
                };

                var payLoad = JsonConvert.SerializeObject(telemetry);
                var message = new Message(Encoding.ASCII.GetBytes(payLoad));

                await device.SendEventAsync(message);

                await Task.Delay(TimeSpan.FromSeconds(15));
            }
        }
        private void TimerCallBack(object state)
        {
            try
            {
                // Check the value of the Sensor.
                // Temperature in Celsius is returned as a double type.  Convert it to string so we can print it.
                sensor.Measure();
                string sensortemp = sensor.TemperatureInCelsius.ToString();
                // Same for Humidity.
                string sensorhum = sensor.Humidity.ToString();

                // Print all of the values to the debug window.
                System.Diagnostics.Debug.WriteLine("Temp is " + sensortemp + " C.  And the Humidity is " + sensorhum + "%. ");
                display.SetText("Temp: " + sensortemp + "C" + "       " + "Humidity: " + sensorhum + "%").SetBacklightRgb(0, 50, 255);

                /* UI updates must be invoked on the UI thread */
                var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Text_Temperature.Text = "Temperature: " + sensortemp + "C";
                    Text_Humidity.Text    = "Humidity: " + sensorhum + "%";
                });
            }
            catch (Exception ex)
            {
                // NOTE: There are frequent exceptions of the following:
                // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '.
                // This appears to be caused by the rapid frequency of writes to the GPIO
                // These are being swallowed here/

                // If you want to see the exceptions uncomment the following:
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
Esempio n. 6
0
        public TempEntry GetTimeAndTemp()
        {
            _sensor.Measure();

            var entry = new TempEntry
            {
                Time        = DateTime.Now,
                Temperature = (Decimal)_sensor.TemperatureInFahrenheit,
                Humidity    = (Decimal)_sensor.Humidity
            };

            return(entry);
        }
Esempio n. 7
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Connect the Sound Sensor to Digital port 4
            // Models of Temp and Humidity sensors are - Dht11, Dht12, Dht21
            // In this example, we use the DHT11 sensor that comes with the GrovePi Starter Kit.
            /// Specifies the model of sensor.
            /// DHT11 - blue one - comes with the GrovePi+ Starter Kit.
            /// DHT22 - white one, aka DHT Pro or AM2302.
            /// DHT21 - black one, aka AM2301.

            IDHTTemperatureAndHumiditySensor sensor = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin3, DHTModel.Dht11);

            var display = DeviceFactory.Build.RgbLcdDisplay();

            // Loop endlessly
            while (true)
            {
                Task.Delay(1000).Wait(); //Delay 1 second
                try
                {
                    // Check the value of the Sensor.
                    // Temperature in Celsius is returned as a double type.  Convert it to string so we can print it.
                    sensor.Measure();
                    var sensortemp = sensor.TemperatureInFahrenheit;
                    // Same for Humidity.
                    string sensorhum = sensor.Humidity.ToString();

                    if (sensortemp > 75.0d)
                    {
                        display.SetBacklightRgb(255, 0, 0);
                    }
                    else
                    {
                        display.SetBacklightRgb(0, 255, 0);
                    }

                    // Print all of the values to the debug window.
                    System.Diagnostics.Debug.WriteLine("Temp is " + sensortemp + " F.  And the Humidity is " + sensorhum + "%. ");
                }
                catch (Exception ex)
                {
                    // NOTE: There are frequent exceptions of the following:
                    // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '.
                    // This appears to be caused by the rapid frequency of writes to the GPIO
                    // These are being swallowed here/

                    // If you want to see the exceptions uncomment the following:
                    // System.Diagnostics.Debug.WriteLine(ex.ToString());
                }
            }
        }
Esempio n. 8
0
        public double Measure()
        {
            var tmp = 0.0;

            try
            {
                GroveTempHumi.Measure();
                tmp = GroveTempHumi.TemperatureInCelsius;

                return(tmp);
            }
            catch (Exception ex)
            {
                return(tmp);
            }
        }
Esempio n. 9
0
        private void getTempD()
        {
            sm.WaitOne();
            humtemp.Measure();
            double tempC = humtemp.TemperatureInCelsius;
            double hum   = humtemp.Humidity;

            sm.Release();
            if (!Double.IsNaN(tempC) && !Double.IsNaN(hum))
            {
                Debug.WriteLine(tempC + "temp\n" + hum + "hum");
                sendDataToWindows("TEMP=" + tempC);
                sendDataToWindows("HUMIDITY=" + hum);
            }
            //if (tempC >= warning)
            // ring buzzer
        }
Esempio n. 10
0
        private async Task <string> GetSensorData(IRotaryAngleSensor vibroSensor, IDHTTemperatureAndHumiditySensor temperatureHumiditySensor)
        {
            temperatureHumiditySensor.Measure();

            var eventDataJson = JsonConvert.SerializeObject(new
            {
                deviceId       = DEVICEID,
                temperature    = temperatureHumiditySensor.TemperatureInCelsius,
                humidity       = temperatureHumiditySensor.Humidity,
                vibrationLevel = vibroSensor.SensorValue(),
                latitude       = LATITUDE,
                longitude      = LONGITUDE
            });

            Debug.WriteLine($"EventData {eventDataJson}");
            return(eventDataJson);
        }
Esempio n. 11
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine($"Polling Time is {pollingTime} seconds");
            //Calculate milliseconds to give to the method below for waiting
            pollingTimeMS = pollingTime * 1000;

            //Initialize azure cloud client
            client = new AzureCloudClient(azureIoTConnectionString);

            while (true)
            {
                try
                {
                    // Check the value of the sensor
                    sensor.Measure();
                    double sensortemp = sensor.TemperatureInFahrenheit;
                    double sensorhum  = sensor.Humidity;

                    //Check for invalid values
                    if (double.IsNaN(sensortemp) || double.IsNaN(sensorhum))
                    {
                        throw new Exception($"Sensor not working - Temperature:{sensortemp}, Humidity:{sensorhum}");
                    }

                    //Sending payload to the cloud
                    Debug.WriteLine($"Temp: {sensortemp.ToString()}F Humidity: {sensorhum}%.");
                    DataObject data = new DataObject()
                    {
                        Temperature = sensortemp,
                        Humidity    = sensorhum,
                        DeviceName  = deviceName
                    };
                    client.WriteData(data);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }

                //Wait for the alloted polling time in milliseconds
                Task.Delay(pollingTimeMS).Wait();
            }
        }
Esempio n. 12
0
        private void rpiRun()
        {
            try
            {
                GroveTempHumi.Measure();
                var tmp = GroveTempHumi.TemperatureInCelsius;
                SGroveTempSensor = "Temperature: " + tmp.ToString() + "℃";
                var tmp1 = GroveTempHumi.Humidity;
                SGroveHumiditySensor = "Humidity: " + tmp1.ToString() + "%";
            }
            catch (Exception /*ex*/)
            {
            }

            var UItask = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                GroveHumidityUI.Text = SGroveHumiditySensor;
                GroveTempUI.Text     = SGroveTempSensor;
            });
        }
Esempio n. 13
0
        private TelemtryData MeasureTelemetry()
        {
            TelemtryData data = new TelemtryData();

            if (sensor != null)
            {
                try
                {
                    sensor.Measure();
                    data.Temperature = sensor.TemperatureInFahrenheit;
                    data.Humidity    = sensor.Humidity;
                    data.LiveData    = true;
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.ToString());
                }
            }
            return(data);
        }
Esempio n. 14
0
        private TelemetryData MeasureTelemetry()
        {
            TelemetryData data = new TelemetryData();

            data.LcdColor = lcdIsGreen ? "green" : "red";
            if (sensor != null)
            {
                try
                {
                    sensor.Measure();
                    data.Temperature = sensor.TemperatureInFahrenheit;
                    data.Humidity    = sensor.Humidity;
                    data.LiveData    = true;
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                }
            }
            return(data);
        }
Esempio n. 15
0
        public override async Task Test()
        {
            try
            {
                GroveTempHumi.Measure();
                var tmp = GroveTempHumi.TemperatureInCelsius;
                TempToSend       = tmp;
                DateToSend       = DateTime.Now;
                SGroveTempSensor = "Temperature: " + tmp.ToString() + "℃";
                var tmp1 = GroveTempHumi.Humidity;
                SGroveHumiditySensor = "Humidity: " + tmp1.ToString() + "%";
            }
            catch (Exception ex)
            {
            }

            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                                                        () =>
            {
                State = SGroveTempSensor;
            });
        }
Esempio n. 16
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Application is running!");


            var DeviceConnectionString = "NithinsPI.azure-devices.net";
            var DeviceId  = "NithinsPI";
            var DeviceKey = "3/Di9ndJYFzf5JphzW8YzRM7HebOhKoUGoqmK6Xh/cY=";

            var device = DeviceClient.Create(DeviceConnectionString, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey),
                                             TransportType.Http1);

            IDHTTemperatureAndHumiditySensor sensor = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin4, DHTModel.Dht11);
            ILed greenLed = DeviceFactory.Build.Led(Pin.DigitalPin5);

            while (true)
            {
                BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

                greenLed.AnalogWrite(Convert.ToByte(255));
                sensor.Measure();
                string sensortemp = sensor.TemperatureInCelsius.ToString();
                string sensorhum  = sensor.Humidity.ToString();

                var telemetry = new Telemetry
                {
                    Temperature = sensortemp,
                    Humidity    = sensorhum
                };

                var payLoad = JsonConvert.SerializeObject(telemetry);
                var message = new Message(Encoding.ASCII.GetBytes(payLoad));

                await device.SendEventAsync(message).ConfigureAwait(false);

                greenLed.AnalogWrite(Convert.ToByte(0));
                await Task.Delay(TimeSpan.FromHours(1));
            }
        }
        public GroveMessage GetSensorValue()
        {
            GroveMessage message = new GroveMessage();

            try
            {
                temphumiSensor.Measure();
                message.Temp      = temphumiSensor.TemperatureInCelsius;
                message.Hum       = temphumiSensor.Humidity;
                message.Sound     = soundSensor.SensorValue();
                message.Light     = lightSensor.SensorValue();
                message.GasSO     = gasSensor.SensorValue();
                message.PIR       = pirMotion.IsPeopleDetected();
                message.Timestamp = DateTime.Now.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(message);
        }
Esempio n. 18
0
        private void THSensorRead(object sender, object e)
        {
            float sensortemp;
            // Same for Humidity.
            float sensorhum;

            lock (senslck)
            {
                THsensor_mod.Measure();
                sensortemp = Convert.ToSingle(THsensor_mod.TemperatureInCelsius);
                // Same for Humidity.
                sensorhum = Convert.ToSingle(THsensor_mod.Humidity);
            }

            var timestamp = DateTime.Now;

            handler.addDATASETtoThermalSensor(timestamp, sensortemp);
            handler.addDATASETtoHumidSensor(timestamp, sensorhum);

            SendToCloud(new { nodeid    = vis.senname.Text,
                              tempvals  = new[] { new { timestamp = timestamp, val = sensortemp } },
                              humidvals = new[] { new { timestamp = timestamp, val = sensorhum } } });
        }
Esempio n. 19
0
        private void Timer_Tick(object sender, object e)
        {
            ledOn = !ledOn;
            if (ledOn)
            {
                grove.DigitalWrite(led, 1);
                //hat.Display.Fill(Colors.Beige);
            }
            else
            {
                grove.DigitalWrite(led, 0);
                //hat.Display.Clear();
            }
            var b = grove.DigitalRead(butt);

            grove.DigitalWrite(buzzer, b);

            dht.Measure();

            lbl.Text = string.Format("T: {0}, H: {1}",
                                     dht.TemperatureInCelsius, dht.Humidity);
            //hat.Display.Update();
            //lbl.Text = DateTime.Now.ToLongTimeString();
        }
Esempio n. 20
0
        private async void Timer_Tick(ThreadPoolTimer timer)
        {
            string sensortemp;
            string sensorhum;
            double dsensortemp = 0.0;
            double dsensorhum  = 0.0;

            double dco2 = 0.0;

            if (_cancelRequested == false)
            {
                Debug.WriteLine($"------------------------------------------------------ Blick {pocitadlo++}!!!");
                try
                {
                    // Check the value of the Sensor.
                    // Temperature in Celsius is returned as a double type.  Convert it to string so we can print it.
                    sensor.Measure();
                    //sensortemp = sensor.TemperatureInCelsius.ToString();
                    dsensortemp = sensor.TemperatureInCelsius;
                    // Same for Humidity.
                    //sensorhum = sensor.Humidity.ToString();
                    dsensorhum = sensor.Humidity;

                    // Print all of the values to the debug window.
                    System.Diagnostics.Debug.WriteLine("Temp is " + dsensortemp + " C.  And the Humidity is " + dsensorhum + "%. ");
                }
                catch (Exception ex)
                {
                    // NOTE: There are frequent exceptions of the following:
                    // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '.
                    // This appears to be caused by the rapid frequency of writes to the GPIO
                    // These are being swallowed here/

                    // If you want to see the exceptions uncomment the following:
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }

                try
                {
                    using (SerialDevice serialPort = await SerialDevice.FromIdAsync(dis[0].Id))
                    {
                        /* Configure serial settings */
                        serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                        serialPort.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                        serialPort.BaudRate     = 9600;                                         /* mini UART: only standard baudrates */
                        serialPort.Parity       = SerialParity.None;                            /* mini UART: no parities */
                        serialPort.StopBits     = SerialStopBitCount.One;                       /* mini UART: 1 stop bit */
                        serialPort.DataBits     = 8;

                        /* Write a string out over serial */
                        //string txBuffer = "Hello Serial";
                        byte[]     send86Buffer = { 0XFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79 };
                        DataWriter dataWriter   = new DataWriter();
                        //dataWriter.WriteString(txBuffer);

                        dataWriter.WriteBytes(send86Buffer);

                        uint bytesWritten = await serialPort.OutputStream.WriteAsync(dataWriter.DetachBuffer());

                        /* Read data in from the serial port */
                        const uint maxReadLength = 1024;
                        DataReader dataReader    = new DataReader(serialPort.InputStream);
                        uint       bytesToRead   = await dataReader.LoadAsync(maxReadLength);

                        byte[] recv86Buffer = new byte[bytesToRead];
                        dataReader.ReadBytes(recv86Buffer);
                        //string koko = System.Convert.ToString(recv86Buffer[0],16)
                        dco2 = recv86Buffer[2] * 256 + recv86Buffer[3];
                        Debug.WriteLine("Přišlo: " +
                                        System.Convert.ToString(recv86Buffer[0], 16) + ", " +
                                        System.Convert.ToString(recv86Buffer[1], 16) + ", " +
                                        System.Convert.ToString(recv86Buffer[2], 16) + ", " +
                                        System.Convert.ToString(recv86Buffer[3], 16) + ", " +
                                        System.Convert.ToString(recv86Buffer[4], 16) + ", " +
                                        System.Convert.ToString(recv86Buffer[5], 16) + ", " +
                                        System.Convert.ToString(recv86Buffer[6], 16) + ", " +
                                        System.Convert.ToString(recv86Buffer[7], 16) + ", " +
                                        System.Convert.ToString(recv86Buffer[8], 16) +
                                        "; Gas concentration = " + dco2.ToString() + " ;");
                    }

                    try
                    {
                        var cb = new SqlConnectionStringBuilder();
                        cb.DataSource     = "iot01.database.windows.net";
                        cb.UserID         = "ivanj9";
                        cb.Password       = "******";
                        cb.InitialCatalog = "iot01";

                        using (var connection = new SqlConnection(cb.ConnectionString))
                        {
                            connection.Open();


                            String queryx = "INSERT INTO dbo.data_co2 (datum, teplota, vlhkost, co2, senzorokno, senzorosoba) VALUES (@datum, @teplota, @vlhkost, @co2, @senzorokno, @senzorosoba)";

                            using (SqlCommand command = new SqlCommand(queryx, connection))
                            {
                                command.Parameters.AddWithValue("@datum", DateTime.Now);
                                command.Parameters.AddWithValue("@teplota", dsensortemp);
                                command.Parameters.AddWithValue("@vlhkost", dsensorhum);
                                command.Parameters.AddWithValue("@co2", dco2);
                                command.Parameters.AddWithValue("@senzorokno", 0);
                                command.Parameters.AddWithValue("@senzorosoba", 0);

                                //connection.Open();
                                int result = command.ExecuteNonQuery();

                                // Check Error
                                if (result < 0)
                                {
                                    Console.WriteLine("Error inserting data into Database!");
                                }
                            }
                        }
                    }
                    catch (SqlException e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                    //throw;
                }
            }
            else
            {
                Debug.WriteLine("Timer cancel!!!");

                timer.Cancel();
                //
                // Indicate that the background task has completed.
                //
                deferral.Complete();
            }
        }
Esempio n. 21
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // LCD - This screen is I2C
            IRgbLcdDisplay LCD = DeviceFactory.Build.RgbLcdDisplay();

            LCD.SetBacklightRgb(255, 255, 255);
            LCD.SetText("Hello world!"); // Not sure what colour this will show up in

            // LEDs
            ILed red  = DeviceFactory.Build.Led(Pin.DigitalPin2);
            ILed blue = DeviceFactory.Build.Led(Pin.DigitalPin3);

            // Ultrasonic
            IUltrasonicRangerSensor Ultrasonic = DeviceFactory.Build.UltraSonicSensor(Pin.DigitalPin4);

            // Temperature and Humidity
            // TODO: Double check Sensor model number. Assumed DHT11 from the GrovePi+ Starter Kit
            IDHTTemperatureAndHumiditySensor tempHumidity = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin5, DHTModel.Dht11);

            // Sound sensor
            ISoundSensor Sound = DeviceFactory.Build.SoundSensor(Pin.AnalogPin0);

            // LDR
            IRotaryAngleSensor LDR = DeviceFactory.Build.RotaryAngleSensor(Pin.AnalogPin1);

            while (true)
            {
                Task.Delay(100).Wait();

                try
                {
                    // Ultrasonic sensor
                    int distance = Ultrasonic.MeasureInCentimeters();
                    Debug.WriteLine("Distance: " + distance.ToString());
                    // TODO - tune to distance of door
                    //if(distance < 50)

                    // LDR
                    int lightLevel = LDR.SensorValue();
                    Debug.WriteLine("Light Level: " + lightLevel.ToString());

                    // LEDs
                    red.ChangeState(SensorStatus.On);
                    blue.ChangeState(SensorStatus.On);

                    // Temperature Humidity
                    tempHumidity.Measure();
                    double temp_degC = tempHumidity.TemperatureInCelsius;
                    double humidity  = tempHumidity.Humidity;
                    Debug.WriteLine("Temperature: " + temp_degC + "\tHumidity: " + humidity);

                    // Sound sensor
                    int soundLevel = Sound.SensorValue();
                    Debug.WriteLine("Sound Level: " + soundLevel);

                    // TODO: Send data to Azure
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }
Esempio n. 22
0
        private async void SendDeviceToCloudMessagesAsync()
        {
            var accessStatus = await Geolocator.RequestAccessAsync();

            double lat = 0;
            double lon = 0;

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:


                // If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
                Geolocator geolocator = new Geolocator {
                    DesiredAccuracyInMeters = 0
                };

                // Carry out the operation.
                Geoposition pos = await geolocator.GetGeopositionAsync();

                System.Diagnostics.Debug.WriteLine(pos);
                System.Diagnostics.Debug.WriteLine(pos.Coordinate.Latitude);
                System.Diagnostics.Debug.WriteLine(pos.Coordinate.Longitude);
                System.Diagnostics.Debug.WriteLine(pos.ToString());
                lat = pos.Coordinate.Latitude;
                lon = pos.Coordinate.Longitude;

                break;

            case GeolocationAccessStatus.Denied:

                break;

            case GeolocationAccessStatus.Unspecified:

                break;
            }

            while (true)
            {
                try
                {
                    // Check the value of the Sensor.
                    // Temperature in Celsius is returned as a double type.  Convert it to string so we can print it.
                    sensor.Measure();
                    sensorTemp = sensor.TemperatureInCelsius;
                    // Same for Humidity.
                    sensorHum = sensor.Humidity;

                    // Print all of the values to the debug window.
                    System.Diagnostics.Debug.WriteLine("Temp is " + sensorTemp + " C.  And the Humidity is " + sensorHum + "%. ");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("ERROR: " + ex);
                    // NOTE: There are frequent exceptions of the following:
                    // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '.
                    // This appears to be caused by the rapid frequency of writes to the GPIO
                    // These are being swallowed here/

                    // If you want to see the exceptions uncomment the following:
                    // System.Diagnostics.Debug.WriteLine(ex.ToString());
                }



                JsonValues telemetryDataPoint = new JsonValues
                {
                    Id          = DateTime.Now.ToString("yyyy-dd-M:hh:mm:ss"),
                    name        = "Pi1",
                    humidity    = sensorHum,
                    temperature = sensorTemp,
                    date        = DateTime.Now.ToString("dd.MM.yyyy"),
                    longitude   = lon,
                    latitude    = lat
                };

                System.Diagnostics.Debug.WriteLine(telemetryDataPoint);
                var messageString = JsonConvert.SerializeObject(telemetryDataPoint);

                var message = new Message(Encoding.ASCII.GetBytes(messageString));


                //await deviceClient.SendEventAsync(message);
                //UploadToAzureStorage(messageString);
                await SendAsync(telemetryDataPoint);

                Task.Delay(10000).Wait();
            }
        }
        private void InitWorker()
        {
            IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
                async(workItem) =>
            {
                int work_index = 0;

                int distance        = 0, sound = 0, light = 0, rotary = 0;
                SensorStatus button = SensorStatus.Off;
                SensorStatus buzzer = SensorStatus.Off;

                while (true)
                {
                    if (work_index < 5)
                    {
                        rotary = GroveRotary.SensorValue();
                        button = GroveButton.CurrentState;

                        //
                        RotaryValue = rotary;
                        int level   = RotaryValue / 100;
                        if (level > 10)
                        {
                            level = 10;
                        }
                        GroveLedBar.SetLevel((byte)level);

                        buzzer = GroveBuzzer.CurrentState;

                        if (RotaryValue > 1000)
                        {
                            if (buzzer != SensorStatus.On)
                            {
                                GroveBuzzer.ChangeState(SensorStatus.On);
                            }
                        }
                        else
                        {
                            if (buzzer != SensorStatus.Off)
                            {
                                GroveBuzzer.ChangeState(SensorStatus.Off);
                            }
                        }

                        if (button == SensorStatus.On)
                        {
                            RelayOnOff = 1;
                            GroveRelay.ChangeState(SensorStatus.On);
                        }
                        else
                        {
                            RelayOnOff = 0;
                            GroveRelay.ChangeState(SensorStatus.Off);
                        }

                        work_index++;
                    }
                    else
                    {
                        // Read temp & humidity
                        GroveTempHumi.Measure();
                        LastTemp = GroveTempHumi.TemperatureInCelsius;
                        LastHumi = GroveTempHumi.Humidity;

                        distance = GroveRanger.MeasureInCentimeters();
                        //System.Diagnostics.Debug.WriteLine(distance);

                        sound = GroveSound.SensorValue();
                        //System.Diagnostics.Debug.WriteLine(sound);

                        light = GroveLight.SensorValue();
                        //System.Diagnostics.Debug.WriteLine(light);

                        if (distance > 0 && distance < 100)
                        {
                            ShiftLeft(DistanceList, distance);
                        }

                        ShiftLeft(SoundList, sound);
                        ShiftLeft(LightList, light);

                        work_index = 0;
                    }

                    await Dispatcher.RunAsync(
                        CoreDispatcherPriority.High,
                        () =>
                    {
                        if (work_index == 0)
                        {
                            UpdataUISlow();
                        }
                        else
                        {
                            UpdateUIFast();
                        }
                    });

                    //Delay.Milliseconds(100);
                }
            }
                );
        }