def __init__(self): # read the config file self.config_data = open('/home/pi/WeatherPi/config.json').read() self.config = json.loads(self.config_data) log_string('config file read by module {}'.format(self.__class__))
def check_alarms(): weather = Data().api_data alarms = {} try: alarm_weather = weather['alerts'] Alarm = namedtuple('Alarm', ['severity', 'title', 'start_time', 'expires', 'duration', 'lasts', 'description']) for idx, alarm_obj in enumerate(alarm_weather): severity, title, time_start, expires, description = alarm_obj['severity'], alarm_obj['title'], \ alarm_obj['time'], alarm_obj['expires'], \ alarm_obj['description'].encode('UTF-8') alarm_start_time = time_convert(int(time_start)) alarm_expire_time = time_convert(int(expires)) alarm_duration = str(datetime.fromtimestamp(expires) - datetime.fromtimestamp(time_start)) alarm_lasts = (datetime.fromtimestamp(expires) - datetime.fromtimestamp(time.time())).seconds / 60.0 / 60.0 alarm_lasts = int(round(alarm_lasts, 0)) alarm = Alarm(str(severity), str(title), alarm_start_time, alarm_expire_time, alarm_duration, alarm_lasts, str(description)) if alarm.severity == 'warning': log_string('warning Alarm: {}'.format(alarm)) alarms[idx] = {'severity': alarm.severity, 'duration': alarm_lasts} elif alarm.severity == 'watch': log_string('watch Alarm: {}'.format(alarm)) alarms[idx] = {'severity': alarm.severity, 'duration': alarm_lasts} elif alarm.severity == 'advisory': log_string('watch Alarm: {}'.format(alarm)) alarms[idx] = {'severity': alarm.severity, 'duration': alarm_lasts} else: alarms = None log_string('Alle Wetter Alarme: {}'.format(alarms)) return alarms except KeyError: log_string('no weather alerts') return None
def temp_inside(self): sensor_temp_inside = self.sensor_temp_wohnzimmer output_temp = str(int(round(sensor_temp_inside))).zfill(2) the_output_data = digits[output_temp[0]] + digits[output_temp[1]] + \ temp_digits[self.unit[0]] + temp_digits[self.Celsius[0]] log_string('Temperature Inside: {}°C'.format(output_temp)) return the_output_data
def json_data(self, path): try: log_string('read data from path: {}'.format(path)) data = open(path).read() json_data = json.loads(data) return json_data except IOError: log_string('ERROR - file read by module'.format(self.__class__))
def rain_probability(self): rain_probability = self.rain_percentage_data # json_data['currently']['precipProbability'] rain_probability *= 100 log_string('Regenwahrscheinlichkeit: {}%'.format(rain_probability)) rain_probability_data = str(int(round(rain_probability))).zfill(2) log_string('Regenwahrscheinlichkeit als String für Output: {}%'.format(rain_probability_data)) the_output_data = digits[rain_probability_data[0]] + digits[rain_probability_data[1]] + temp_digits[self.percent[0]] return the_output_data
def rain_probability(self): rain_probability = self.rain_percentage_data # json_data['currently']['precipProbability'] rain_probability *= 100 log_string('Regenwahrscheinlichkeit: {}%'.format(rain_probability)) rain_probability_data = str(int(round(rain_probability))).zfill(2) log_string('Regenwahrscheinlichkeit als String für Output: {}%'.format( rain_probability_data)) the_output_data = digits[rain_probability_data[0]] + digits[ rain_probability_data[1]] + temp_digits[self.percent[0]] return the_output_data
def rain_forecast(self): percentage_list = [] color_list = [] hourly_data = self.hourly_data for item in hourly_data: rain_percentage = item['precipProbability'] * 100 percentage_list.append(round(rain_percentage)) color = 0 for percentage in percentage_list[:self.forecast_range_hour]: if percentage == 0: color = "G" # GREEN elif 0 < percentage <= 30: color = "Y" # YELLOW elif 31 <= percentage <= 100: color = "R" # RED color_list.append(color) green_list = [i for i, color in enumerate(color_list) if color == "G"] yellow_list = [i for i, color in enumerate(color_list) if color == "Y"] red_list = [i for i, color in enumerate(color_list) if color == "R"] the_output_data = { "GREEN": green_list, "YELLOW": yellow_list, "RED": red_list } log_string('Regenwahrscheinlichkeit 24h: {}\n' 'Farben auf Display: {}\n' 'Farbenliste als Array: {}'.format( percentage_list[:self.forecast_range_hour], color_list, the_output_data )) return the_output_data
def __init__(self): log_string('Run Update module by: {}'.format(self.__class__)) # set the configs self.config = Config().get_config() # parameter for the api request.rqst url self.FORECAST_IO_KEY = self.config['FORECAST_IO_KEY'] self.LATITUDE = self.config['LATITUDE'] self.LONGITUDE = self.config['LONGITUDE'] self.FORECAST_URL = 'https://api.forecast.io/forecast/' # endpoint for the API self.options = '?lang=de&units=si&exclude=flags' # some options, see details in API documentation # parameter for the sensor request.rqst url self.username = self.config['NETATMO_USERNAME'] self.password = self.config['NETATMO_PASSWORD'] self.client_id = self.config['NETATMO_CLIENT_ID'] self.client_secret = self.config['NETATMO_CLIENT_SECRET'] self.device_id = self.config['NETATMO_DEVICE_ID']
def auth_netatmo(self): payload = { 'grant_type': 'password', 'username': self.username, 'password': self.password, 'client_id': self.client_id, 'client_secret': self.client_secret, 'scope': 'read_station' } try: response = requests.post("https://api.netatmo.com/oauth2/token", data=payload) response.raise_for_status() access_token = response.json()["access_token"] refresh_token = response.json()["refresh_token"] scope = response.json()["scope"] print("Your access token is:", access_token) print("Your refresh token is:", refresh_token) print("Your scopes are:", scope) log_string('tokens generated') return access_token except requests.exceptions.HTTPError as error: log_string(error.response.status_code) log_string(error.response.text)
def rain_forecast(self): percentage_list = [] color_list = [] hourly_data = self.hourly_data for item in hourly_data: rain_percentage = item['precipProbability'] * 100 percentage_list.append(round(rain_percentage)) color = 0 for percentage in percentage_list[:self.forecast_range_hour]: if percentage == 0: color = "G" # GREEN elif 0 < percentage <= 30: color = "Y" # YELLOW elif 31 <= percentage <= 100: color = "R" # RED color_list.append(color) green_list = [i for i, color in enumerate(color_list) if color == "G"] yellow_list = [i for i, color in enumerate(color_list) if color == "Y"] red_list = [i for i, color in enumerate(color_list) if color == "R"] the_output_data = { "GREEN": green_list, "YELLOW": yellow_list, "RED": red_list } log_string('Regenwahrscheinlichkeit 24h: {}\n' 'Farben auf Display: {}\n' 'Farbenliste als Array: {}'.format( percentage_list[:self.forecast_range_hour], color_list, the_output_data)) return the_output_data
def auth_netatmo(self): payload = {'grant_type': 'password', 'username': self.username, 'password': self.password, 'client_id': self.client_id, 'client_secret': self.client_secret, 'scope': 'read_station'} try: response = requests.post("https://api.netatmo.com/oauth2/token", data=payload) response.raise_for_status() access_token = response.json()["access_token"] refresh_token = response.json()["refresh_token"] scope = response.json()["scope"] print("Your access token is:", access_token) print("Your refresh token is:", refresh_token) print("Your scopes are:", scope) log_string('tokens generated') return access_token except requests.exceptions.HTTPError as error: log_string(error.response.status_code) log_string(error.response.text)
def update_api(self): log_string('get latest weather from forecast.io') api_request_url = self.FORECAST_URL + self.FORECAST_IO_KEY + '/' + str(self.LATITUDE) + ',' + \ str(self.LONGITUDE) + self.options log_string('build request url: {}'.format(api_request_url)) try: log_string('Try to get data online...') data = requests.get(api_request_url, timeout=5).json() # save data dict as json file with open('/home/pi/WeatherPi/logs/api.json', 'w') as outputfile: json.dump(data, outputfile, indent=2, sort_keys=True) log_string('json data saved to temporary file') blink('white') except StandardError: log_string('ConnectionError - fallback to cached Data')
def update_sensors(self): payload = { 'access_token': self.auth_netatmo(), 'device_id': self.device_id } try: response = requests.post("https://api.netatmo.com/api/getstationsdata", params=payload) response.raise_for_status() data = response.json()["body"] # save data dict as json file with open('/home/pi/WeatherPi/logs/sensors.json', 'w') as outputfile: json.dump(data, outputfile, indent=2, sort_keys=True) log_string('sensor data saved to /logs') return data except requests.exceptions.HTTPError as error: log_string(error.response.status_code) log_string(error.response.text)
def update_sensors(self): payload = { 'access_token': self.auth_netatmo(), 'device_id': self.device_id } try: response = requests.post( "https://api.netatmo.com/api/getstationsdata", params=payload) response.raise_for_status() data = response.json()["body"] # save data dict as json file with open('/home/pi/WeatherPi/logs/sensors.json', 'w') as outputfile: json.dump(data, outputfile, indent=2, sort_keys=True) log_string('sensor data saved to /logs') return data except requests.exceptions.HTTPError as error: log_string(error.response.status_code) log_string(error.response.text)
def __init__(self): log_string('Run Update module by: {}'.format(self.__class__)) # set the configs self.config = Config().get_config() self.api_path = '/home/pi/WeatherPi/logs/api.json' self.api_data = self.json_data(self.api_path) # self.test_path = '/home/pi/WeatherPi/logs/test_weather_with_alarm.json' self.sensor_path = '/home/pi/WeatherPi/logs/sensors.json' self.sensor_data = self.json_data(self.sensor_path) # api data self.api_time = self.api_data['currently']['time'] self.temp_api = self.api_data['currently']['temperature'] self.rain_percentage_data = self.api_data['currently']['precipProbability'] self.rain_percentage = self.rain_percentage_data * 100 self.forecast = self.api_data['currently']['summary'].encode('UTF-8') self.weather_icon = self.api_data['currently']['icon'] self.hourly_data = self.api_data['hourly']['data'] self.hourly_forecast = self.api_data['hourly']['summary'] self.daily = self.api_data['daily']['data'] self.forecast_today = self.daily[0] self.temp_range_today_min = int(self.forecast_today['temperatureMin']) self.temp_range_today_max = int(self.forecast_today['temperatureMax']) # generated string self.forecast_today = '{} bis {}°C - {}'.format( self.temp_range_today_min, self.temp_range_today_max, self.hourly_forecast.encode('UTF-8') ) # variables for weather icon self.version_path = self.config['UNICORN_VERSION'] + '/' self.folder_path = '/home/pi/WeatherPi/Modules/Animations/' self.path = self.folder_path + self.version_path self.icon_extension = '.' + 'png' self.icon_path = self.path + self.weather_icon + self.icon_extension # sensor data base self.sensor_base = [item for item in self.sensor_data['devices'] if item.get('_id') == self.config['NETATMO_DEVICE_ID']][0] # sensor data Wohnzimmer self.sensor_temp_wohnzimmer = self.sensor_base['dashboard_data']['Temperature'] self.sensor_pressure_wohnzimmer = self.sensor_base['dashboard_data']['AbsolutePressure'] self.sensor_humidity_wohnzimmer = self.sensor_base['dashboard_data']['Humidity'] # sensor data modules self.sensor_modules = self.sensor_base['modules'] # sensor data Kinderzimmer self.sensor_kinderzimmer = [item for item in self.sensor_modules if item.get('_id') == self.config['NETATMO_SENSOR_KINDER']][0] self.sensor_temp_kinderzimmer = self.sensor_kinderzimmer['dashboard_data']['Temperature'] # sensor data Schlafzimmer self.sensor_schlafzimmer = [item for item in self.sensor_modules if item.get('_id') == self.config['NETATMO_SENSOR_SCHLAF']][0] self.sensor_temp_schlafzimmer = self.sensor_schlafzimmer['dashboard_data']['Temperature'] # sensor data Balkon self.sensor_outside = [item for item in self.sensor_modules if item.get('_id') == self.config['NETATMO_SENSOR_BALKON']][0] self.sensor_temp_outside = self.sensor_outside['dashboard_data']['Temperature'] self.sensor_humidity_outside = self.sensor_outside['dashboard_data']['Humidity']
def temp_outside(self): sensor_temp_outside = self.sensor_temp_outside log_string('sensor_temp_outside: {}'.format(sensor_temp_outside)) sensor_outside_int = int(round(sensor_temp_outside)) log_string('sensor_temp_outside rounded: {}'.format(sensor_outside_int)) sensor_outside_data = str(abs(sensor_outside_int)).zfill(2) log_string('format absolute sensor_temp_outside to string: {}'.format(sensor_outside_data)) if sensor_outside_int < 0: plus_minus = "-" log_string('Vorzeichen: {}'.format(plus_minus)) else: plus_minus = "+" log_string('Vorzeichen: {}'.format(plus_minus)) the_output_data = temp_digits[plus_minus[0]] + \ temp_digits[sensor_outside_data[0]] + \ temp_digits[sensor_outside_data[1]] + \ temp_digits[self.celsius[0]] log_string('Temperature Outside: {}{}°C'.format(plus_minus, sensor_outside_data)) return the_output_data
def blink(color): blinkt_init() for y in range(9): delta = (time.time() - start_time) * 16 # Triangle wave, a snappy ping-pong effect offset = int(abs((delta % 16) - 8)) if color == 'white': for i in range(8): blinkt.set_pixel(i, leds[offset + i], leds[offset + i], leds[offset + i]) blinkt.show() elif color == 'red': for i in range(8): blinkt.set_pixel(i, leds[offset + i], 0, 0) blinkt.show() elif color == 'yellow': for i in range(8): blinkt.set_pixel(i, leds[offset + i], leds[offset + i], 0) blinkt.show() elif color == 'blue': for i in range(8): blinkt.set_pixel(i, 0, 0, leds[offset + i]) blinkt.show() elif color == 'green': for i in range(8): blinkt.set_pixel(i, 0, leds[offset + i], 0) blinkt.show() else: log_string( 'ERROR: Blinkt Color {} not set. Showing white.'.format(color)) for i in range(8): blinkt.set_pixel(i, leds[offset + i], leds[offset + i], leds[offset + i]) blinkt.show() time.sleep(0.1) blinkt.clear() blinkt.show() log_string('Blinkt: {}'.format(color))
def __init__(self): log_string('Run Update module by: {}'.format(self.__class__)) # set the configs self.config = Config().get_config() self.api_path = '/home/pi/WeatherPi/logs/api.json' self.api_data = self.json_data(self.api_path) # self.test_path = '/home/pi/WeatherPi/logs/test_weather_with_alarm.json' self.sensor_path = '/home/pi/WeatherPi/logs/sensors.json' self.sensor_data = self.json_data(self.sensor_path) # api data self.api_time = self.api_data['currently']['time'] self.temp_api = self.api_data['currently']['temperature'] self.rain_percentage_data = self.api_data['currently'][ 'precipProbability'] self.rain_percentage = self.rain_percentage_data * 100 self.forecast = self.api_data['currently']['summary'].encode('UTF-8') self.weather_icon = self.api_data['currently']['icon'] self.hourly_data = self.api_data['hourly']['data'] self.hourly_forecast = self.api_data['hourly']['summary'] self.daily = self.api_data['daily']['data'] self.forecast_today = self.daily[0] self.temp_range_today_min = int(self.forecast_today['temperatureMin']) self.temp_range_today_max = int(self.forecast_today['temperatureMax']) # generated string self.forecast_today = '{} bis {}°C - {}'.format( self.temp_range_today_min, self.temp_range_today_max, self.hourly_forecast.encode('UTF-8')) # variables for weather icon self.version_path = self.config['UNICORN_VERSION'] + '/' self.folder_path = '/home/pi/WeatherPi/Modules/Animations/' self.path = self.folder_path + self.version_path self.icon_extension = '.' + 'png' self.icon_path = self.path + self.weather_icon + self.icon_extension # sensor data base self.sensor_base = [ item for item in self.sensor_data['devices'] if item.get('_id') == self.config['NETATMO_DEVICE_ID'] ][0] # sensor data Wohnzimmer self.sensor_temp_wohnzimmer = self.sensor_base['dashboard_data'][ 'Temperature'] self.sensor_pressure_wohnzimmer = self.sensor_base['dashboard_data'][ 'AbsolutePressure'] self.sensor_humidity_wohnzimmer = self.sensor_base['dashboard_data'][ 'Humidity'] # sensor data modules self.sensor_modules = self.sensor_base['modules'] # sensor data Kinderzimmer self.sensor_kinderzimmer = [ item for item in self.sensor_modules if item.get('_id') == self.config['NETATMO_SENSOR_KINDER'] ][0] self.sensor_temp_kinderzimmer = self.sensor_kinderzimmer[ 'dashboard_data']['Temperature'] # sensor data Schlafzimmer self.sensor_schlafzimmer = [ item for item in self.sensor_modules if item.get('_id') == self.config['NETATMO_SENSOR_SCHLAF'] ][0] self.sensor_temp_schlafzimmer = self.sensor_schlafzimmer[ 'dashboard_data']['Temperature'] # sensor data Balkon self.sensor_outside = [ item for item in self.sensor_modules if item.get('_id') == self.config['NETATMO_SENSOR_BALKON'] ][0] self.sensor_temp_outside = self.sensor_outside['dashboard_data'][ 'Temperature'] self.sensor_humidity_outside = self.sensor_outside['dashboard_data'][ 'Humidity']
def temp_outside(self): sensor_temp_outside = self.sensor_temp_outside log_string('sensor_temp_outside: {}'.format(sensor_temp_outside)) sensor_outside_int = int(round(sensor_temp_outside)) log_string( 'sensor_temp_outside rounded: {}'.format(sensor_outside_int)) sensor_outside_data = str(abs(sensor_outside_int)).zfill(2) log_string('format absolute sensor_temp_outside to string: {}'.format( sensor_outside_data)) if sensor_outside_int < 0: plus_minus = "-" log_string('Vorzeichen: {}'.format(plus_minus)) else: plus_minus = "+" log_string('Vorzeichen: {}'.format(plus_minus)) the_output_data = temp_digits[plus_minus[0]] + \ temp_digits[sensor_outside_data[0]] + \ temp_digits[sensor_outside_data[1]] + \ temp_digits[self.celsius[0]] log_string('Temperature Outside: {}{}°C'.format( plus_minus, sensor_outside_data)) return the_output_data