def get_weather_data(self, **kwargs): weather = kwargs.get('weather_data', False) if not weather: amb_api = AmbientAPI() devices = amb_api.get_devices() if len(devices) > 0: device = devices[0] weather = device.last_data if weather and isinstance(weather, dict): # Prepare the data, which will be sent self.wx_data = self.make_aprs_wx( wind_dir=weather.get('winddir'), wind_speed=float(weather.get('windspeedmph')), wind_gust=float(weather.get('windgustmph')), temperature=weather.get('tempf'), rain_last_hr=weather.get('hourlyrainin'), rain_last_24_hrs=None, rain_since_midnight=weather.get('dailyrainin'), humidity=weather.get('humidity'), # Attention, barometric pressure in tenths of millibars/tenths of hPascal! pressure=self.hg_to_mbar(weather.get('baromabsin'))) return self.wx_data
class AmbientStationData: """Class to interface with ambient-api library.""" def __init__(self, hass, api_key, app_key): """Initialize station data object.""" self.hass = hass self._api_keys = { 'AMBIENT_ENDPOINT': 'https://api.ambientweather.net/v1', 'AMBIENT_API_KEY': api_key, 'AMBIENT_APPLICATION_KEY': app_key, 'log_level': 'DEBUG' } self.data = None self._station = None self._api = None self._devices = None self.connect_success = False self.get_data = Throttle(SCAN_INTERVAL)(self.async_update) self._connect_api() # attempt to connect to API async def async_update(self): """Get new data.""" # refresh API connection since servers turn over nightly _LOGGER.debug("Getting new data from server") new_data = None await self.hass.async_add_executor_job(self._connect_api) await asyncio.sleep(2) # need minimum 2 seconds between API calls if self._station is not None: data = await self.hass.async_add_executor_job( self._station.get_data) if data is not None: new_data = data[0] self.data = new_data else: _LOGGER.debug("data is None type") else: _LOGGER.debug("Station is None type") return new_data def _connect_api(self): """Connect to the API and capture new data.""" from ambient_api.ambientapi import AmbientAPI self._api = AmbientAPI(**self._api_keys) self._devices = self._api.get_devices() if self._devices: self._station = self._devices[0] if self._station is not None: self.connect_success = True else: _LOGGER.debug("No station devices available")
from ambient_api.ambientapi import AmbientAPI import time AMBIENT_ENDPOINT = "https://api.ambientweather.net/v1" AMBIENT_API_KEY = '8f50cfbcc72e421b9cce87bd28f051fc56d6a85cf31e4bc8bc746912bd080fa8' AMBIENT_APPLICATION_KEY = 'ded210ad609a4cdcb77f734956f89d06d5393923d94d4210a83c736667f4e304' api = AmbientAPI() devices = api.get_devices() print(devices) #device = devices[0] # #print (device.get_data())
import pprint from ambient_api.ambientapi import AmbientAPI weather = AmbientAPI() devices = weather.get_devices() for device in devices: print(str(device)) pprint.pprint(device.last_data) pprint.pprint(device.get_data())
def get_weather(): weather = AmbientAPI() devices = weather.get_devices() utc_timezone = pytz.timezone("UTC") local_timezone = pytz.timezone(settings.TIME_ZONE) for device in devices: try: station = WeatherStation.objects.get( mac_address=device.mac_address) except WeatherStation.DoesNotExist: station = WeatherStation.objects.create( name=device.info.get("name"), location=device.info.get("location"), mac_address=device.mac_address) log_message("Weather Station created: %s (%s)" % (station.mac_address, station.name)) if station.enabled: last_data = device.last_data current_conditions = convert_keys(last_data) parsed_date = parse(current_conditions["date"]) current_conditions["date"] = parsed_date.astimezone(utc_timezone) current_conditions["local_date"] = parsed_date.astimezone( local_timezone) current_conditions["station"] = station pprint.pprint(current_conditions) try: current_data = WeatherData.objects.get( station=station, date=current_conditions.get("date")) except WeatherData.DoesNotExist: try: current_data = WeatherData.objects.create( **current_conditions) log_message( "Current weather data collected on %s from %s (%s)" % (current_data.date, current_data.station.mac_address, current_data.station.name)) except TypeError as e: current_data = WeatherData.objects.create( station=station, baromabsin=current_conditions.get("baromabsin"), baromrelin=current_conditions.get("baromrelin"), dailyrainin=current_conditions.get("dailyrainin"), local_date=current_conditions.get("local_date"), date=current_conditions.get("date"), dateutc=current_conditions.get("dateutc"), dew_point=current_conditions.get("dew_point"), eventrainin=current_conditions.get("eventrainin"), feels_like=current_conditions.get("feels_like"), hourlyrainin=current_conditions.get("hourlyrainin"), humidity=current_conditions.get("humidity"), humidityin=current_conditions.get("humidityin"), last_rain=current_conditions.get("last_rain"), maxdailygust=current_conditions.get("maxdailygust"), monthlyrainin=current_conditions.get("monthlyrainin"), solarradiation=current_conditions.get( "solarradiation"), tempf=current_conditions.get("tempf"), tempinf=current_conditions.get("tempinf"), totalrainin=current_conditions.get("totalrainin"), uv=current_conditions.get("uv"), weeklyrainin=current_conditions.get("weeklyrainin"), winddir=current_conditions.get("winddir"), windgustmph=current_conditions.get("windgustmph"), windspeedmph=current_conditions.get("windspeedmph"), windspdmph_avg10m=current_conditions.get( "windspdmph_avg10m"), ) log_message( "Current weather data collected on %s from %s (%s)" % (current_data.date, current_data.station.mac_address, current_data.station.name)) log_message("New field found in data. (%s)" % e) for past_data in device.get_data(): past_data = convert_keys(past_data) past_data["station"] = station past_date = parse(past_data["date"]) past_data["date"] = past_date.astimezone(utc_timezone) past_data["local_date"] = past_date.astimezone(local_timezone) try: past_entry = WeatherData.objects.get( station=station, date=past_data.get("date")) except WeatherData.DoesNotExist: past_entry = WeatherData.objects.create(**past_data) log_message("Past weather data collected for %s from %s (%s)" % (past_entry.date, past_entry.station.mac_address, past_entry.station.name)) aprs = AmbientAPRS( station_id=station.name, latitude=station.latitude, longitude=station.longitude # 43.131258, # -76.155028 ) weather_data = aprs.get_weather_data(weather_data=last_data) packet = aprs.build_packet() is_aprs = aprs.send_packet() if not is_aprs: log_message("APRS Packet failed to send.") log_message("%s %s %s" % (aprs.station_id, aprs.address, aprs.position)) log_message(aprs.packet_data) log_message(packet) log_message(weather_data) else: log_message("APRS Packet sent successfully.")
def genLoopPackets(self): logging.debug("calling: genLoopPackets") while True: # Query the API to get the latest reading. try: error_occured = False logging.debug("starting getLoopPackets") # Adding an extra buffer so the API throttle limit isn't hit logging.debug( "sleeping an extra 3 seconds to not hit API throttle limit." ) time.sleep(3) # init the API weather = AmbientAPI(AMBIENT_ENDPOINT=self.api_url, AMBIENT_API_KEY=self.api_key, AMBIENT_APPLICATION_KEY=self.api_app_key) logging.debug("Init API call returned") # get the first device devices = weather.get_devices() logging.debug("Got weather devices") if not devices: logging.error( 'AmbientAPI get_devices() returned empty dict') raise Exception( 'AmbientAPI get_devices() returned empty dict') else: logging.debug('Weather get_devices() payload not empty') # get the last report dict data = devices[0].last_data # info = devices[0].info logging.debug("Got last report") # Convert the epoch to the format weewx wants. current_observation = self.convert_epoch_ms_to_sec( data["dateutc"]) # output the observation self.print_dict(data) except Exception as e: syslog.syslog(DRIVER_NAME + " driver encountered an error.") logging.error(DRIVER_NAME + " driver encountered an error.") syslog.syslog("Error caught was: %s" % e) logging.error("Error caught was: %s" % e) error_occured = True # build the packet data try: logging.debug("============Starting Packet Build============") if error_occured: error_occured = False raise Exception( 'Previous error occured, skipping packet build.') dailyrainin = 0.0 # Check the API for dai if 'dailyrainin' in data.keys(): dailyrainin = self.get_float(data['dailyrainin']) # Create the initial packet dict _packet = { 'dateTime': current_observation, 'usUnits': weewx.US, 'rain': self.check_rain_rate(dailyrainin), } # Key is weewx packet, value is Ambient value # Loop the values in the mapping and look for actual values in the API data mapping = self.get_packet_mapping() for key, value in mapping.items(): is_battery = value.startswith('batt') if value in data: logging.debug( "Setting Weewx value: '%s' to: %s using Ambient field: '%s'" % (key, str(data[value]), value)) if is_battery: _packet[key] = self.get_battery_status(data[value]) else: _packet[key] = self.get_float(data[value]) else: logging.debug( "Dropping Ambient value: '%s' from Weewx packet." % (value)) self.print_dict(_packet) logging.debug("============Completed Packet Build============") yield _packet logging.info("loopPacket Accepted") except Exception as e: syslog.syslog(DRIVER_NAME + " driver had an error sending data to weewx.") logging.error(DRIVER_NAME + " driver had an error sending data to weewx.") syslog.syslog("Error caught was: %s" % e) logging.error("Error caught was: %s" % e) # Sleepy Time logging.debug("Going to sleep") time.sleep(self.loop_interval) logging.debug("Mom, I'm up!")