def getDetailsForDate(location, m, d): # Connects to weather.com and downloads data for a given day of the year, # for each year we've specified. From the data we download, extract the # bits we're interested in data = {} data["Date"] = "/".join([str(m).zfill(2), str(d).zfill(2)]) # MM/DD data["Results"] = [] for y in range(years[first], years[last] + 1): # weather.com is missing random data entries all over the place; when # we hit one, handle it gracefully rather than crashing try: # data found! results = json.loads( weathercom.getCityWeatherDetails( location, queryType="particular-date-data", date={ "year": "{:04}".format(y), "month": "{:02}".format(m), "date": "{:02}".format(d) })) data["Results"].append(extractInterestingData(results)) except: # data missing OR invalid date print("MISSING DATA:", location, data["Date"]) data["Results"].append({ "LowTempC": "n/a", "HighTempC": "n/a", "Weather": "n/a" }) data = consolidateWeatherData(data) return data
def weatherReport(city): weatherDetails = weathercom.getCityWeatherDetails(city) print(weatherDetails) humidity = json.loads(weatherDetails)["vt1observation"]["humidity"] temp = json.loads(weatherDetails)["vt1observation"]["temperature"] phrase = json.loads(weatherDetails)["vt1observation"]["phrase"] return humidity, temp, phrase
def predict(self): model = load('./package/model.joblib') self.rain_json = json.loads( weathercom.getCityWeatherDetails(city="besiktas", queryType=self.query_type)) # hour ve isRainy dinamik. for hour, is_rainy in self.find_rain(): ex = [[ self.date.month, self.date.day, hour, self.is_holiday, self.is_weekend, self.is_school_holiday, is_rainy ]] label = model.predict(ex)[0] self.will_be_returned['result'].append({ 'hour': hour, 'rain': is_rainy, 'speed': SPEED_CLASS[str(label)] }) return self.will_be_returned
def PrevisaoDoTempo(cidade): weatherDetails = weathercom.getCityWeatherDetails( city=cidade, queryType="daily-data") print( f'Cidade: {weatherDetails[weatherDetails.find("city")+8:weatherDetails.find("longitude")-4]}' ) temperatura = weatherDetails[weatherDetails.find("temperature") + 14:weatherDetails.find("temperatureMax") - 3] print(f'Temperatura: {temperatura}ºC') temperaturamax = weatherDetails[weatherDetails.find("temperatureMax") + 25:weatherDetails.find("uvIndex") - 3] print(f'Temperatura máxima desde as 7 da manhã: {temperaturamax}ºC') sensacao = weatherDetails[weatherDetails.find("feelsLike") + 12:weatherDetails.find("gust") - 3] print(f'Sensação térmica: {sensacao}ºC') umidade = weatherDetails[weatherDetails.find("humidity") + 11:weatherDetails.find("icon") - 3] print(f'Umidade relativa do ar: {umidade}%') precip = weatherDetails[weatherDetails.find("precip24") + 15:weatherDetails.find("snowD") - 3] print(f'Precipitação do dia: {precip}mm') vento = weatherDetails[weatherDetails.find("windSpeed") + 11:weatherDetails.find("windDir") - 3] print(f'Velocidade do vento: {vento}km/h') return (temperaturamax, temperatura, precip)
def weathercomapi(): # check for single or double quotes # https://pypi.org/project/weathercom/ tenday = weathercom.getCityWeatherDetails(city="bs273al", queryType="ten-days-data") forcast = json.loads(tenday) day = forcast['vt1dailyForecast']['dayOfWeek'][0] tempnow = forcast['vt1dailyForecast']['day']['temperature'][0] iconnow = forcast['vt1dailyForecast']['day']['icon'][0] context = { 'today': day, 'todaytemp': tempnow, 'todayicon': iconnow, # 'day1pop': day1pop, # 'day1rain': day1rain, # 'day1snow': day1snow, # 'day2min': "%.0f" % day2min, # 'day2max': "%.0f" % day2max, # 'day2desc': day2desc, # 'icon2': icon2, # 'day2pop': day2pop, # 'day2rain': day2rain, # 'day2snow': day2snow, } return render_template("weathercom.html", page_title="Nested dictionary", weather=context)
def precip(num=False, city='moscow'): weatherDetails = weathercom.getCityWeatherDetails(city) weatherDetails = eval(weatherDetails.replace("null", "None")) s = weatherDetails['vt1observation']['precip24Hour'] if num: return s else: return '%s мм' % s
def pressure(num=False, city='moscow'): weatherDetails = weathercom.getCityWeatherDetails(city) weatherDetails = eval(weatherDetails.replace("null", "None")) s = weatherDetails['vt1observation']['altimeter'] if num: return s else: return '%s мбар' % s
def snow(num=False, city='moscow'): weatherDetails = weathercom.getCityWeatherDetails(city) weatherDetails = eval(weatherDetails.replace("null", "None")) s = weatherDetails['vt1observation']['snowDepth'] if num: return s else: return '%s м' % s
def wind_speed(num=False, city='moscow'): weatherDetails = weathercom.getCityWeatherDetails(city) weatherDetails = eval(weatherDetails.replace("null", "None")) s = weatherDetails['vt1observation']['windSpeed'] if num: return s else: return '%s км/ч' % s
def max_temp(num=False, city='moscow'): weatherDetails = weathercom.getCityWeatherDetails(city) weatherDetails = eval(weatherDetails.replace("null", "None")) s = weatherDetails['vt1observation']['temperatureMaxSince7am'] if num: return s else: return '%s °C' % s
def temp_feel(num=False, city='moscow'): weatherDetails = weathercom.getCityWeatherDetails(city) weatherDetails = eval(weatherDetails.replace("null", "None")) s = weatherDetails['vt1observation']['feelsLike'] if num: return s else: return '%s °C' % s
def getAirTemp(loadingWhat): #NOT DONE loading(loadingWhat) query = "\"temperature\"" weatherDetailsJSON = weathercom.getCityWeatherDetails("Gwynn, Virginia") jsonData = json.loads(weatherDetailsJSON) temp = int(jsonData["vt1observation"]["temperature"]) temp = (temp * 9 / 5 + 32) print("AIR TEMP(at gwynn island, virginia) : {0}".format(temp) + "\n")
def weather(): speak('which city, sir.') city = takeCommand() weatherDetails = weathercom.getCityWeatherDetails(city) humidity = json.loads(weatherDetails)["vt1observation"]["humidity"] temp = json.loads(weatherDetails)["vt1observation"]["temperature"] phrase = json.loads(weatherDetails)["vt1observation"]["phrase"] print('humidity =', humidity) print('temperature =', temp, 'c') print('climate', phrase) speak('report from' + str(city) + 'sir') speak('humidity' + str(humidity)) speak('temperature' + str(temp) + 'degree celsius') speak('climate' + str(phrase))
import weathercom import requests import pandas as pd import matplotlib as plt weatherDetails = weathercom.getCityWeatherDetails("san fransisco", queryType="ten-days-data") print(weatherDetails) df = pd.read_json(weatherDetails, convert_axes=True) print(df) #plt.show()
async def __weather(city): data = weathercom.getCityWeatherDetails(city) return loads(data)
def printit(): threading.Timer(60.0, printit).start() # Run o código a cada 1h (3600 s) cidade = "Novo Hamburgo" weatherDetails = weathercom.getCityWeatherDetails(city=cidade, queryType="daily-data") print( f'Cidade: {weatherDetails[weatherDetails.find("city")+8:weatherDetails.find("longitude")-4]}' ) temperatura = weatherDetails[weatherDetails.find("temperature") + 14:weatherDetails.find("temperatureMax") - 3] print(f'Temperatura: {temperatura}ºC') temperaturamax = weatherDetails[weatherDetails.find("temperatureMax") + 25:weatherDetails.find("uvIndex") - 3] print(f'Temperatura máxima desde as 7 da manhã: {temperaturamax}ºC') sensacao = weatherDetails[weatherDetails.find("feelsLike") + 12:weatherDetails.find("gust") - 3] print(f'Sensação térmica: {sensacao}ºC') umidade = weatherDetails[weatherDetails.find("humidity") + 11:weatherDetails.find("icon") - 3] print(f'Umidade relativa do ar: {umidade}%') precip = weatherDetails[weatherDetails.find("precip24") + 15:weatherDetails.find("snowD") - 3] print(f'Precipitação do dia: {precip}mm') vento = weatherDetails[weatherDetails.find("windSpeed") + 11:weatherDetails.find("windDir") - 3] print(f'Velocidade do vento: {vento}km/h') print('\nConexão por protocolo MQTT') def envia_relatorio(cliente): previsao = [{ 'variable': 'temperaturamin', 'value': temperatura }, { 'variable': 'temperaturamax', 'value': temperaturamax }, { 'variable': 'chuva', 'value': precip }] json_file = json.dumps(previsao) cliente.publish(topico1, payload=json_file, qos=1, retain=True) # Publica os dados no broker com retenção # Método que exibe o registro da comunicacao por protocolo mqtt no terminal def on_log_esdra(esdra, userdata, level, buf): print("log: ", buf) # Rotina que trata o evento de conexao, exibindo o return code e subscrevendo o cliente aos topicos de interesse def on_connect_esdra(esdra, userdata, flags, rc): print("[STATUS] Conectado ao Broker " + broker + " Resultado de conexao: " + str(rc)) print("subscrevendo ao topico", topico1) # Método que exibe o registro da comunicacao por protocolo mqtt no terminal def on_log_carlos(esdra, userdata, level, buf): print("log: ", buf) # Rotina que trata o evento de conexao, exibindo o return code e subscrevendo o cliente aos topicos de interesse def on_connect_carlos(esdra, userdata, flags, rc): print("[STATUS] Conectado ao Broker " + broker + " Resultado de conexao: " + str(rc)) print("subscrevendo ao topico", topico1) def configura_cliente(cliente, id): cliente.loop_start() print("Conectando ao broker...") cliente.connect(broker, porta) if id == 1: cliente.on_connect = on_connect_esdra cliente.on_log = on_log_esdra if id == 2: cliente.on_connect = on_connect_carlos cliente.on_log = on_log_carlos envia_relatorio(cliente) time.sleep(5) cliente.loop_stop() # Definindo os objetos broker = "mqtt.tago.io" # Endereço do broker porta = 1883 # Porta sem segurança para testes #keepAlive = 60 # Tempo em segundos para o envio de uma requisicao ping # Topicos para publicar os dados no tago.io topico1 = "tago/data/previsao" print("Criando nova instancia") esdra = mqtt.Client() esdra.username_pw_set('', "e35c4944-06a4-46f1-be9d-243af76bd4a0") print("Configurando o cliente") configura_cliente(esdra, 1) print("Criando nova instancia") carlos = mqtt.Client() carlos.username_pw_set('', '7f1d7f85-761e-4b98-92b4-7bab3f528b82') print("Configurando o cliente") configura_cliente(carlos, 2)
datetime.date(2020, 4, 19), datetime.date(2021, 1, 1), datetime.date(2021, 3, 3), datetime.date(2020, 5, 1), datetime.date(2020, 5, 6), datetime.date(2020, 5, 24), datetime.date(2020, 9, 6), datetime.date(2020, 9, 22), datetime.date(2020, 12, 24), datetime.date(2020, 12, 25), datetime.date(2020, 12, 26) ] sc_regr = joblib.load('std_scaler.bin') data = weathercom.getCityWeatherDetails(city='Sofia', queryType="ten-days-data") # This would be an input to the ANN to estimate the air quality for the next few days df = pd.read_json(data) weather = pd.DataFrame() date = pd.DataFrame() weather['Temperature'] = df['vt1dailyForecast']['day']['temperature'] weather['Humidity'] = df['vt1dailyForecast']['day']['humidityPct'] date['Date'] = pd.to_datetime(df['vt1dailyForecast']['validDate']) weather['IsHoliday'] = date['Date'].apply(is_holiday) weather['Weekday'] = date['Date'].dt.dayofweek weather['Season'] = date['Date'].apply(season)
def get_weather(): # This would be an input to the ANN to estimate the air quality for the next few days data = weathercom.getCityWeatherDetails(city='Sofia', queryType="ten-days-data") return data