// Update Devices, updateType decides what to update.
        // 0 = All
        // 1 = Switches and Sensors
        // 2 = Rooms
        public async Task UpdateDevices(int updateType = 0)
        {
            if (!(bool)localSettings.Values["refreshRunning"])
            {
                localSettings.Values["refreshRunning"] = true;
                if (updateType == 0 || updateType == 1)
                {
                    URLActions domoticzData = new URLActions();
                    string result = await domoticzData.LoadAllUsedDevices();

                    if (result != null && result != "false")
                    {
                        ProcessDeviceOverview(result);
                        localSettings.Values["hostSettingsLoadedSuccesfully"] = true;
                    }
                    else
                    {
                        if (localSettings.Values["connectionFailedAmount"] == null && (int)localSettings.Values["connectionFailedAmount"] < 3)
                        {
                            bool connectionStatus = await domoticzData.TestConnection();
                            if (connectionStatus)
                            {
                                result = await domoticzData.LoadAllUsedDevices();
                                if (result != null && result != "false")
                                {
                                    ProcessDeviceOverview(result);
                                    localSettings.Values["hostSettingsLoadedSuccesfully"] = true;
                                }
                                else
                                {
                                    localSettings.Values["connectionFailedAmount"] = (int)localSettings.Values["connectionFailedAmount"] + 1;
                                    localSettings.Values["refreshRunning"] = false;
                                    return;
                                }
                            }
                            else
                            {
                                localSettings.Values["refreshRunning"] = false;
                                return;
                            }
                        }
                        else
                        {
                            localSettings.Values["refreshRunning"] = false;
                            return;
                        }
                    }

                    int deviceOrder = 0;

                    // Update Switches
                    foreach (Switch Switch in Switches)
                    {
                        deviceOrder++;
                        bool valid = true;

                        if (string.IsNullOrEmpty(Switch.Name))
                        {
                            valid = false;
                        }
                        else
                        {
                            Device t = store.Devices.Where(p => p.Idx == Switch.Idx.Trim()).FirstOrDefault();

                            if (t == null)
                            {
                                Device = new Device();
                                Device.Idx = Switch.Idx.Trim();
                                Device.Name = Switch.Name.Trim();
                                Device.Description = Switch.Name.Trim();
                                Device.DeviceType = Switch.Type.Trim();
                                Device.AddDate = DateTime.Now;
                                Device.LastSeenDate = Convert.ToDateTime(Switch.LastUpdate);

                                Device.Used = Switch.Used;
                                Device.Favorite = Switch.Favorite;

                                Device.PlanId = Switch.PlanId;
                                Device.Image = Switch.Image;
                                Device.Order = deviceOrder;

                                Device.Status = Switch.Status;
                                Device.Unit = Switch.Unit;

                                Device.SwitchType = Switch.SwitchType;
                                Device.SwitchTypeVal = Switch.SwitchTypeVal;

                                if (Switch.SwitchTypeVal == 7)
                                {
                                    Device.Level = Switch.Level;
                                    Device.LevelInt = Switch.LevelInt;
                                    Device.MaxDimLevel = Switch.MaxDimLevel;
                                }

                                Device.SwitchProtected = Switch.IsProtected;

                                if (valid)
                                {
                                    await store.SaveDevice(Device);
                                }
                            }
                            else
                            {
                                t.Name = Switch.Name.Trim();
                                t.Description = Switch.Name.Trim();

                                t.LastSeenDate = Convert.ToDateTime(Switch.LastUpdate);

                                t.Used = Switch.Used;
                                t.Favorite = Switch.Favorite;

                                t.PlanId = Switch.PlanId;
                                t.Image = Switch.Image;
                                t.Order = deviceOrder;

                                t.Status = Switch.Status;
                                t.Unit = Switch.Unit;

                                t.SwitchType = Switch.SwitchType;
                                t.SwitchTypeVal = Switch.SwitchTypeVal;

                                if (Switch.SwitchTypeVal == 7)
                                {
                                    t.Level = Switch.Level;
                                    t.LevelInt = Switch.LevelInt;
                                    t.MaxDimLevel = Switch.MaxDimLevel;
                                }

                                t.SwitchProtected = Switch.IsProtected;

                                await store.SaveDevice(t);
                            }

                        }
                    }
                    switches = null;

                    // Update Temperature + Humidity Devices
                    foreach (Sensor Sensor in Sensors)
                    {
                        deviceOrder++;
                        bool valid = true;

                        if (string.IsNullOrEmpty(Sensor.Name))
                        {
                            valid = false;
                        }
                        else
                        {
                            Device t = store.Devices.Where(p => p.Idx == Sensor.Idx.Trim()).FirstOrDefault();

                            if (t == null)
                            {
                                Device = new Device();
                                Device.Idx = Sensor.Idx.Trim();
                                Device.Name = Sensor.Name.Trim();
                                Device.Description = Sensor.Name.Trim();
                                Device.DeviceType = Sensor.Type.Trim();
                                Device.AddDate = DateTime.Now;
                                Device.LastSeenDate = Convert.ToDateTime(Sensor.LastUpdate);
                                Device.Unit = Sensor.Unit;
                                Device.Used = Sensor.Used;
                                Device.Favorite = Sensor.Favorite;
                                Device.Order = deviceOrder;

                                if (Sensor.Type == "Temp")
                                {
                                    Device.Temp = Sensor.Temp;
                                }
                                if (Sensor.Type == "Humidity")
                                {
                                    Device.Humidity = Sensor.Humidity;
                                }
                                else if (Sensor.Type == "Temp + Humidity")
                                {
                                    Device.Temp = Sensor.Temp;
                                    Device.Humidity = Sensor.Humidity;
                                }
                                else if (Sensor.Type == "Rain" || Sensor.Type == "UV" || Sensor.Type == "Wind")
                                {
                                    Device.Data = Sensor.Data;
                                }
                                else if (Sensor.Type == "General" || Sensor.Type == "Current" || Sensor.Type == "RFXMeter" || Sensor.Type == "Usage")
                                {
                                    Device.SubType = Sensor.SubType;
                                    Device.Data = Sensor.Data;
                                }

                                if (valid)
                                {
                                    await store.SaveDevice(Device);
                                }
                            }
                            else
                            {
                                t.Name = Sensor.Name.Trim();
                                t.Description = Sensor.Name.Trim();

                                t.LastSeenDate = Convert.ToDateTime(Sensor.LastUpdate);

                                t.Used = Sensor.Used;
                                t.Favorite = Sensor.Favorite;
                                t.Order = deviceOrder;
                                t.Unit = Sensor.Unit;

                                if (Sensor.Type == "Temp")
                                {
                                    t.Temp = Sensor.Temp;
                                }
                                if (Sensor.Type == "Humidity")
                                {
                                    t.Humidity = Sensor.Humidity;
                                }
                                else if (Sensor.Type == "Temp + Humidity")
                                {
                                    t.Temp = Sensor.Temp;
                                    t.Humidity = Sensor.Humidity;
                                }
                                else if (Sensor.Type == "Rain" || Sensor.Type == "UV" || Sensor.Type == "Wind")
                                {
                                    t.Data = Sensor.Data;
                                }
                                else if (Sensor.Type == "General" || Sensor.Type == "Current" || Sensor.Type == "RFXMeter" || Sensor.Type == "Usage")
                                {
                                    t.SubType = Sensor.SubType;
                                    t.Data = Sensor.Data;
                                }

                                await store.SaveDevice(t);
                            }

                        }
                    }
                    sensors = null;
                }

                if (updateType == 0 || updateType == 2)
                {
                    //
                    // Load Rooms
                    //
                    URLActions domoticzData = new URLActions();
                    string result = await domoticzData.LoadRooms();

                    if (result != null && result != "false")
                    {
                        localSettings.Values["availableRooms"] = result;
                    }

                    result = null;
                }

                localSettings.Values["refreshRunning"] = false;
            }
        }
        /// <summary>
        /// Add a device to the persistent device store, and saves the devices data file.
        /// </summary>
        /// <param name="device">The device to save or update in the data file.</param>
        public async Task SaveDevice(Device device)
        {
            if (!Devices.Contains(device))
            {
                Devices.Add(device);
            }

            await WriteDevices();
        }
        /// <summary>
        /// Load devices from a file on first-launch of the app. If the file does not yet exist,
        /// pre-seed it with a device, in order to give the app demonstration data.
        /// </summary>
        public async Task LoadDevices()
        {
            // Ensure that we don't load device data more than once.
            if (loaded)
            {
                return;
            }
            loaded = true;

            StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
            this.devices.Clear();

            var item = await folder.TryGetItemAsync("devices.xml");
            if (item == null)
            {
                // Add some 'starter' devices
                devices.Add(
                    new Device()
                    {
                        Idx = "1",
                        Name = "Example Device",
                        Description = "Light above TV",
                        DeviceType = "Lighting 2",
                        AddDate = new DateTime(2015, 12, 12),
                        LastSeenDate = new DateTime(2015, 12, 12)
                    });
                await WriteDevices();
                return;
            }

            // Load devices out of a simple XML format.
            if (item.IsOfType(StorageItemTypes.File))
            {
                StorageFile deviceFile = item as StorageFile;

                string deviceXmlText = await FileIO.ReadTextAsync(deviceFile);

                try
                {
                    XElement xmldoc = XElement.Parse(deviceXmlText);

                    var deviceElements = xmldoc.Descendants("Device");
                    foreach (var deviceElement in deviceElements)
                    {
                        Device device = new Device();

                        var idxElement = deviceElement.Descendants("Idx").FirstOrDefault();
                        if (idxElement != null)
                        {
                            device.Idx = idxElement.Value;
                        }

                        var nameElement = deviceElement.Descendants("Name").FirstOrDefault();
                        if (nameElement != null)
                        {
                            device.Name = nameElement.Value;
                        }

                        var descElement = deviceElement.Descendants("Description").FirstOrDefault();
                        if (descElement != null)
                        {
                            device.Description = descElement.Value;
                        }

                        var devTypeElement = deviceElement.Descendants("DeviceType").FirstOrDefault();
                        if (devTypeElement != null)
                        {
                            device.DeviceType = devTypeElement.Value;
                        }

                        var addElement = deviceElement.Descendants("AddDate").FirstOrDefault();
                        if (addElement != null)
                        {
                            DateTime addDate;
                            if (DateTime.TryParse(addElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out addDate))
                            {
                                device.AddDate = addDate;
                            }
                            else
                            {
                                device.AddDate = null;
                            }
                        }

                        var lastSeenElement = deviceElement.Descendants("LastSeenDate").FirstOrDefault();
                        if (lastSeenElement != null)
                        {
                            DateTime lastSeenDate;
                            if (DateTime.TryParse(lastSeenElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out lastSeenDate))
                            {
                                device.LastSeenDate = lastSeenDate;
                            }
                            else
                            {
                                device.LastSeenDate = null;
                            }
                        }

                        var usedElement = deviceElement.Descendants("Used").FirstOrDefault();
                        if (usedElement != null)
                        {
                            device.Used = Int32.Parse(usedElement.Value);
                        }

                        var favoriteElement = deviceElement.Descendants("Favorite").FirstOrDefault();
                        if (favoriteElement != null)
                        {
                            device.Favorite = Int32.Parse(favoriteElement.Value);
                        }

                        var planIdElement = deviceElement.Descendants("PlanId").FirstOrDefault();
                        if (planIdElement != null)
                        {
                            device.PlanId = planIdElement.Value;
                        }

                        var imageElement = deviceElement.Descendants("Image").FirstOrDefault();
                        if (imageElement != null)
                        {
                            device.Image = imageElement.Value;
                        }

                        var orderElement = deviceElement.Descendants("Order").FirstOrDefault();
                        if (orderElement != null)
                        {
                            device.Order = Int32.Parse(orderElement.Value);
                        }

                        var statusElement = deviceElement.Descendants("Status").FirstOrDefault();
                        if (statusElement != null)
                        {
                            device.Status = statusElement.Value;
                        }

                        var tempElement = deviceElement.Descendants("Temp").FirstOrDefault();
                        if (tempElement != null)
                        {
                            device.Temp = Double.Parse(tempElement.Value);
                        }

                        var humidityElement = deviceElement.Descendants("Humidity").FirstOrDefault();
                        if (humidityElement != null)
                        {
                            device.Humidity = Int32.Parse(humidityElement.Value);
                        }

                        var unitElement = deviceElement.Descendants("Unit").FirstOrDefault();
                        if (unitElement != null)
                        {
                            device.Unit = Int32.Parse(unitElement.Value);
                        }

                        var switchTypeElement = deviceElement.Descendants("SwitchType").FirstOrDefault();
                        if (switchTypeElement != null)
                        {
                            device.SwitchType = switchTypeElement.Value;
                        }

                        var switchProtectedElement = deviceElement.Descendants("SwitchProtected").FirstOrDefault();
                        if (switchProtectedElement != null)
                        {
                            device.SwitchProtected = bool.Parse(switchProtectedElement.Value);
                        }

                        var switchTypeValElement = deviceElement.Descendants("SwitchTypeVal").FirstOrDefault();
                        if (switchTypeValElement != null)
                        {
                            device.SwitchTypeVal = Int32.Parse(switchTypeValElement.Value);
                        }

                        var levelElement = deviceElement.Descendants("Level").FirstOrDefault();
                        if (levelElement != null)
                        {
                            device.Level = Int32.Parse(levelElement.Value);
                        }

                        var levelIntElement = deviceElement.Descendants("LevelInt").FirstOrDefault();
                        if (levelIntElement != null)
                        {
                            device.LevelInt = Int32.Parse(levelIntElement.Value);
                        }

                        var maxDimLevelElement = deviceElement.Descendants("MaxDimLevel").FirstOrDefault();
                        if (maxDimLevelElement != null)
                        {
                            device.MaxDimLevel = Int32.Parse(maxDimLevelElement.Value);
                        }

                        var subTypeElement = deviceElement.Descendants("SubType").FirstOrDefault();
                        if (subTypeElement != null)
                        {
                            device.SubType = subTypeElement.Value;
                        }

                        var dataElement = deviceElement.Descendants("Data").FirstOrDefault();
                        if (dataElement != null)
                        {
                            device.Data = dataElement.Value;
                        }

                        var showOnDashElement = deviceElement.Descendants("ShowOnDash").FirstOrDefault();
                        if (showOnDashElement != null)
                        {
                            device.ShowOnDash = bool.Parse(showOnDashElement.Value);
                        }

                        Devices.Add(device);
                    }
                }
                catch (XmlException ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                    return;
                }

            }
        }
 /// <summary>
 /// Delete a device from the persistent device store, and save the devices file.
 /// </summary>
 /// <param name="device">The device to delete. If the device is not an existing device in the store,
 /// will not have an effect.</param>
 public async Task DeleteDevice(Device device)
 {
     Devices.Remove(device);
     await WriteDevices();
 }