bremor / bureau_of_meteorology

Custom component for retrieving weather information from the Bureau of Meteorology.
MIT License
190 stars 31 forks source link

How to update location automatically #176

Closed alexdobo closed 1 year ago

alexdobo commented 1 year ago

Is it possible to update the location based on a GPS?

My Home Assistant is in a caravan, and I'd like to be able to get the weather for my current location.

Is there a config file I can change the location in?

anthonykeane commented 1 year ago

I would also welcome this as a feature

alexdobo commented 1 year ago

I've been able to get it to auto update location by adding the following code into sensor.py

    async def async_added_to_hass(self) -> None:
        """Set up a listener and load data."""
        self.async_on_remove(self.coordinator.async_add_listener(self._update_callback))
        self.async_on_remove(self.coordinator.async_add_listener(self._update_callback))
        self._update_callback()

#New code here

        # Schedule periodic updates of latitude and longitude
        self._latitude_task = asyncio.create_task(self._update_latitude_periodically())
        self._longitude_task = asyncio.create_task(self._update_longitude_periodically())

    async def _update_latitude_periodically(self) -> None:
        """Periodically update the latitude value."""
        while True:
            latitude = self.get_latitude()
            self.collector.locations_data["data"]["latitude"] = latitude
            _LOGGER.info("Updated latitude: %s", latitude)
            await asyncio.sleep(60)  # Update every minute

    async def _update_longitude_periodically(self) -> None:
        """Periodically update the longitude value."""
        while True:
            longitude = self.get_longitude()
            self.collector.locations_data["data"]["longitude"] = longitude
            _LOGGER.info("Updated longitude: %s", longitude)
            await asyncio.sleep(60)  # Update every minute

    def get_latitude(self):
        # Get the current latitude from Home Assistant
        return self.hass.config.latitude

    def get_longitude(self):
        # Get the current longitude from Home Assistant
        return self.hass.config.longitude 
alexdobo commented 1 year ago

Correction, that didn't work. Instead modify the init.py file with:

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up BOM from a config entry."""
    lat = hass.config.latitude
    lon = hass.config.longitude
    collector = Collector(lat,lon)
    _LOGGER.info("Latitude: %s, Longitude: %s", lat, lon)