def weatherConditions(key, lat, lon): f = Hammock( 'https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}&units=metric' .format(lat, lon, key)) weather = f.GET().json() current_observation = {} current_observation["temperature"] = weather['main']['temp'] current_observation["condition"] = weather['weather'][0]["main"] current_observation["humidity"] = weather['main']['humidity'] current_observation["cloud_cover"] = weather['clouds']['all'] return current_observation
def hourly(key, forecast_date, lat, lon): f = Hammock( 'https://api.openweathermap.org/data/2.5/forecast?lat={}&lon={}&appid={}&units=metric' .format(lat, lon, key)) hourly_forecast = f.GET().json() forecasts = hourly_forecast["list"] for forecast in forecasts: h = datetime.fromtimestamp(forecast["dt"]) if h - forecast_date < timedelta(hours=3): return forecast
class ParticleCloud(object): """ Provides access to the Particle cloud to call function, read variables, subscribe for events and publish events. """ def __init__(self, username_or_access_token, password=None, device_ids=None, api_prefix='https://api.particle.io/v1', **kwargs): """ :param username_or_access_token: if access token, then no password is required :param password: :param device_ids: list of device ids to consider. only these devices will be part of the dynamic API if None, then all device ids are pulled from Particle Cloud :param api_prefix: base url of API server, defaults to https://api.particle.io/v1 :param **kwargs: hammock session will be initiated with passed kwargs. So if you like to use an http proxy pass your proxies dictionary here """ self.particle_cloud_api = Hammock(api_prefix + "/devices", **kwargs) self.api_prefix = api_prefix if password is None: self.access_token = username_or_access_token else: self.access_token = self._login(username_or_access_token, password) self.device_ids = device_ids self._get_devices() @staticmethod def wait_forever(self): while True: try: time.sleep(3600) except: continue @staticmethod def _check_error(response): """Raises an exception if the Particle Cloud returned an error.""" if (not response.ok) or (response.status_code != 200): raise Exception( response.json()['error'] + ': ' + response.json()['error_description'] ) def _login(self, username, password): data = { 'username': username, 'password': password, 'grant_type': 'password' } # https://docs.particle.io/reference/api/ # You must give a valid client ID and password in HTTP Basic Auth. # For controlling your own developer account, you can use particle:particle. res = self.particle_cloud_api.oauth.token.POST(auth=('particle', 'particle'), data=data) self._check_error(res) return res.json()['access_token'] def _get_devices(self): """Create a dictionary of devices known to the user account.""" params = {'access_token': self.access_token} res = self.particle_cloud_api.GET(params=params) self._check_error(res) json_list = res.json() self.devices = {} if json_list: for d in json_list: if self.device_ids is None or (self.device_ids is not None and d['id'] in self.device_ids): info = self._get_device_info(d['id']) d['functions'] = info['functions'] d['variables'] = info['variables'] d['device_id'] = d['id'] # my preference is to call it device_id d['particle_device_api'] = self.particle_cloud_api(d['id']) d['access_token'] = self.access_token d['api_prefix'] = self.api_prefix self.devices[d['name']] = _ParticleDevice(**d) def _get_device_info(self, device_id): """ Queries the Particle Cloud for detailed information about a device. """ params = {'access_token': self.access_token} r = self.particle_cloud_api(device_id).GET(params=params) self._check_error(r) return r.json() def __getattr__(self, name): """ Returns a Device object as an attribute of the ParticleCloud object. accessed like: particle_cloud_variable.device_name """ if name in self.devices: return self.devices[name] else: raise AttributeError()