예제 #1
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_zones_with_forecast(mock_make_get_request):
    mock_make_get_request.return_value = None
    n = noaa.NOAA(user_agent='test_agent')
    n.zones('test_type', 'test_zone_id', forecast=True)
    mock_make_get_request.assert_called_with(
        '/zones/test_type/test_zone_id/forecast',
        end_point=n.DEFAULT_END_POINT)
예제 #2
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_test_user_agent():
    """Test able to set/get user agent.
    """
    n = noaa.NOAA(user_agent='test_agent')
    assert n._user_agent == 'test_agent'
    n.user_agent = 'test_agent2'
    assert n.user_agent == 'test_agent2'
예제 #3
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_stations_observations_with_current(mock_make_get_request):
    mock_make_get_request.return_value = None
    n = noaa.NOAA(user_agent='test_agent')
    n.stations_observations('PAULOSTATION', current=True)
    mock_make_get_request.assert_called_with(
        '/stations/PAULOSTATION/observations/current',
        end_point=n.DEFAULT_END_POINT)
예제 #4
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_products_locations(mock_make_get_request):
    mock_make_get_request.return_value = None
    n = noaa.NOAA(user_agent='test_agent')
    n.products_locations(location_id='test_location_id')
    mock_make_get_request.assert_any_call(
        '/products/locations/test_location_id/types',
        end_point=n.DEFAULT_END_POINT)
예제 #5
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_products_types_with_locations_failed(mock_make_get_request):
    mock_make_get_request.return_value = None
    n = noaa.NOAA(user_agent='test_agent')

    with pytest.raises(Exception) as err:
        n.products_types(locations=True, location_id='test_location_id')
    assert str(err.value) == ('Error: Missing type id (type_id=None)')
예제 #6
0
    def __init__(self, master):
        self.master = master
        self.master.geometry("700x400+600+{:d}".format(200+PI_TOOLBAR+TK_HEADER))
        self.master.title("Graphs Window")
        self.frame = Frame(self.master)

        # Load the local coordinates from file
        ABSPATH = os.path.abspath(os.path.dirname(sys.argv[0]))
        try:
            with open(ABSPATH+'/.lonlat.txt','r') as fileobj:
                coords = []
                for line in fileobj:
                    coords.append(line.rstrip())
        except:
            print("You must create a file .lonlat.txt containing the coordinates to submit to NOAA")
            exit()
        self.lat = coords[1]
        self.lon = coords[0]

        # Create the NOAA object instance
        self.n             = noaa.NOAA()
        self.have_forecast = False

        # Plot date formats
        self.alldays   = DayLocator()
        self.quartdays = HourLocator(byhour=[0,6,12,18])
        self.dayFormat = DateFormatter('%a %-m/%d')
예제 #7
0
def check_noaa_standard(arr, length_thresh, range_thresh, interval_thresh):
    """
    Returns TRUE/FALSE if noaa.get_observations_by_lat_lon meets criteria given

    :param array arr: array of points to judge criteria on
    :param float length_thresh: threshold for generators length
    :param float range_thresh: threshold for generators date range
    :param float interval_thresh: threshold for generators interval (length/range)
    :return: bool if points meet criteria
    :rtype: boolean
    """
    n = noaa.NOAA()
    gen, gen_temp = tee(n.get_observations_by_lat_lon(arr[0], arr[1]))
    gen_length = len(list(gen_temp))
    print('Length:', gen_length)
    if gen_length < length_thresh:
        return False

    temp_lst = []
    for i in gen:
        temp_lst.append(i['timestamp'])

    date_lst = [datetime.strptime(x, '%Y-%m-%dT%H:%M:%S%z') for x in temp_lst]
    date_length = len(date_lst)

    date_range = (max(date_lst) - min(date_lst)).total_seconds() / 3600
    date_interval = date_length / date_range

    print('Range:', date_range)
    print('Interval:', date_interval)
    if date_range > range_thresh and date_interval >= interval_thresh:
        return True
    else:
        return False
예제 #8
0
파일: main.py 프로젝트: hubertron/drktime
def getWeather():
    while True:
        locations = getLocation()
        global res1day
        n = noaa.NOAA()
        res = n.get_forecasts(locations[0], locations[1], False)
        res1day = res[0]["detailedForecast"]
        time.sleep(3600)
예제 #9
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_stations_observations_with_recordId(mock_make_get_request):
    mock_make_get_request.return_value = None
    n = noaa.NOAA(user_agent='test_agent')
    n.stations_observations('PAULOSTATION',
                            recordId='2017-01-04T18:54:00+00:00')
    mock_make_get_request.assert_called_with(
        '/stations/PAULOSTATION/observations/2017-01-04T18:54:00+00:00',
        end_point=n.DEFAULT_END_POINT)
예제 #10
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_products_types_with_locations_and_id(mock_make_get_request):
    mock_make_get_request.return_value = None
    n = noaa.NOAA(user_agent='test_agent')
    n.products_types(locations=True,
                     location_id='test_location_id',
                     type_id='test_id')
    mock_make_get_request.assert_called_with(
        '/products/types/test_id/locations/test_location_id',
        end_point=n.DEFAULT_END_POINT)
예제 #11
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_get_request_header():
    """Test request header is set correctly.
    """

    n = noaa.NOAA(user_agent='test_agent', accept=noaa.ACCEPT.CAP)
    request_header = n.get_request_header()
    assert request_header == {
        'User-Agent': 'test_agent',
        'accept': 'application/cap+xml'
    }
예제 #12
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_make_get_request(mock_requests):
    mock_response_obj = MagicMock()
    mock_response_obj.text = 'mock text'
    mock_response_obj.json = lambda: {"test": "test"}
    mock_response_obj.status_code = 200
    mock_requests.get.return_value = mock_response_obj

    n = noaa.NOAA(user_agent='test_agent')
    res = n.make_get_request('http://test', end_point='test.paulo.com')
    assert res == {"test": "test"}
 def __init__(self, postal_code, country_code, start, end):
     self.postal_code = postal_code
     self.country_code = country_code
     self.start = start
     self.end = end
     self.observations = [
         x for x in noaa.NOAA().get_observations(
             postal_code, country_code, start=start, end=end)
     ]
     self.values = {}
예제 #14
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_points_forecast_with_hourly(mock_make_get_request):
    mock_make_get_request.return_value = {
        'properties': {
            'forecast': 'forecast_hourly_uri',
            'forecastHourly': 'forecast_hourly_uri'
        }
    }
    n = noaa.NOAA(user_agent='test_agent')
    n.points_forecast(23.44, 34.55, data_type="hourly")
    mock_make_get_request.assert_any_call(uri='forecast_hourly_uri',
                                          end_point=n.DEFAULT_END_POINT)
예제 #15
0
def weather(bot, update, zipcode="35007", hourly=True):
    weather_fetcher = noaa.NOAA()
    results = weather_fetcher.get_forecasts(zipcode, "US", hourly=hourly)
    if hourly:
        results = results[:10]  # 10 hours
        all_forecasts = parse_all_hourly_weather(results)
        update.message.reply_text(all_forecasts)
    else:
        results = results[1:6]  # each is a half day so 3 days
        all_forecasts = parse_all_daily_weather(results)
        update.message.reply_text(all_forecasts)
예제 #16
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_make_get_request_failed(mock_requests):
    mock_response_obj = MagicMock()
    mock_response_obj.text = 'mock text'
    mock_response_obj.status_code = 500
    mock_response_obj.json = lambda: {"test": "test"}
    mock_requests.get.return_value = mock_response_obj

    with pytest.raises(Exception) as err:
        n = noaa.NOAA(user_agent='test_agent')
        n.make_get_request('http://test')
        assert err == 'Error: end_point is None.'
예제 #17
0
def NOAA_combine_forc(sample, keep_list):
    """
    Average NOAA weather forecasts for given station coordinates and year
    NOAA.points_forecast uses local (PST) time 10/09/2020

    :param array sample: coordinates for weather stations used for averaging 
    :param list keep_list: list of headers wished to retain
    :return: dataframe of averaged weather forecasts for stations and year
    :rtype: dataframe
    """
    n = noaa.NOAA()
    forc_df = pd.DataFrame()

    for row in sample:
        gen = n.points_forecast(row[0], row[1])
        for i in gen['properties']['periods']:
            i['lat'] = row[0]
            i['lon'] = row[1]
            forc_df = forc_df.append(i, ignore_index=True)

    forc_df = forc_df[keep_list]

    # Convert time to UTC
    forc_df['startTime'] = pd.to_datetime(forc_df['startTime'])
    forc_df['startTime'] = forc_df['startTime'].dt.tz_convert('utc')
    forc_df.set_index(keys=['startTime'], drop=True, inplace=True)

    # Find average of wind speeds
    temp_df = forc_df['windSpeed'].str.split(' to ', expand=True)

    temp_df[0] = temp_df[0].str.slice(start=0, stop=2)
    temp_df[1] = temp_df[1].str.slice(start=0, stop=2)
    temp_df[temp_df.columns] = temp_df[temp_df.columns].astype(float)
    temp_df['avg'] = temp_df.mean(axis=1)
    forc_df['windSpeed'] = temp_df['avg']

    # Count instances of index
    temp_df['ct'] = 1
    temp_df2 = temp_df.groupby(by=temp_df.index).sum()
    temp_df2 = temp_df2['ct']
    forc_df = forc_df.merge(temp_df2,
                            how='left',
                            left_index=True,
                            right_index=True)
    forc_df = forc_df[forc_df['ct'] > 9]

    NOAA_forc_df = forc_df.groupby(by=forc_df.index).mean()
    NOAA_forc_df['temperature'] = (NOAA_forc_df['temperature'] - 32) * (
        5 / 9)  # Convert F to C

    return NOAA_forc_df
예제 #18
0
def create_homepage():

    latitude = request.args.get('latitude')
    longitude = request.args.get('longitude')
    n = noaa.NOAA()
    cordinate_api = n.points_forecast(latitude, longitude, hourly=False)
    # print(cordinate_api)
    # print(cordinate)
    # api_request = requests.get("https://api.weather.gov/points/" + str(latitude) + "," + str(longitude))
    cordinate_api = api_request.json()
    return render_template("cordinate.html",
                           latitude=latitude,
                           longitude=longitude,
                           cordinate_api=cordinate_api)
예제 #19
0
파일: test_noaa.py 프로젝트: HHousen/noaa
def test_set_accept():
    """Test setting valid accept string.
    """
    with pytest.raises(Exception) as err:
        noaa.NOAA(accept='test')
    assert str(err.value) == ("Invalid format. Available formats are: "
                              "["
                              "'application/atom+xml', "
                              "'application/cap+xml', "
                              "'application/geo+json', "
                              "'application/json', "
                              "'application/ld+json', "
                              "'application/vnd.noaa.dwml+xml', "
                              "'application/vnd.noaa.obs+xml'"
                              "]")
예제 #20
0
 def update(self):
     from noaa_sdk import noaa
     if self._zoneid != 'LAT,LONG':
         params = {'zone': self._zoneid}
     else:
         params = {'point': '{0},{1}'.format(self.latitude, self.longitude)}
     try:
         nws = noaa.NOAA().alerts(active=1, **params)
         nwsalerts = nws['features']
         if len(nwsalerts) > 1:
             nwsalerts = sorted(nwsalerts, key=sortedbyurgencyandseverity)
             self._state = nwsalerts[0]['properties']['urgency']
             self._event_type = nwsalerts[0]['properties']['event']
             self._event_severity = nwsalerts[0]['properties']['severity']
             self._description = nwsalerts[0]['properties']['description']
             self._headline = nwsalerts[0]['properties']['headline']
             self._instruction = nwsalerts[0]['properties']['instruction']
             #second set of events
             self._state2 = nwsalerts[0]['properties']['urgency']
             self._event_type2 = nwsalerts[0]['properties']['event']
             self._event_severity2 = nwsalerts[0]['properties']['severity']
             self._description2 = nwsalerts[0]['properties']['description']
             self._headline2 = nwsalerts[0]['properties']['headline']
             self._instruction2 = nwsalerts[0]['properties']['instruction']
         elif len(nwsalerts) == 1:
             self._state = nwsalerts[0]['properties']['urgency']
             self._event_type = nwsalerts[0]['properties']['event']
             self._event_severity = nwsalerts[0]['properties']['severity']
             self._description = nwsalerts[0]['properties']['description']
             self._headline = nwsalerts[0]['properties']['headline']
             self._instruction = nwsalerts[0]['properties']['instruction']
             self._state2 = 'none'
         else:
             self._state = 'none'
             self._event_type = 'none'
             self._event_severity = 'none'
             self._headline = 'none'
             self._instruction = 'none'
             self._description = 'none'
             self._state2 = 'none'
     except Exception as err:
         self._state = 'Error'
         self._event_type = 'none'
         self._event_severity = 'none'
         self._headline = 'none'
         self._instruction = 'none'
         self._description = err
예제 #21
0
def get_weather(zip=21042):
    def forecast_summary(summary_list):
        place = None
        summary = []
        for i in summary_list:
            if place is None:
                # print(i)
                summary.append(i)
            elif place == i:
                1
            elif place != i:
                # print(i)
                summary.append(i)
            place = i
        return summary

    n = noaa.NOAA()
    res = n.get_forecasts('21042', 'US', True)

    #curr_day = [ v['startTime'][0:10] for v in res ][0]
    days = list(set([v['startTime'][0:10] for v in res]))
    days.sort()
    days_dict = [('Hello Hello, today\'s forecast:', days[0]),
                 ('Tomorrow\'s forecast:', days[1])]
    weather_report = []
    for dat in days_dict:
        weather_report.append(dat[0])
        shortForecasts = [
            v['shortForecast'] for v in res if v['startTime'][0:10] == dat[1]
        ] + ['.']
        weather_report.append(",".join(forecast_summary(shortForecasts)))

        temps = [
            v['temperature'] for v in res if v['startTime'][0:10] == dat[1]
        ]
        temps.sort()
        min = temps[0]
        max = temps[-1]
        weather_report.append("Minimum temperature:" + str(min) +
                              ", and Maximum temperature:" + str(max) +
                              " degrees.")

    return (" ".join(weather_report))
예제 #22
0
def get_forecast(latitude, longitude):

    n = noaa.NOAA()
    response = n.points_forecast(40.7314, -73.8656, hourly=True)
    forecast = json_normalize(data=response['properties'],
                              record_path='periods')

    forecast['datetime'] = pd.to_datetime(forecast['startTime'])
    str.split(forecast['windSpeed'])

    forecast.rename(
        columns={
            'temperature': 'temp',
            #'dewpoint.english' : 'dewPt',
            #'mslp.english' : 'pressure',
            #'humidity' : 'rh',
            'windDirection': 'wdir_cardinal',
            'windSpeed': 'wspd',
            'qpf.english': 'precip_hrly',
            'feelslike.english': 'feels_like',
            'uvi': 'uv_index',
            'wx': 'wx_phrase',
            'FCTTIME.mon': 'month',
            'FCTTIME.hour': 'hour',
            'FCTTIME.mday': 'day',
            'FCTTIME.weekday_name': 'weekday'
        },
        inplace=True)

    # return the simplified forecast
    forecast = forecast[[
        'datetime', 'month', 'day', 'hour', 'temp', 'wx_phrase', 'dewPt', 'rh',
        'pressure', 'wdir_cardinal', 'wspd', 'precip_hrly', 'feels_like'
    ]]

    # convert to numeric
    cols = forecast.columns.drop(['datetime', 'wx_phrase', 'wdir_cardinal'])
    forecast[cols] = forecast[cols].apply(pd.to_numeric, errors='coerce')

    return (forecast)
예제 #23
0
def newData():
    # Get new data
    query = 'SELECT MAX(timestamp) FROM observations'
    cursor.execute(query,())
    sqlResult = cursor.fetchall()
    startDate = datetime.datetime.strptime(str(sqlResult[0]['MAX(timestamp)']), "%Y-%m-%dT%H:%M:%S%z" ).strftime("%Y-%m-%dT%H:%M:%SZ") #changed from - "%Y-%m-%dT00:00:00Z"
    endDate = (datetime.datetime.now() + datetime.timedelta(hours=8)).strftime("%Y-%m-%dT%H:%M:%SZ") #changed from - "%Y-%m-%dT23:59:59Z"

    ##Stolen from DB creation script
    n = noaa.NOAA()
    observations =  n.get_observations(zipCode,country,startDate,endDate)
    
    
    insertQuery = """ REPLACE INTO observations 
                        (timestamp, windSpeed, temperature, relativeHumidity, 
                         windDirection, barometricPressure, visibility, textDescription)
                    VALUES
                        (%s, %s, %s, %s, %s, %s, %s, %s) """                       #changed ? to %s to fit MySQL/MariaDB standards
    ## LATER: Convert noaa dataset to pandas dataframe and insert once?
    count = 0
    for obs in observations:
        insertValues = (obs["timestamp"],
                        obs["windSpeed"]["value"],
                        obs["temperature"]["value"],
                        obs["relativeHumidity"]["value"],
                        obs["windDirection"]["value"],
                        obs["barometricPressure"]["value"],
                        obs["visibility"]["value"],
                        obs["textDescription"])
        cursor.execute(insertQuery, insertValues)
        count += 1
    if count > 0:
        cursor.execute("COMMIT;")
    
    #Now get full table
    
    query = 'SELECT * FROM observations'
    cursor.execute(query,())
    sqlResult = cursor.fetchall()
예제 #24
0
 def _update(self):
     if self._zoneid != 'LAT,LONG':
         params = {'zone': self._zoneid}
     else:
         params = {'point': '{0},{1}'.format(self.latitude, self.longitude)}
     try:
         nws = noaa.NOAA().alerts(active=1, **params)
         nwsalerts = []
         for alert in nws['features']:
             nwsalerts.append(alert['properties'])
         self._state = len(nwsalerts)
         self._attributes = {}
         self._attributes['alerts'] = sorted(nwsalerts,
                                             key=sortedbyurgencyandseverity)
         self._attributes['urgency'] = self._attributes['alerts'][0][
             'urgency'] if self._state > 0 else None
         self._attributes['event_type'] = self._attributes['alerts'][0][
             'event'] if self._state > 0 else None
         self._attributes['event_severity'] = self._attributes['alerts'][0][
             'severity'] if self._state > 0 else None
         self._attributes['description'] = self._attributes['alerts'][0][
             'description'] if self._state > 0 else None
         self._attributes['headline'] = self._attributes['alerts'][0][
             'headline'] if self._state > 0 else None
         self._attributes['instruction'] = self._attributes['alerts'][0][
             'instruction'] if self._state > 0 else None
         self._attributes['alerts_string'] = json.dumps(
             self._attributes['alerts'])
     except Exception as err:
         self._state = 'Error'
         self._attributes['alerts'] = None
         self._attributes['urgency'] = None
         self._attributes['event_type'] = None
         self._attributes['event_severity'] = None
         self._attributes['description'] = err
         self._attributes['headline'] = None
         self._attributes['instruction'] = None
         self._attributes['alerts_string'] = None
         _LOGGER.error(err)
예제 #25
0
def NOAA_combine_obs(sample, replace_list, remove_list):
    """
    Average NOAA weather observations for given station coordinates and year
    
    :param array station_coor: coordinates for weather stations used for averaging 
    :param integer year: year to use for lookup
    :return: dataframe of averaged weather observations for stations and year
    :rtype: dataframe
    """
    n = noaa.NOAA()
    obs_df = pd.DataFrame()

    for row in sample:
        observations = n.get_observations_by_lat_lon(row[0], row[1])
        for i in observations:
            for j in remove_list:
                del i[j]
            for j in replace_list:
                i[j] = i[j]['value']
            i['lat'] = row[0]
            i['lon'] = row[1]

            obs_df = obs_df.append(i, ignore_index=True)

    obs_df['timestamp'] = pd.to_datetime(obs_df['timestamp'])
    obs_df['timestamp_rounded'] = obs_df['timestamp'].dt.round(freq='H')
    # obs_df['timestamp_rounded'] = obs_df['timestamp_rounded'].dt.tz_localize('utc')
    obs_df.set_index(keys=['lat', 'lon', 'timestamp_rounded'],
                     drop=True,
                     inplace=True)

    obs_df = obs_df[~obs_df.index.duplicated(keep='first')]
    obs_df.drop(columns=['timestamp'], inplace=True)
    obs_df.reset_index(level=['lat', 'lon'], drop=True, inplace=True)
    obs_df[obs_df.columns] = obs_df[obs_df.columns].astype(float)

    NOAA_obs_df = obs_df.groupby(by=obs_df.index).mean()

    return NOAA_obs_df
예제 #26
0
    def getAlerts(self):

        params = {'point': '{0},{1}'.format(self.lat, self.lon)}

        #while True:
        try:
            debug.info("Checking NWS weather alerts")
            nws = noaa.NOAA().alerts(active=1, **params)
            self.network_issues = False
        except Exception as err:
            debug.error(err)
            self.network_issues = True
            pass
        #print (nws)
        if not self.network_issues:
            nwsalerts = []

            for alert in nws['features']:
                nwsalerts.append(alert['properties'])
            _state = len(nwsalerts)
            debug.info("Number of alerts is " + str(_state))

            if _state > 0:
                _attributes = {}
                _attributes['alerts'] = sorted(
                    nwsalerts, key=self.sortedbyurgencyandseverity)
                _attributes['urgency'] = _attributes['alerts'][0][
                    'urgency'] if _state > 0 else None
                _attributes['event_severity'] = _attributes['alerts'][0][
                    'severity'] if _state > 0 else None
                _attributes['event'] = _attributes['alerts'][0][
                    'event'] if _state > 0 else None
                _attributes['description'] = _attributes['alerts'][0][
                    'description'] if _state > 0 else None
                _attributes['headline'] = _attributes['alerts'][0][
                    'headline'] if _state > 0 else None
                _attributes['instruction'] = _attributes['alerts'][0][
                    'instruction'] if _state > 0 else None
                _attributes['effective'] = _attributes['alerts'][0][
                    'effective'] if _state > 0 else None
                _attributes['expires'] = _attributes['alerts'][0][
                    'expires'] if _state > 0 else None
                _attributes['alerts_string'] = json.dumps(
                    _attributes['alerts'])

                # Build up the weather alert string
                # urgency	(Immediate, Expected, Future, Unknown)
                # severity	severity level(minor, moderate, severe, extreme)
                #
                if self.data.config.wxalert_nws_show_expire and _attributes[
                        'expires'] != None:
                    warn_date = _attributes['expires']
                else:
                    warn_date = _attributes['effective']

                #Convert to date for display
                warn_datetime = datetime.datetime.strptime(
                    warn_date, self.alert_date_format)
                if self.time_format == "%H:%M":
                    wx_alert_time = warn_datetime.strftime("%m/%d %H:%M")
                else:
                    wx_alert_time = warn_datetime.strftime("%m/%d %I:%M %p")

                #Strip out the string at end of string for the title
                if "Warning" in _attributes['event']:
                    wx_alert_title = _attributes['event'][:-(len(" Warning"))]
                    wx_type = "warning"
                elif "Watch" in _attributes['event']:
                    wx_alert_title = _attributes['event'][:-(len(" Watch"))]
                    wx_type = "watch"
                elif "Advisory" in _attributes['event']:
                    wx_alert_title = _attributes['event'][:-(len(" Advisory"))]
                    wx_type = "advisory"
                else:
                    wx_alert_title = _attributes['event']
                    wx_type = "statement"

                # Only create an alert for Immediate and Expected?

                if wx_type != "statement":
                    self.data.wx_alerts = [
                        wx_alert_title, wx_type, wx_alert_time,
                        _attributes['urgency'], _attributes['event_severity']
                    ]
                    # Only interrupt the first time
                    if self.weather_alert == 0 and self.data.wx_updated:
                        self.data.wx_alert_interrupt = True
                        self.sleepEvent.set()
                    self.weather_alert += 1

                    debug.info(self.data.wx_alerts)
                else:
                    self.data.wx_alert_interrupt = False
                    self.weather_alert = 0
                    self.data.wx_alerts = []
                    debug.info("No active NWS alerts in your area")

            else:
                self.data.wx_alert_interrupt = False
                self.weather_alert = 0
                self.data.wx_alerts = []
                debug.info("No active NWS alerts in your area")
예제 #27
0
    def bot(conf):
        """
        bot(conf)
        Bot.
        """
        with open('cphrases.json', 'r+') as aliases:
            phrases = json.loads(aliases.read())

        if conf['aiml_bot'] is True:
            logging.info("Loading the aiml kernel and files!")
            k = aiml.Kernel()
            k.learn('main.xml')
            k.respond('load aiml b')

        else:
            logger.warn("Aiml bot is disabled!")

        print(conf['bot_name'])
        print(conf['description'])

        #There are two forms of input, audio or terminal. There are two stored forms, the raw response (rresponse), and the parsed response used for just command words (response)
        stopwords = set(sw.words('english'))
        while True:
            if conf['audio'] is True:
                logging.warn("Microphone is active! Listening...")
                rresponse = utils.m()
            else:
                rresponse = input("## ")

            response = rresponse.split(' ')
            logging.info("Command: {}".format(response))
            for w in stopwords:
                if w in response:
                    response.remove(w)

            for phrase in phrases['greet_phrases']:
                if phrase in response:
                    x = datetime.datetime.now().hour
                    if x > 0 and x <= 12:
                        print(
                            "Program your generic response for the morning time here"
                        )
                    elif x > 12 and x < 18:
                        print("Programing afternoon response")
                    else:
                        print("Program night response")

            if "nearby" in response:
                logging.debug("Running command! \n {}".format(rresponse))
                #Fetch nearby locations
                url = "https://maps.googleapis.com/maps/api/place/textsearch/json?"
                r = requests.get(url + 'query=' + rresponse + '&key=' +
                                 conf['maps_api_key'])
                res = r.json()
                res = res['results']
                if conf['audio'] is True:
                    resp = res[0]['name'] + '. address is ' + res[0][
                        'formatted_address']
                    synth(resp)
                else:
                    print(res[0]['name'] + '. Address is ' +
                          res[0]['formatted_address'])

            if "weather" in response:
                logging.debug("Ran weather command with: {}".format(response))
                try:
                    wind_direction = {
                        "N": "North",
                        "E": "East",
                        "S": "South",
                        "W": "West",
                        "SE": "south east",
                        "SW": "south west",
                        "NW": "north west",
                        "NE": "north east",
                        "NNE": "north north east",
                        "NNW": "north north west",
                        "SSE": "south south east",
                        "SSW": "south south west",
                    }

                    res = noaa.NOAA().get_forecasts(conf['zipcode'],
                                                    conf['country'], True)
                    if res[0]['temperatureUnit'] is "F":
                        temp_unit = "farenheit"
                    elif res[0]['temperatureUnit'] is "C":
                        temp_unit = "celcius"
                    else:
                        temp_unit = "unknown"

                    wind_direction = wind_direction[str(
                        res[0]["windDirection"]
                    )]  #Useless type conversion, there to help make things flow better conceptually though.

                    res = res[0]['shortForecast'] + ". the temperature is " + str(
                        res[0]['temperature']
                    ) + " degrees " + temp_unit + ", with wind speeds of " + res[
                        0]['windSpeed'] + " heading " + wind_direction

                    if conf['audio'] is True:
                        synth(res)
                    else:
                        print(res)
                except KeyboardInterrupt as e:
                    logger.warn("Command canceled! \n {}".format(e))

            else:
                if conf['audio'] is True:
                    synth(str(k.respond(rresponse)))
                else:
                    print(k.respond(rresponse))
예제 #28
0
#https://api.weather.gov/alerts/active
#nws = noaa.NOAA().alerts(active=1,zone=CONF_ZONEID)
#follow format of https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/components/weather/darksky.py
try:
    CONF_ZONEID
except NameError:
    params={'point': '{0},{1}'.format(latitude,longitude)}
    print('latlong')
else:
    params={'zone': CONF_ZONEID}
    print('zoneid')
params['limit'] = 3
params={}
print(params)
try:
    nws = noaa.NOAA().alerts(active=1, **params)
    #nws = noaa.NOAA().active_alerts()
    print(nws)
except Exception as err:
    print(err)

nwsalerts = nws['features']

def sortedbyurgencyandseverity(prop):
    if (prop['properties']['urgency']).lower() == 'immediate':
        sortedvalue = 1
    elif (prop['properties']['urgency']).lower() == 'expected':
        sortedvalue = 10
    elif (prop['properties']['urgency']).lower() == 'future':
        sortedvalue = 100
    else:
예제 #29
0
createTableCmd = """ CREATE TABLE IF NOT EXISTS observations (            
                        timestamp VARCHAR(31) NOT NULL PRIMARY KEY,             
                        windSpeed FLOAT,                                        
                        temperature FLOAT,
                        relativeHumidity FLOAT,
                        windDirection INTEGER,
                        barometricPressure INTEGER,
                        visibility INTEGER,
                        textDescription TEXT
                     ) ; """  #changed to VARCHAR to set key length for MySQL/MariaDB, changed REAL to FLOAT to adhere more accurately to MariaDB standards
cur.execute(createTableCmd)
print("Database prepared")

# Get hourly weather observations from NOAA Weather Service API
print("Getting weather data...")
n = noaa.NOAA()
observations = n.get_observations(zipCode, country, startDate, endDate)

#populate table with weather observations
print("Inserting rows...")
insertCmd = """ INSERT INTO observations 
                    (timestamp, windSpeed, temperature, relativeHumidity, 
                     windDirection, barometricPressure, visibility, textDescription)
                VALUES
                    (%s, %s, %s, %s, %s, %s, %s, %s) """                       #changed ? to %s to fit MySQL/MariaDB standards
count = 0
for obs in observations:
    insertValues = (obs["timestamp"], obs["windSpeed"]["value"],
                    obs["temperature"]["value"],
                    obs["relativeHumidity"]["value"],
                    obs["windDirection"]["value"],
예제 #30
0
 def __init__(self):
     MycroftSkill.__init__(self)
     self.noaa = noaa.NOAA()