] # A thread-safe task queue that stores actions to perform against Reddit task_queue = SimpleQueue() # Config the logger logging.basicConfig(filename='weather_output.log', filemode='w', level=logging.INFO) # Set up the weather API for later usage config = configparser.ConfigParser() config.read('weather_api.ini') api_key = config['weatherbit.io']['api_key'] weather_api = Api(api_key) weather_api.set_granularity('daily') # Load locations to check from stored CSV file locations = [] with open('top_150_cities.csv', newline='') as csvfile: reader = csv.DictReader(csvfile, fieldnames=['city', 'region', 'id']) for row in reader: locations.append(row) # Setup Reddit Connection reddit = praw.Reddit( 'niceweatherbot', user_agent='python:niceweatherbot:v1.0.0 (by u/jakekarnes42)') # Create a thread pool pool = ThreadPoolExecutor()
from machine import Pin from time import localtime, sleep from weatherbit.api import Api import threading api_key = "key" lat = 49.44684 lon = 8.357229999999959 api = Api(api_key) api.set_granularity('daily') class MQTT_subcriber(): #Class for controlling the ESP pass def auto_water( ): #This function looks what the forecast says and let flow enough water for everything pass def manuell(): #function for manuell control e.g. if it is not enough water pass threading.Thread(target=auto_water).start() threading.Thread(target=manuell).start()
class weatherbit(awp): def __init__(self, location, listOfTimePredictions) : self.name = "weatherbit" self.allowedTimePredictions = "N-N-0" super(weatherbit, self).__init__(self.name, listOfTimePredictions) self.login() self.setLocation(location) def login(self): if self.login_data["apikey"] : self.api = Api(self.login_data["apikey"]) else : warnings.warn('MWP_WARNING. The "%s" Weather Package(WP) has not been \ properly activated due to the apikey' % (self.name.upper())) def setLocation(self,location): self.forecast = self.api.get_forecast(lat=location[0],lon=location[1]) def update(self,days=["ALL"]) : listOfTimePredictions = self.WD.keys() for api_periods in self.weather.keys() : if api_periods == "daily" : self.api.set_granularity('daily') self.weather[api_periods] = self.forecast.get_series(['temp','precip','rh','wind_spd']) elif api_periods == "hourly" : self.api.set_granularity('hourly') self.weather[api_periods] = self.forecast.get_series(['temp','precip','rh','wind_spd']) elif api_periods == "currently" : self.api.set_granularity('hourly') self.weather[api_periods] = self.forecast.get_series(['temp','precip','rh','wind_spd'])[0] for timePrediction in listOfTimePredictions : self.setTemperature(timePrediction) self.setWindVelocity(timePrediction) self.setRainProbability(timePrediction) self.setRainIntensity(timePrediction) self.setRelativeHumidity(timePrediction) def setTemperature(self,timePrediction="0-0-0"): #Units: ÂșC value = self.setWeatherProperty(timePrediction,'temp') self.WD[timePrediction]["Temperature"] = value def setWindVelocity(self,timePrediction="0-0-0"): #Units: m/s value = self.setWeatherProperty(timePrediction,'wind_spd') self.WD[timePrediction]["WindVelocity"] = value def setRainProbability(self,timePrediction="0-0-0"): #Units: Percentatge [0-1] #Warning: Weatherbit does not calculate Weather Prediction self.WD[timePrediction]["RainProbability"] = None def setRainIntensity(self,timePrediction="0-0-0"): #Units: mm/hour value = self.setWeatherProperty(timePrediction,'precip') self.WD[timePrediction]["RainIntensity"] = value def setRelativeHumidity(self,timePrediction="0-0-0"): #Units: Percentatge [0-1] value = self.setWeatherProperty(timePrediction,'rh') self.WD[timePrediction]["RelativeHumidity"] = value/100.0 if value else value def setWeatherProperty(self,timePrediction,WP) : value = None day, hour, minute, predictionType = decomposeTimePrediction(timePrediction) try : if day : value = self.weather[predictionType][day][WP] elif hour : # N hours value = self.weather[predictionType][hour][WP] elif not day and \ not hour and \ not minute : value = self.weather[predictionType][WP] except : print("WP[%s]: \"%s\" is not available for \"%s\" prediction. " % (self.name,WP,predictionType)) return value
model_best_cv, [model_best_val, model_best_test])) print('--Best model in CV not best in val and in test datasets/n') # plot metrics # df_metrics.pivot(index='df', columns='model', values='MSE').plot() # df_metrics.dtypes # get datetime column from date and period by mapping time and period with "df_map_HH_Period" # plt.scatter(x = df_train['pred.GradBoostRegr'], y = df_train['dmd_coeff']) ################################################################################################################################################### ################ #### Step 5 #### ################ from weatherbit.api import Api # pip install pyweatherbit api_call = Api(key_API_WeatherFct) api_call.set_granularity('daily') # 'hourly', '3hourly' df_weather_Fct = pd.DataFrame() for iCity in list_cities: print('{}: Downloading Weather Forecast for {}'.format( ddt.now().strftime('%d%b%Y %H:%M:%S:'), iCity)) tmp_df_weather_fct = pd.DataFrame( api_call.get_forecast(city=iCity, country='GB').get_series( ['temp', 'max_temp', 'min_temp', 'precip'])) tmp_df_weather_fct['City'] = iCity df_weather_Fct = df_weather_Fct.append(tmp_df_weather_fct) # simple daily average; more accurate would be to have a population- or other-weighted average temperature; other measure for wind speed df_weather_Fct_avg = df_weather_Fct[[ 'datetime', 'temp' ]].groupby('datetime').mean().reset_index() df_weather_Fct_avg['date'], df_weather_Fct_avg['time'] = df_weather_Fct_avg[ 'datetime'].dt.date, df_weather_Fct_avg['datetime'].dt.time
# Class for making Weatherbit API calls. This class will be instantiated as a # singleton to gather all necessary information from the API. from weatherbit.api import Api import API_Key import json # Get the private key string from API_KEY. api_key = API_Key.API_Key().Weatherbit_Key # Authenticate our API Key. This variable will be used for all API calls. weatherbit = Api(api_key) # Set the API for retrieving the daily forecast. weatherbit.set_granularity('daily') # Gets the forecast for the current day. # Params: # lat: Float: The latitude of the city. # long: Float: The longitude of the city. # Return: List containing the precipitation, average temperature, and max # temperature per hour from midnight to the current hour. def get_daily_forecast(lat, long): forecast = weatherbit.get_forecast(lat=lat, lon=long) precip = forecast.json['data'][0]['precip'] precip = precip / 25.4 # Convert mm to inches avg_temp = forecast.json['data'][0]['temp'] avg_temp = avg_temp * 1.8 + 32 # Convert Celsius to Fahrenheit max_temp = forecast.json['data'][0]['max_temp'] max_temp = max_temp * 1.8 + 32 weather = [precip, avg_temp, max_temp]