body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
21e2180e6bf64fc4d23ab83bb27893bb26a5b31ec30c6e4e492b97853d0a395b | def actionRefreshWeather(self, values_dict):
'\n Refresh all weather as a result of an action call\n\n The actionRefreshWeather() method calls the refreshWeatherData() method to\n request a complete refresh of all weather data (Actions.XML call.)\n\n -----\n\n :param indigo.Dict values_dict:\n '
self.logger.debug(u'Processing Action: refresh all weather data.')
self.refreshWeatherData() | Refresh all weather as a result of an action call
The actionRefreshWeather() method calls the refreshWeatherData() method to
request a complete refresh of all weather data (Actions.XML call.)
-----
:param indigo.Dict values_dict: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | actionRefreshWeather | DaveL17/WUnderground7 | 0 | python | def actionRefreshWeather(self, values_dict):
'\n Refresh all weather as a result of an action call\n\n The actionRefreshWeather() method calls the refreshWeatherData() method to\n request a complete refresh of all weather data (Actions.XML call.)\n\n -----\n\n :param indigo.Dict values_dict:\n '
self.logger.debug(u'Processing Action: refresh all weather data.')
self.refreshWeatherData() | def actionRefreshWeather(self, values_dict):
'\n Refresh all weather as a result of an action call\n\n The actionRefreshWeather() method calls the refreshWeatherData() method to\n request a complete refresh of all weather data (Actions.XML call.)\n\n -----\n\n :param indigo.Dict values_dict:\n '
self.logger.debug(u'Processing Action: refresh all weather data.')
self.refreshWeatherData()<|docstring|>Refresh all weather as a result of an action call
The actionRefreshWeather() method calls the refreshWeatherData() method to
request a complete refresh of all weather data (Actions.XML call.)
-----
:param indigo.Dict values_dict:<|endoftext|> |
a1b853a5065be179970bdac396eb0ac3cfc474dba13046bf448d3e5aa7d8d4b1 | def callCount(self):
"\n Maintain count of calls made to the WU API\n\n Maintains a count of daily calls to Weather Underground to help ensure that the\n plugin doesn't go over a user-defined limit. The limit is set within the plugin\n config dialog.\n\n -----\n "
calls_made = int(self.pluginPrefs.get('dailyCallCounter', '0'))
calls_max = int(self.pluginPrefs.get('callCounter', '500'))
if (calls_made >= calls_max):
self.logger.info(u'Daily call limit ({0}) reached. Taking the rest of the day off.'.format(calls_max))
self.logger.debug(u'Set call limiter to: True')
self.pluginPrefs['dailyCallLimitReached'] = True
mark_delta = (dt.datetime.now() + dt.timedelta(days=1))
new_mark = mark_delta.replace(hour=0, minute=0, second=0, microsecond=0)
self.next_poll_attempt = new_mark
self.pluginPrefs['nextPoll'] = dt.datetime.strftime(self.next_poll_attempt, '%Y-%m-%d %H:%M:%S')
self.logger.debug(u'Next Poll Time Updated: {0} (max calls exceeded)'.format(self.next_poll_attempt))
else:
self.pluginPrefs['dailyCallLimitReached'] = False
self.pluginPrefs['dailyCallCounter'] += 1
calls_left = (calls_max - calls_made)
self.logger.debug(u'API calls left: {0}'.format(calls_left)) | Maintain count of calls made to the WU API
Maintains a count of daily calls to Weather Underground to help ensure that the
plugin doesn't go over a user-defined limit. The limit is set within the plugin
config dialog.
----- | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | callCount | DaveL17/WUnderground7 | 0 | python | def callCount(self):
"\n Maintain count of calls made to the WU API\n\n Maintains a count of daily calls to Weather Underground to help ensure that the\n plugin doesn't go over a user-defined limit. The limit is set within the plugin\n config dialog.\n\n -----\n "
calls_made = int(self.pluginPrefs.get('dailyCallCounter', '0'))
calls_max = int(self.pluginPrefs.get('callCounter', '500'))
if (calls_made >= calls_max):
self.logger.info(u'Daily call limit ({0}) reached. Taking the rest of the day off.'.format(calls_max))
self.logger.debug(u'Set call limiter to: True')
self.pluginPrefs['dailyCallLimitReached'] = True
mark_delta = (dt.datetime.now() + dt.timedelta(days=1))
new_mark = mark_delta.replace(hour=0, minute=0, second=0, microsecond=0)
self.next_poll_attempt = new_mark
self.pluginPrefs['nextPoll'] = dt.datetime.strftime(self.next_poll_attempt, '%Y-%m-%d %H:%M:%S')
self.logger.debug(u'Next Poll Time Updated: {0} (max calls exceeded)'.format(self.next_poll_attempt))
else:
self.pluginPrefs['dailyCallLimitReached'] = False
self.pluginPrefs['dailyCallCounter'] += 1
calls_left = (calls_max - calls_made)
self.logger.debug(u'API calls left: {0}'.format(calls_left)) | def callCount(self):
"\n Maintain count of calls made to the WU API\n\n Maintains a count of daily calls to Weather Underground to help ensure that the\n plugin doesn't go over a user-defined limit. The limit is set within the plugin\n config dialog.\n\n -----\n "
calls_made = int(self.pluginPrefs.get('dailyCallCounter', '0'))
calls_max = int(self.pluginPrefs.get('callCounter', '500'))
if (calls_made >= calls_max):
self.logger.info(u'Daily call limit ({0}) reached. Taking the rest of the day off.'.format(calls_max))
self.logger.debug(u'Set call limiter to: True')
self.pluginPrefs['dailyCallLimitReached'] = True
mark_delta = (dt.datetime.now() + dt.timedelta(days=1))
new_mark = mark_delta.replace(hour=0, minute=0, second=0, microsecond=0)
self.next_poll_attempt = new_mark
self.pluginPrefs['nextPoll'] = dt.datetime.strftime(self.next_poll_attempt, '%Y-%m-%d %H:%M:%S')
self.logger.debug(u'Next Poll Time Updated: {0} (max calls exceeded)'.format(self.next_poll_attempt))
else:
self.pluginPrefs['dailyCallLimitReached'] = False
self.pluginPrefs['dailyCallCounter'] += 1
calls_left = (calls_max - calls_made)
self.logger.debug(u'API calls left: {0}'.format(calls_left))<|docstring|>Maintain count of calls made to the WU API
Maintains a count of daily calls to Weather Underground to help ensure that the
plugin doesn't go over a user-defined limit. The limit is set within the plugin
config dialog.
-----<|endoftext|> |
6c669e00bf970031978991f196a9f79d0c7c00eb2a972d4d8c21e59befec565f | def callDay(self):
'\n Track day for call counter reset and forecast email\n\n Manages the day for the purposes of maintaining the call counter and the flag\n for the daily forecast email message.\n\n -----\n '
call_day = self.pluginPrefs.get('dailyCallDay', '1970-01-01')
call_limit_reached = self.pluginPrefs.get('dailyCallLimitReached', False)
todays_date = dt.datetime.today().date()
today_str = u'{0}'.format(todays_date)
today_date = dt.datetime.strptime(call_day, '%Y-%m-%d').date()
self.logger.debug(u'Processing API: Call counter')
self.logger.debug(u'Daily call limit reached: {0}'.format(call_limit_reached))
if (call_day in ['', '1970-01-01']):
self.logger.debug(u'Initializing variable dailyCallDay: {0}'.format(today_str))
self.pluginPrefs['dailyCallDay'] = today_str
if (todays_date > today_date):
self.pluginPrefs['dailyCallCounter'] = 0
self.pluginPrefs['dailyCallLimitReached'] = False
self.pluginPrefs['dailyCallDay'] = today_str
for dev in indigo.devices.itervalues('self'):
try:
if ('weatherSummaryEmailSent' in dev.states):
dev.updateStateOnServer('weatherSummaryEmailSent', value=False)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Error setting email sent value.')
self.logger.debug(u'Reset call limit, call counter and call day.')
self.logger.debug(u'New call day: {0}'.format((todays_date > today_date)))
if call_limit_reached:
self.logger.info(u'Daily call limit reached. Taking the rest of the day off.') | Track day for call counter reset and forecast email
Manages the day for the purposes of maintaining the call counter and the flag
for the daily forecast email message.
----- | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | callDay | DaveL17/WUnderground7 | 0 | python | def callDay(self):
'\n Track day for call counter reset and forecast email\n\n Manages the day for the purposes of maintaining the call counter and the flag\n for the daily forecast email message.\n\n -----\n '
call_day = self.pluginPrefs.get('dailyCallDay', '1970-01-01')
call_limit_reached = self.pluginPrefs.get('dailyCallLimitReached', False)
todays_date = dt.datetime.today().date()
today_str = u'{0}'.format(todays_date)
today_date = dt.datetime.strptime(call_day, '%Y-%m-%d').date()
self.logger.debug(u'Processing API: Call counter')
self.logger.debug(u'Daily call limit reached: {0}'.format(call_limit_reached))
if (call_day in [, '1970-01-01']):
self.logger.debug(u'Initializing variable dailyCallDay: {0}'.format(today_str))
self.pluginPrefs['dailyCallDay'] = today_str
if (todays_date > today_date):
self.pluginPrefs['dailyCallCounter'] = 0
self.pluginPrefs['dailyCallLimitReached'] = False
self.pluginPrefs['dailyCallDay'] = today_str
for dev in indigo.devices.itervalues('self'):
try:
if ('weatherSummaryEmailSent' in dev.states):
dev.updateStateOnServer('weatherSummaryEmailSent', value=False)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Error setting email sent value.')
self.logger.debug(u'Reset call limit, call counter and call day.')
self.logger.debug(u'New call day: {0}'.format((todays_date > today_date)))
if call_limit_reached:
self.logger.info(u'Daily call limit reached. Taking the rest of the day off.') | def callDay(self):
'\n Track day for call counter reset and forecast email\n\n Manages the day for the purposes of maintaining the call counter and the flag\n for the daily forecast email message.\n\n -----\n '
call_day = self.pluginPrefs.get('dailyCallDay', '1970-01-01')
call_limit_reached = self.pluginPrefs.get('dailyCallLimitReached', False)
todays_date = dt.datetime.today().date()
today_str = u'{0}'.format(todays_date)
today_date = dt.datetime.strptime(call_day, '%Y-%m-%d').date()
self.logger.debug(u'Processing API: Call counter')
self.logger.debug(u'Daily call limit reached: {0}'.format(call_limit_reached))
if (call_day in [, '1970-01-01']):
self.logger.debug(u'Initializing variable dailyCallDay: {0}'.format(today_str))
self.pluginPrefs['dailyCallDay'] = today_str
if (todays_date > today_date):
self.pluginPrefs['dailyCallCounter'] = 0
self.pluginPrefs['dailyCallLimitReached'] = False
self.pluginPrefs['dailyCallDay'] = today_str
for dev in indigo.devices.itervalues('self'):
try:
if ('weatherSummaryEmailSent' in dev.states):
dev.updateStateOnServer('weatherSummaryEmailSent', value=False)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Error setting email sent value.')
self.logger.debug(u'Reset call limit, call counter and call day.')
self.logger.debug(u'New call day: {0}'.format((todays_date > today_date)))
if call_limit_reached:
self.logger.info(u'Daily call limit reached. Taking the rest of the day off.')<|docstring|>Track day for call counter reset and forecast email
Manages the day for the purposes of maintaining the call counter and the flag
for the daily forecast email message.
-----<|endoftext|> |
c0af7df0b030b027beb16408b6b196033ebda449ab17163184eba102189fc354 | def commsKillAll(self):
'\n Disable all plugin devices\n\n commsKillAll() sets the enabled status of all plugin devices to false.\n\n -----\n '
for dev in indigo.devices.itervalues('self'):
try:
indigo.device.enable(dev, value=False)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Exception when trying to kill all comms.') | Disable all plugin devices
commsKillAll() sets the enabled status of all plugin devices to false.
----- | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | commsKillAll | DaveL17/WUnderground7 | 0 | python | def commsKillAll(self):
'\n Disable all plugin devices\n\n commsKillAll() sets the enabled status of all plugin devices to false.\n\n -----\n '
for dev in indigo.devices.itervalues('self'):
try:
indigo.device.enable(dev, value=False)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Exception when trying to kill all comms.') | def commsKillAll(self):
'\n Disable all plugin devices\n\n commsKillAll() sets the enabled status of all plugin devices to false.\n\n -----\n '
for dev in indigo.devices.itervalues('self'):
try:
indigo.device.enable(dev, value=False)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Exception when trying to kill all comms.')<|docstring|>Disable all plugin devices
commsKillAll() sets the enabled status of all plugin devices to false.
-----<|endoftext|> |
51da6d3f784f2327b5c983860fc4a9709e026ca0264e2a068f697e1f315b0f53 | def commsUnkillAll(self):
'\n Enable all plugin devices\n\n commsUnkillAll() sets the enabled status of all plugin devices to true.\n\n -----\n '
for dev in indigo.devices.itervalues('self'):
try:
indigo.device.enable(dev, value=True)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Exception when trying to unkill all comms.') | Enable all plugin devices
commsUnkillAll() sets the enabled status of all plugin devices to true.
----- | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | commsUnkillAll | DaveL17/WUnderground7 | 0 | python | def commsUnkillAll(self):
'\n Enable all plugin devices\n\n commsUnkillAll() sets the enabled status of all plugin devices to true.\n\n -----\n '
for dev in indigo.devices.itervalues('self'):
try:
indigo.device.enable(dev, value=True)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Exception when trying to unkill all comms.') | def commsUnkillAll(self):
'\n Enable all plugin devices\n\n commsUnkillAll() sets the enabled status of all plugin devices to true.\n\n -----\n '
for dev in indigo.devices.itervalues('self'):
try:
indigo.device.enable(dev, value=True)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Exception when trying to unkill all comms.')<|docstring|>Enable all plugin devices
commsUnkillAll() sets the enabled status of all plugin devices to true.
-----<|endoftext|> |
9f97d02a6027b23c0d6928697393eedaef0dbba32280259998e0ada52e93cf68 | def dumpTheJSON(self):
'\n Dump copy of weather JSON to file\n\n The dumpTheJSON() method reaches out to Weather Underground, grabs a copy of\n the configured JSON data and saves it out to a file placed in the Indigo Logs\n folder. If a weather data log exists for that day, it will be replaced. With a\n new day, a new log file will be created (file name contains the date.)\n\n -----\n '
file_name = '{0}/{1} Wunderground.txt'.format(indigo.server.getLogsFolderPath(), dt.datetime.today().date())
try:
with open(file_name, 'w') as logfile:
logfile.write(u'Weather Underground JSON Data\n'.encode('utf-8'))
logfile.write(u'Written at: {0}\n'.format(dt.datetime.today().strftime('%Y-%m-%d %H:%M')).encode('utf-8'))
logfile.write(u'{0}{1}'.format(('=' * 72), '\n').encode('utf-8'))
for key in self.masterWeatherDict.keys():
logfile.write(u'Location Specified: {0}\n'.format(key).encode('utf-8'))
logfile.write(u'{0}\n\n'.format(self.masterWeatherDict[key]).encode('utf-8'))
indigo.server.log(u'Weather data written to: {0}'.format(file_name))
except IOError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.info(u'Unable to write to Indigo Log folder.') | Dump copy of weather JSON to file
The dumpTheJSON() method reaches out to Weather Underground, grabs a copy of
the configured JSON data and saves it out to a file placed in the Indigo Logs
folder. If a weather data log exists for that day, it will be replaced. With a
new day, a new log file will be created (file name contains the date.)
----- | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | dumpTheJSON | DaveL17/WUnderground7 | 0 | python | def dumpTheJSON(self):
'\n Dump copy of weather JSON to file\n\n The dumpTheJSON() method reaches out to Weather Underground, grabs a copy of\n the configured JSON data and saves it out to a file placed in the Indigo Logs\n folder. If a weather data log exists for that day, it will be replaced. With a\n new day, a new log file will be created (file name contains the date.)\n\n -----\n '
file_name = '{0}/{1} Wunderground.txt'.format(indigo.server.getLogsFolderPath(), dt.datetime.today().date())
try:
with open(file_name, 'w') as logfile:
logfile.write(u'Weather Underground JSON Data\n'.encode('utf-8'))
logfile.write(u'Written at: {0}\n'.format(dt.datetime.today().strftime('%Y-%m-%d %H:%M')).encode('utf-8'))
logfile.write(u'{0}{1}'.format(('=' * 72), '\n').encode('utf-8'))
for key in self.masterWeatherDict.keys():
logfile.write(u'Location Specified: {0}\n'.format(key).encode('utf-8'))
logfile.write(u'{0}\n\n'.format(self.masterWeatherDict[key]).encode('utf-8'))
indigo.server.log(u'Weather data written to: {0}'.format(file_name))
except IOError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.info(u'Unable to write to Indigo Log folder.') | def dumpTheJSON(self):
'\n Dump copy of weather JSON to file\n\n The dumpTheJSON() method reaches out to Weather Underground, grabs a copy of\n the configured JSON data and saves it out to a file placed in the Indigo Logs\n folder. If a weather data log exists for that day, it will be replaced. With a\n new day, a new log file will be created (file name contains the date.)\n\n -----\n '
file_name = '{0}/{1} Wunderground.txt'.format(indigo.server.getLogsFolderPath(), dt.datetime.today().date())
try:
with open(file_name, 'w') as logfile:
logfile.write(u'Weather Underground JSON Data\n'.encode('utf-8'))
logfile.write(u'Written at: {0}\n'.format(dt.datetime.today().strftime('%Y-%m-%d %H:%M')).encode('utf-8'))
logfile.write(u'{0}{1}'.format(('=' * 72), '\n').encode('utf-8'))
for key in self.masterWeatherDict.keys():
logfile.write(u'Location Specified: {0}\n'.format(key).encode('utf-8'))
logfile.write(u'{0}\n\n'.format(self.masterWeatherDict[key]).encode('utf-8'))
indigo.server.log(u'Weather data written to: {0}'.format(file_name))
except IOError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.info(u'Unable to write to Indigo Log folder.')<|docstring|>Dump copy of weather JSON to file
The dumpTheJSON() method reaches out to Weather Underground, grabs a copy of
the configured JSON data and saves it out to a file placed in the Indigo Logs
folder. If a weather data log exists for that day, it will be replaced. With a
new day, a new log file will be created (file name contains the date.)
-----<|endoftext|> |
ad85f4a38c7ee81503f4a94dc6a54799840116917b068d8c1cbe7b7db39e0c76 | def emailForecast(self, dev):
'\n Email forecast information\n\n The emailForecast() method will construct and send a summary of select weather\n information to the user based on the email address specified for plugin update\n notifications.\n\n -----\n\n :param indigo.Device dev:\n '
try:
summary_wanted = dev.pluginProps.get('weatherSummaryEmail', '')
summary_sent = dev.states.get('weatherSummaryEmailSent', False)
summary_time = dev.pluginProps.get('weatherSummaryEmailTime', '01:00')
summary_time = dt.datetime.strptime(summary_time, '%H:%M')
if isinstance(summary_wanted, basestring):
if (summary_wanted.lower() == 'false'):
summary_wanted = False
elif (summary_wanted.lower() == 'true'):
summary_wanted = True
if isinstance(summary_sent, basestring):
if (summary_sent.lower() == 'false'):
summary_sent = False
elif (summary_sent.lower() == 'true'):
summary_sent = True
if (summary_wanted and (not summary_sent) and (dt.datetime.now().hour >= summary_time.hour)):
config_menu_units = dev.pluginProps.get('configMenuUnits', '')
email_body = u''
email_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
temp_high_record_year = int(self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'recordyear')))
temp_low_record_year = int(self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'recordyear')))
today_record_high_metric = self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'C'))
today_record_high_standard = self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'F'))
today_record_low_metric = self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'C'))
today_record_low_standard = self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'F'))
forecast_today_metric = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[0]['fcttext_metric']
forecast_today_standard = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[0]['fcttext']
forecast_today_title = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[0]['title']
forecast_tomorrow_metric = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[1]['fcttext_metric']
forecast_tomorrow_standard = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[1]['fcttext']
forecast_tomorrow_title = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[1]['title']
max_humidity = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'maxhumidity'))
today_high_metric = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'high', 'celsius'))
today_high_standard = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'high', 'fahrenheit'))
today_low_metric = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'low', 'celsius'))
today_low_standard = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'low', 'fahrenheit'))
today_qpf_metric = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'qpf_allday', 'mm'))
today_qpf_standard = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'qpf_allday', 'in'))
yesterday_high_temp_metric = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'maxtempm'))
yesterday_high_temp_standard = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'maxtempi'))
yesterday_low_temp_metric = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'mintempm'))
yesterday_low_temp_standard = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'mintempi'))
yesterday_total_qpf_metric = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'precipm'))
yesterday_total_qpf_standard = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'precipi'))
max_humidity = u'{0}'.format(self.floatEverything(state_name='sendMailMaxHumidity', val=max_humidity))
today_high_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailHighC', val=today_high_metric))
today_high_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailHighF', val=today_high_standard))
today_low_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailLowC', val=today_low_metric))
today_low_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailLowF', val=today_low_standard))
today_qpf_metric = u'{0} mm.'.format(self.floatEverything(state_name='sendMailQPF', val=today_qpf_metric))
today_qpf_standard = u'{0} in.'.format(self.floatEverything(state_name='sendMailQPF', val=today_qpf_standard))
today_record_high_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailRecordHighC', val=today_record_high_metric))
today_record_high_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailRecordHighF', val=today_record_high_standard))
today_record_low_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailRecordLowC', val=today_record_low_metric))
today_record_low_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailRecordLowF', val=today_record_low_standard))
yesterday_high_temp_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailMaxTempM', val=yesterday_high_temp_metric))
yesterday_high_temp_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailMaxTempI', val=yesterday_high_temp_standard))
yesterday_low_temp_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailMinTempM', val=yesterday_low_temp_metric))
yesterday_low_temp_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailMinTempI', val=yesterday_low_temp_standard))
yesterday_total_qpf_metric = u'{0} mm.'.format(self.floatEverything(state_name='sendMailPrecipM', val=yesterday_total_qpf_metric))
yesterday_total_qpf_standard = u'{0} in.'.format(self.floatEverything(state_name='sendMailPrecipM', val=yesterday_total_qpf_standard))
email_list.append(u'{0}'.format(dev.name))
if (config_menu_units in ['M', 'MS']):
for element in [forecast_today_title, forecast_today_metric, forecast_tomorrow_title, forecast_tomorrow_metric, today_high_metric, today_low_metric, max_humidity, today_qpf_metric, today_record_high_metric, temp_high_record_year, today_record_low_metric, temp_low_record_year, yesterday_high_temp_metric, yesterday_low_temp_metric, yesterday_total_qpf_metric]:
try:
email_list.append(element)
except KeyError:
email_list.append(u'Not provided')
elif (config_menu_units in 'I'):
for element in [forecast_today_title, forecast_today_metric, forecast_tomorrow_title, forecast_tomorrow_metric, today_high_metric, today_low_metric, max_humidity, today_qpf_standard, today_record_high_metric, temp_high_record_year, today_record_low_metric, temp_low_record_year, yesterday_high_temp_metric, yesterday_low_temp_metric, yesterday_total_qpf_standard]:
try:
email_list.append(element)
except KeyError:
email_list.append(u'Not provided')
elif (config_menu_units in 'S'):
for element in [forecast_today_title, forecast_today_standard, forecast_tomorrow_title, forecast_tomorrow_standard, today_high_standard, today_low_standard, max_humidity, today_qpf_standard, today_record_high_standard, temp_high_record_year, today_record_low_standard, temp_low_record_year, yesterday_high_temp_standard, yesterday_low_temp_standard, yesterday_total_qpf_standard]:
try:
email_list.append(element)
except KeyError:
email_list.append(u'Not provided')
email_list = tuple([(u'--' if (x == '') else x) for x in email_list])
email_body += u'{d[0]}\n-------------------------------------------\n\n{d[1]}:\n{d[2]}\n\n{d[3]}:\n{d[4]}\n\nToday:\n-------------------------\nHigh: {d[5]}\nLow: {d[6]}\nHumidity: {d[7]}%\nPrecipitation total: {d[8]}\n\nRecord:\n-------------------------\nHigh: {d[9]} ({d[10]})\nLow: {d[11]} ({d[12]})\n\nYesterday:\n-------------------------\nHigh: {d[13]}\nLow: {d[14]}\nPrecipitation: {d[15]}\n\n'.format(d=email_list)
indigo.server.sendEmailTo(self.pluginPrefs['updaterEmail'], subject=u'Daily Weather Summary', body=email_body)
dev.updateStateOnServer('weatherSummaryEmailSent', value=True)
else:
pass
except (KeyError, IndexError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
dev.updateStateOnServer('weatherSummaryEmailSent', value=True, uiValue=u'Err')
self.logger.debug(u'Unable to compile forecast data for {0}.'.format(dev.name))
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Unable to send forecast email message. Will keep trying.') | Email forecast information
The emailForecast() method will construct and send a summary of select weather
information to the user based on the email address specified for plugin update
notifications.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | emailForecast | DaveL17/WUnderground7 | 0 | python | def emailForecast(self, dev):
'\n Email forecast information\n\n The emailForecast() method will construct and send a summary of select weather\n information to the user based on the email address specified for plugin update\n notifications.\n\n -----\n\n :param indigo.Device dev:\n '
try:
summary_wanted = dev.pluginProps.get('weatherSummaryEmail', )
summary_sent = dev.states.get('weatherSummaryEmailSent', False)
summary_time = dev.pluginProps.get('weatherSummaryEmailTime', '01:00')
summary_time = dt.datetime.strptime(summary_time, '%H:%M')
if isinstance(summary_wanted, basestring):
if (summary_wanted.lower() == 'false'):
summary_wanted = False
elif (summary_wanted.lower() == 'true'):
summary_wanted = True
if isinstance(summary_sent, basestring):
if (summary_sent.lower() == 'false'):
summary_sent = False
elif (summary_sent.lower() == 'true'):
summary_sent = True
if (summary_wanted and (not summary_sent) and (dt.datetime.now().hour >= summary_time.hour)):
config_menu_units = dev.pluginProps.get('configMenuUnits', )
email_body = u
email_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
temp_high_record_year = int(self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'recordyear')))
temp_low_record_year = int(self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'recordyear')))
today_record_high_metric = self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'C'))
today_record_high_standard = self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'F'))
today_record_low_metric = self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'C'))
today_record_low_standard = self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'F'))
forecast_today_metric = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[0]['fcttext_metric']
forecast_today_standard = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[0]['fcttext']
forecast_today_title = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[0]['title']
forecast_tomorrow_metric = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[1]['fcttext_metric']
forecast_tomorrow_standard = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[1]['fcttext']
forecast_tomorrow_title = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[1]['title']
max_humidity = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'maxhumidity'))
today_high_metric = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'high', 'celsius'))
today_high_standard = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'high', 'fahrenheit'))
today_low_metric = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'low', 'celsius'))
today_low_standard = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'low', 'fahrenheit'))
today_qpf_metric = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'qpf_allday', 'mm'))
today_qpf_standard = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'qpf_allday', 'in'))
yesterday_high_temp_metric = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'maxtempm'))
yesterday_high_temp_standard = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'maxtempi'))
yesterday_low_temp_metric = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'mintempm'))
yesterday_low_temp_standard = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'mintempi'))
yesterday_total_qpf_metric = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'precipm'))
yesterday_total_qpf_standard = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'precipi'))
max_humidity = u'{0}'.format(self.floatEverything(state_name='sendMailMaxHumidity', val=max_humidity))
today_high_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailHighC', val=today_high_metric))
today_high_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailHighF', val=today_high_standard))
today_low_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailLowC', val=today_low_metric))
today_low_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailLowF', val=today_low_standard))
today_qpf_metric = u'{0} mm.'.format(self.floatEverything(state_name='sendMailQPF', val=today_qpf_metric))
today_qpf_standard = u'{0} in.'.format(self.floatEverything(state_name='sendMailQPF', val=today_qpf_standard))
today_record_high_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailRecordHighC', val=today_record_high_metric))
today_record_high_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailRecordHighF', val=today_record_high_standard))
today_record_low_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailRecordLowC', val=today_record_low_metric))
today_record_low_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailRecordLowF', val=today_record_low_standard))
yesterday_high_temp_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailMaxTempM', val=yesterday_high_temp_metric))
yesterday_high_temp_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailMaxTempI', val=yesterday_high_temp_standard))
yesterday_low_temp_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailMinTempM', val=yesterday_low_temp_metric))
yesterday_low_temp_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailMinTempI', val=yesterday_low_temp_standard))
yesterday_total_qpf_metric = u'{0} mm.'.format(self.floatEverything(state_name='sendMailPrecipM', val=yesterday_total_qpf_metric))
yesterday_total_qpf_standard = u'{0} in.'.format(self.floatEverything(state_name='sendMailPrecipM', val=yesterday_total_qpf_standard))
email_list.append(u'{0}'.format(dev.name))
if (config_menu_units in ['M', 'MS']):
for element in [forecast_today_title, forecast_today_metric, forecast_tomorrow_title, forecast_tomorrow_metric, today_high_metric, today_low_metric, max_humidity, today_qpf_metric, today_record_high_metric, temp_high_record_year, today_record_low_metric, temp_low_record_year, yesterday_high_temp_metric, yesterday_low_temp_metric, yesterday_total_qpf_metric]:
try:
email_list.append(element)
except KeyError:
email_list.append(u'Not provided')
elif (config_menu_units in 'I'):
for element in [forecast_today_title, forecast_today_metric, forecast_tomorrow_title, forecast_tomorrow_metric, today_high_metric, today_low_metric, max_humidity, today_qpf_standard, today_record_high_metric, temp_high_record_year, today_record_low_metric, temp_low_record_year, yesterday_high_temp_metric, yesterday_low_temp_metric, yesterday_total_qpf_standard]:
try:
email_list.append(element)
except KeyError:
email_list.append(u'Not provided')
elif (config_menu_units in 'S'):
for element in [forecast_today_title, forecast_today_standard, forecast_tomorrow_title, forecast_tomorrow_standard, today_high_standard, today_low_standard, max_humidity, today_qpf_standard, today_record_high_standard, temp_high_record_year, today_record_low_standard, temp_low_record_year, yesterday_high_temp_standard, yesterday_low_temp_standard, yesterday_total_qpf_standard]:
try:
email_list.append(element)
except KeyError:
email_list.append(u'Not provided')
email_list = tuple([(u'--' if (x == ) else x) for x in email_list])
email_body += u'{d[0]}\n-------------------------------------------\n\n{d[1]}:\n{d[2]}\n\n{d[3]}:\n{d[4]}\n\nToday:\n-------------------------\nHigh: {d[5]}\nLow: {d[6]}\nHumidity: {d[7]}%\nPrecipitation total: {d[8]}\n\nRecord:\n-------------------------\nHigh: {d[9]} ({d[10]})\nLow: {d[11]} ({d[12]})\n\nYesterday:\n-------------------------\nHigh: {d[13]}\nLow: {d[14]}\nPrecipitation: {d[15]}\n\n'.format(d=email_list)
indigo.server.sendEmailTo(self.pluginPrefs['updaterEmail'], subject=u'Daily Weather Summary', body=email_body)
dev.updateStateOnServer('weatherSummaryEmailSent', value=True)
else:
pass
except (KeyError, IndexError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
dev.updateStateOnServer('weatherSummaryEmailSent', value=True, uiValue=u'Err')
self.logger.debug(u'Unable to compile forecast data for {0}.'.format(dev.name))
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Unable to send forecast email message. Will keep trying.') | def emailForecast(self, dev):
'\n Email forecast information\n\n The emailForecast() method will construct and send a summary of select weather\n information to the user based on the email address specified for plugin update\n notifications.\n\n -----\n\n :param indigo.Device dev:\n '
try:
summary_wanted = dev.pluginProps.get('weatherSummaryEmail', )
summary_sent = dev.states.get('weatherSummaryEmailSent', False)
summary_time = dev.pluginProps.get('weatherSummaryEmailTime', '01:00')
summary_time = dt.datetime.strptime(summary_time, '%H:%M')
if isinstance(summary_wanted, basestring):
if (summary_wanted.lower() == 'false'):
summary_wanted = False
elif (summary_wanted.lower() == 'true'):
summary_wanted = True
if isinstance(summary_sent, basestring):
if (summary_sent.lower() == 'false'):
summary_sent = False
elif (summary_sent.lower() == 'true'):
summary_sent = True
if (summary_wanted and (not summary_sent) and (dt.datetime.now().hour >= summary_time.hour)):
config_menu_units = dev.pluginProps.get('configMenuUnits', )
email_body = u
email_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
temp_high_record_year = int(self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'recordyear')))
temp_low_record_year = int(self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'recordyear')))
today_record_high_metric = self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'C'))
today_record_high_standard = self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'F'))
today_record_low_metric = self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'C'))
today_record_low_standard = self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'F'))
forecast_today_metric = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[0]['fcttext_metric']
forecast_today_standard = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[0]['fcttext']
forecast_today_title = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[0]['title']
forecast_tomorrow_metric = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[1]['fcttext_metric']
forecast_tomorrow_standard = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[1]['fcttext']
forecast_tomorrow_title = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))[1]['title']
max_humidity = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'maxhumidity'))
today_high_metric = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'high', 'celsius'))
today_high_standard = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'high', 'fahrenheit'))
today_low_metric = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'low', 'celsius'))
today_low_standard = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'low', 'fahrenheit'))
today_qpf_metric = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'qpf_allday', 'mm'))
today_qpf_standard = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday', 'qpf_allday', 'in'))
yesterday_high_temp_metric = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'maxtempm'))
yesterday_high_temp_standard = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'maxtempi'))
yesterday_low_temp_metric = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'mintempm'))
yesterday_low_temp_standard = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'mintempi'))
yesterday_total_qpf_metric = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'precipm'))
yesterday_total_qpf_standard = self.nestedLookup(weather_data, keys=('history', 'dailysummary', 'precipi'))
max_humidity = u'{0}'.format(self.floatEverything(state_name='sendMailMaxHumidity', val=max_humidity))
today_high_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailHighC', val=today_high_metric))
today_high_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailHighF', val=today_high_standard))
today_low_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailLowC', val=today_low_metric))
today_low_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailLowF', val=today_low_standard))
today_qpf_metric = u'{0} mm.'.format(self.floatEverything(state_name='sendMailQPF', val=today_qpf_metric))
today_qpf_standard = u'{0} in.'.format(self.floatEverything(state_name='sendMailQPF', val=today_qpf_standard))
today_record_high_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailRecordHighC', val=today_record_high_metric))
today_record_high_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailRecordHighF', val=today_record_high_standard))
today_record_low_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailRecordLowC', val=today_record_low_metric))
today_record_low_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailRecordLowF', val=today_record_low_standard))
yesterday_high_temp_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailMaxTempM', val=yesterday_high_temp_metric))
yesterday_high_temp_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailMaxTempI', val=yesterday_high_temp_standard))
yesterday_low_temp_metric = u'{0:.0f}C'.format(self.floatEverything(state_name='sendMailMinTempM', val=yesterday_low_temp_metric))
yesterday_low_temp_standard = u'{0:.0f}F'.format(self.floatEverything(state_name='sendMailMinTempI', val=yesterday_low_temp_standard))
yesterday_total_qpf_metric = u'{0} mm.'.format(self.floatEverything(state_name='sendMailPrecipM', val=yesterday_total_qpf_metric))
yesterday_total_qpf_standard = u'{0} in.'.format(self.floatEverything(state_name='sendMailPrecipM', val=yesterday_total_qpf_standard))
email_list.append(u'{0}'.format(dev.name))
if (config_menu_units in ['M', 'MS']):
for element in [forecast_today_title, forecast_today_metric, forecast_tomorrow_title, forecast_tomorrow_metric, today_high_metric, today_low_metric, max_humidity, today_qpf_metric, today_record_high_metric, temp_high_record_year, today_record_low_metric, temp_low_record_year, yesterday_high_temp_metric, yesterday_low_temp_metric, yesterday_total_qpf_metric]:
try:
email_list.append(element)
except KeyError:
email_list.append(u'Not provided')
elif (config_menu_units in 'I'):
for element in [forecast_today_title, forecast_today_metric, forecast_tomorrow_title, forecast_tomorrow_metric, today_high_metric, today_low_metric, max_humidity, today_qpf_standard, today_record_high_metric, temp_high_record_year, today_record_low_metric, temp_low_record_year, yesterday_high_temp_metric, yesterday_low_temp_metric, yesterday_total_qpf_standard]:
try:
email_list.append(element)
except KeyError:
email_list.append(u'Not provided')
elif (config_menu_units in 'S'):
for element in [forecast_today_title, forecast_today_standard, forecast_tomorrow_title, forecast_tomorrow_standard, today_high_standard, today_low_standard, max_humidity, today_qpf_standard, today_record_high_standard, temp_high_record_year, today_record_low_standard, temp_low_record_year, yesterday_high_temp_standard, yesterday_low_temp_standard, yesterday_total_qpf_standard]:
try:
email_list.append(element)
except KeyError:
email_list.append(u'Not provided')
email_list = tuple([(u'--' if (x == ) else x) for x in email_list])
email_body += u'{d[0]}\n-------------------------------------------\n\n{d[1]}:\n{d[2]}\n\n{d[3]}:\n{d[4]}\n\nToday:\n-------------------------\nHigh: {d[5]}\nLow: {d[6]}\nHumidity: {d[7]}%\nPrecipitation total: {d[8]}\n\nRecord:\n-------------------------\nHigh: {d[9]} ({d[10]})\nLow: {d[11]} ({d[12]})\n\nYesterday:\n-------------------------\nHigh: {d[13]}\nLow: {d[14]}\nPrecipitation: {d[15]}\n\n'.format(d=email_list)
indigo.server.sendEmailTo(self.pluginPrefs['updaterEmail'], subject=u'Daily Weather Summary', body=email_body)
dev.updateStateOnServer('weatherSummaryEmailSent', value=True)
else:
pass
except (KeyError, IndexError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
dev.updateStateOnServer('weatherSummaryEmailSent', value=True, uiValue=u'Err')
self.logger.debug(u'Unable to compile forecast data for {0}.'.format(dev.name))
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Unable to send forecast email message. Will keep trying.')<|docstring|>Email forecast information
The emailForecast() method will construct and send a summary of select weather
information to the user based on the email address specified for plugin update
notifications.
-----
:param indigo.Device dev:<|endoftext|> |
0001036b7d18c6bb141ebf538532d828d95a2ec8b492d88f2793d97e347e73fd | def fixCorruptedData(self, state_name, val):
'\n Format corrupted and missing data\n\n Sometimes WU receives corrupted data from personal weather stations. Could be\n zero, positive value or "--" or "-999.0" or "-9999.0". This method tries to\n "fix" these values for proper display.\n\n -----\n\n :param str state_name:\n :param str or float val:\n '
try:
val = float(val)
if (val < (- 55.728)):
self.logger.debug(u'Formatted {0} data. Got: {1} Returning: (-99.0, --)'.format(state_name, val))
return ((- 99.0), u'--')
else:
return (val, str(val))
except (ValueError, TypeError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Imputing {0} data. Got: {1} Returning: (-99.0, --)'.format(state_name, val))
return ((- 99.0), u'--') | Format corrupted and missing data
Sometimes WU receives corrupted data from personal weather stations. Could be
zero, positive value or "--" or "-999.0" or "-9999.0". This method tries to
"fix" these values for proper display.
-----
:param str state_name:
:param str or float val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | fixCorruptedData | DaveL17/WUnderground7 | 0 | python | def fixCorruptedData(self, state_name, val):
'\n Format corrupted and missing data\n\n Sometimes WU receives corrupted data from personal weather stations. Could be\n zero, positive value or "--" or "-999.0" or "-9999.0". This method tries to\n "fix" these values for proper display.\n\n -----\n\n :param str state_name:\n :param str or float val:\n '
try:
val = float(val)
if (val < (- 55.728)):
self.logger.debug(u'Formatted {0} data. Got: {1} Returning: (-99.0, --)'.format(state_name, val))
return ((- 99.0), u'--')
else:
return (val, str(val))
except (ValueError, TypeError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Imputing {0} data. Got: {1} Returning: (-99.0, --)'.format(state_name, val))
return ((- 99.0), u'--') | def fixCorruptedData(self, state_name, val):
'\n Format corrupted and missing data\n\n Sometimes WU receives corrupted data from personal weather stations. Could be\n zero, positive value or "--" or "-999.0" or "-9999.0". This method tries to\n "fix" these values for proper display.\n\n -----\n\n :param str state_name:\n :param str or float val:\n '
try:
val = float(val)
if (val < (- 55.728)):
self.logger.debug(u'Formatted {0} data. Got: {1} Returning: (-99.0, --)'.format(state_name, val))
return ((- 99.0), u'--')
else:
return (val, str(val))
except (ValueError, TypeError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Imputing {0} data. Got: {1} Returning: (-99.0, --)'.format(state_name, val))
return ((- 99.0), u'--')<|docstring|>Format corrupted and missing data
Sometimes WU receives corrupted data from personal weather stations. Could be
zero, positive value or "--" or "-999.0" or "-9999.0". This method tries to
"fix" these values for proper display.
-----
:param str state_name:
:param str or float val:<|endoftext|> |
89451f98f409f7d86b562c4c590cfe5f8a3e9796941b53cae8f1510a4f05d59b | def floatEverything(self, state_name, val):
"\n Take value and return float\n\n This doesn't actually float everything. Select values are sent here to see if\n they float. If they do, a float is returned. Otherwise, a Unicode string is\n returned. This is necessary because Weather Underground will send values that\n won't float even when they're supposed to.\n\n -----\n\n :param str state_name:\n :param val:\n "
try:
return float(val)
except (ValueError, TypeError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Error floating {0} (val = {1})'.format(state_name, val))
return (- 99.0) | Take value and return float
This doesn't actually float everything. Select values are sent here to see if
they float. If they do, a float is returned. Otherwise, a Unicode string is
returned. This is necessary because Weather Underground will send values that
won't float even when they're supposed to.
-----
:param str state_name:
:param val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | floatEverything | DaveL17/WUnderground7 | 0 | python | def floatEverything(self, state_name, val):
"\n Take value and return float\n\n This doesn't actually float everything. Select values are sent here to see if\n they float. If they do, a float is returned. Otherwise, a Unicode string is\n returned. This is necessary because Weather Underground will send values that\n won't float even when they're supposed to.\n\n -----\n\n :param str state_name:\n :param val:\n "
try:
return float(val)
except (ValueError, TypeError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Error floating {0} (val = {1})'.format(state_name, val))
return (- 99.0) | def floatEverything(self, state_name, val):
"\n Take value and return float\n\n This doesn't actually float everything. Select values are sent here to see if\n they float. If they do, a float is returned. Otherwise, a Unicode string is\n returned. This is necessary because Weather Underground will send values that\n won't float even when they're supposed to.\n\n -----\n\n :param str state_name:\n :param val:\n "
try:
return float(val)
except (ValueError, TypeError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Error floating {0} (val = {1})'.format(state_name, val))
return (- 99.0)<|docstring|>Take value and return float
This doesn't actually float everything. Select values are sent here to see if
they float. If they do, a float is returned. Otherwise, a Unicode string is
returned. This is necessary because Weather Underground will send values that
won't float even when they're supposed to.
-----
:param str state_name:
:param val:<|endoftext|> |
ea446a44ff2a2fde363c6392057aa30356e18dcc52c428090856b5a9877ea1e1 | def generatorTime(self, filter='', values_dict=None, type_id='', target_id=0):
'\n List of hours generator\n\n Creates a list of times for use in setting the desired time for weather\n forecast emails to be sent.\n\n -----\n :param str filter:\n :param indigo.Dict values_dict:\n :param str type_id:\n :param int target_id:\n '
return [(u'{0:02.0f}:00'.format(hour), u'{0:02.0f}:00'.format(hour)) for hour in range(0, 24)] | List of hours generator
Creates a list of times for use in setting the desired time for weather
forecast emails to be sent.
-----
:param str filter:
:param indigo.Dict values_dict:
:param str type_id:
:param int target_id: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | generatorTime | DaveL17/WUnderground7 | 0 | python | def generatorTime(self, filter=, values_dict=None, type_id=, target_id=0):
'\n List of hours generator\n\n Creates a list of times for use in setting the desired time for weather\n forecast emails to be sent.\n\n -----\n :param str filter:\n :param indigo.Dict values_dict:\n :param str type_id:\n :param int target_id:\n '
return [(u'{0:02.0f}:00'.format(hour), u'{0:02.0f}:00'.format(hour)) for hour in range(0, 24)] | def generatorTime(self, filter=, values_dict=None, type_id=, target_id=0):
'\n List of hours generator\n\n Creates a list of times for use in setting the desired time for weather\n forecast emails to be sent.\n\n -----\n :param str filter:\n :param indigo.Dict values_dict:\n :param str type_id:\n :param int target_id:\n '
return [(u'{0:02.0f}:00'.format(hour), u'{0:02.0f}:00'.format(hour)) for hour in range(0, 24)]<|docstring|>List of hours generator
Creates a list of times for use in setting the desired time for weather
forecast emails to be sent.
-----
:param str filter:
:param indigo.Dict values_dict:
:param str type_id:
:param int target_id:<|endoftext|> |
f8aed1291301474a150806f568edd4e229fe0b3e63b7aa3e7bc4bdac22246940 | def getLatLong(self, values_dict, type_id, dev_id):
'\n Get server latitude and longitude\n\n Called when a device configuration dialog is opened. Returns the current\n latitude and longitude from the Indigo server.\n\n -----\n\n :param indigo.Dict values_dict:\n :param str type_id:\n :param int dev_id:\n '
(latitude, longitude) = indigo.server.getLatitudeAndLongitude()
values_dict['centerlat'] = latitude
values_dict['centerlon'] = longitude
return values_dict | Get server latitude and longitude
Called when a device configuration dialog is opened. Returns the current
latitude and longitude from the Indigo server.
-----
:param indigo.Dict values_dict:
:param str type_id:
:param int dev_id: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | getLatLong | DaveL17/WUnderground7 | 0 | python | def getLatLong(self, values_dict, type_id, dev_id):
'\n Get server latitude and longitude\n\n Called when a device configuration dialog is opened. Returns the current\n latitude and longitude from the Indigo server.\n\n -----\n\n :param indigo.Dict values_dict:\n :param str type_id:\n :param int dev_id:\n '
(latitude, longitude) = indigo.server.getLatitudeAndLongitude()
values_dict['centerlat'] = latitude
values_dict['centerlon'] = longitude
return values_dict | def getLatLong(self, values_dict, type_id, dev_id):
'\n Get server latitude and longitude\n\n Called when a device configuration dialog is opened. Returns the current\n latitude and longitude from the Indigo server.\n\n -----\n\n :param indigo.Dict values_dict:\n :param str type_id:\n :param int dev_id:\n '
(latitude, longitude) = indigo.server.getLatitudeAndLongitude()
values_dict['centerlat'] = latitude
values_dict['centerlon'] = longitude
return values_dict<|docstring|>Get server latitude and longitude
Called when a device configuration dialog is opened. Returns the current
latitude and longitude from the Indigo server.
-----
:param indigo.Dict values_dict:
:param str type_id:
:param int dev_id:<|endoftext|> |
c5d2fbf177c5586ef6a0695809e2bf529accf69080051dee3e91d23e6d2c58c7 | def getSatelliteImage(self, dev):
'\n Download satellite image and save to file\n\n The getSatelliteImage() method will download a file from a user- specified\n location and save it to a user-specified folder on the local server. This\n method is used by the Satellite Image Downloader device type.\n\n -----\n\n :param indigo.Device dev:\n '
destination = unicode(dev.pluginProps['imageDestinationLocation'])
source = unicode(dev.pluginProps['imageSourceLocation'])
try:
if destination.endswith(('.gif', '.jpg', '.jpeg', '.png')):
get_data_time = dt.datetime.now()
try:
self.logger.debug(u'Source: {0}'.format(source))
self.logger.debug(u'Destination: {0}'.format(destination))
r = requests.get(source, stream=True, timeout=20)
with open(destination, 'wb') as img:
for chunk in r.iter_content(2000):
img.write(chunk)
except requests.exceptions.ConnectionError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Error downloading satellite image. (No comm.)')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return
except NameError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
urllib.urlretrieve(source, destination)
dev.updateStateOnServer('onOffState', value=True, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
data_cycle_time = (dt.datetime.now() - get_data_time)
data_cycle_time = (dt.datetime.min + data_cycle_time).time()
self.logger.debug(u'[ {0} download: {1} seconds ]'.format(dev.name, data_cycle_time.strftime('%S.%f')))
return
else:
self.logger.error(u'The image destination must include one of the approved types (.gif, .jpg, .jpeg, .png)')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'Bad Type')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return False
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'[{0}] Error downloading satellite image.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | Download satellite image and save to file
The getSatelliteImage() method will download a file from a user- specified
location and save it to a user-specified folder on the local server. This
method is used by the Satellite Image Downloader device type.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | getSatelliteImage | DaveL17/WUnderground7 | 0 | python | def getSatelliteImage(self, dev):
'\n Download satellite image and save to file\n\n The getSatelliteImage() method will download a file from a user- specified\n location and save it to a user-specified folder on the local server. This\n method is used by the Satellite Image Downloader device type.\n\n -----\n\n :param indigo.Device dev:\n '
destination = unicode(dev.pluginProps['imageDestinationLocation'])
source = unicode(dev.pluginProps['imageSourceLocation'])
try:
if destination.endswith(('.gif', '.jpg', '.jpeg', '.png')):
get_data_time = dt.datetime.now()
try:
self.logger.debug(u'Source: {0}'.format(source))
self.logger.debug(u'Destination: {0}'.format(destination))
r = requests.get(source, stream=True, timeout=20)
with open(destination, 'wb') as img:
for chunk in r.iter_content(2000):
img.write(chunk)
except requests.exceptions.ConnectionError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Error downloading satellite image. (No comm.)')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return
except NameError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
urllib.urlretrieve(source, destination)
dev.updateStateOnServer('onOffState', value=True, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
data_cycle_time = (dt.datetime.now() - get_data_time)
data_cycle_time = (dt.datetime.min + data_cycle_time).time()
self.logger.debug(u'[ {0} download: {1} seconds ]'.format(dev.name, data_cycle_time.strftime('%S.%f')))
return
else:
self.logger.error(u'The image destination must include one of the approved types (.gif, .jpg, .jpeg, .png)')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'Bad Type')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return False
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'[{0}] Error downloading satellite image.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | def getSatelliteImage(self, dev):
'\n Download satellite image and save to file\n\n The getSatelliteImage() method will download a file from a user- specified\n location and save it to a user-specified folder on the local server. This\n method is used by the Satellite Image Downloader device type.\n\n -----\n\n :param indigo.Device dev:\n '
destination = unicode(dev.pluginProps['imageDestinationLocation'])
source = unicode(dev.pluginProps['imageSourceLocation'])
try:
if destination.endswith(('.gif', '.jpg', '.jpeg', '.png')):
get_data_time = dt.datetime.now()
try:
self.logger.debug(u'Source: {0}'.format(source))
self.logger.debug(u'Destination: {0}'.format(destination))
r = requests.get(source, stream=True, timeout=20)
with open(destination, 'wb') as img:
for chunk in r.iter_content(2000):
img.write(chunk)
except requests.exceptions.ConnectionError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Error downloading satellite image. (No comm.)')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return
except NameError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
urllib.urlretrieve(source, destination)
dev.updateStateOnServer('onOffState', value=True, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
data_cycle_time = (dt.datetime.now() - get_data_time)
data_cycle_time = (dt.datetime.min + data_cycle_time).time()
self.logger.debug(u'[ {0} download: {1} seconds ]'.format(dev.name, data_cycle_time.strftime('%S.%f')))
return
else:
self.logger.error(u'The image destination must include one of the approved types (.gif, .jpg, .jpeg, .png)')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'Bad Type')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return False
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'[{0}] Error downloading satellite image.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)<|docstring|>Download satellite image and save to file
The getSatelliteImage() method will download a file from a user- specified
location and save it to a user-specified folder on the local server. This
method is used by the Satellite Image Downloader device type.
-----
:param indigo.Device dev:<|endoftext|> |
61da86a50d03ca7dec67ca9b50423e78a69ed7a83e4252984757e8654146cde3 | def getWUradar(self, dev):
'\n Get radar image through WU API\n\n The getWUradar() method will download a satellite image from Weather\n Underground. The construction of the image is based upon user preferences\n defined in the WUnderground Radar device type.\n\n -----\n\n :param indigo.Device dev:\n '
location = u''
name = unicode(dev.pluginProps['imagename'])
parms = u''
parms_dict = {'apiref': 'EXAMPLE_KEY', 'centerlat': float(dev.pluginProps.get('centerlat', 41.25)), 'centerlon': float(dev.pluginProps.get('centerlon', (- 87.65))), 'delay': int(dev.pluginProps.get('delay', 25)), 'feature': dev.pluginProps.get('feature', True), 'height': int(dev.pluginProps.get('height', 500)), 'imagetype': dev.pluginProps.get('imagetype', 'radius'), 'maxlat': float(dev.pluginProps.get('maxlat', 43.0)), 'maxlon': float(dev.pluginProps.get('maxlon', (- 90.5))), 'minlat': float(dev.pluginProps.get('minlat', 39.0)), 'minlon': float(dev.pluginProps.get('minlon', (- 86.5))), 'newmaps': dev.pluginProps.get('newmaps', False), 'noclutter': dev.pluginProps.get('noclutter', True), 'num': int(dev.pluginProps.get('num', 10)), 'radius': float(dev.pluginProps.get('radius', 150)), 'radunits': dev.pluginProps.get('radunits', 'nm'), 'rainsnow': dev.pluginProps.get('rainsnow', True), 'reproj.automerc': dev.pluginProps.get('Mercator', False), 'smooth': dev.pluginProps.get('smooth', 1), 'timelabel.x': int(dev.pluginProps.get('timelabelx', 10)), 'timelabel.y': int(dev.pluginProps.get('timelabely', 20)), 'timelabel': dev.pluginProps.get('timelabel', True), 'width': int(dev.pluginProps.get('width', 500))}
try:
if parms_dict['feature']:
radartype = 'animatedradar'
else:
radartype = 'radar'
if (parms_dict['imagetype'] == 'radius'):
for key in ('minlat', 'minlon', 'maxlat', 'maxlon', 'imagetype'):
del parms_dict[key]
elif (parms_dict['imagetype'] == 'boundingbox'):
for key in ('centerlat', 'centerlon', 'radius', 'imagetype'):
del parms_dict[key]
else:
for key in ('minlat', 'minlon', 'maxlat', 'maxlon', 'imagetype', 'centerlat', 'centerlon', 'radius'):
location = u'q/{0}'.format(dev.pluginProps['location'])
name = ''
del parms_dict[key]
if (not parms_dict['reproj.automerc']):
del parms_dict['reproj.automerc']
for (k, v) in parms_dict.iteritems():
if (str(v) == 'False'):
v = 0
elif (str(v) == 'True'):
v = 1
if (len(parms) < 1):
parms += '{0}={1}'.format(k, v)
else:
parms += '&{0}={1}'.format(k, v)
source = 'http://api.wunderground.com/api/{0}/{1}/{2}{3}{4}?{5}'.format(self.pluginPrefs['apiKey'], radartype, location, name, '.gif', parms)
destination = '{0}/IndigoWebServer/images/controls/static/{1}.gif'.format(indigo.server.getInstallFolderPath(), dev.pluginProps['imagename'])
try:
get_data_time = dt.datetime.now()
self.logger.debug(u'URL: {0}'.format(source))
r = requests.get(source, stream=True, timeout=20)
self.logger.debug(u'Status code: {0}'.format(r.status_code))
if (r.status_code == 200):
with open(destination, 'wb') as img:
for chunk in r.iter_content(1024):
img.write(chunk)
dev.updateStateOnServer('onOffState', value=True, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
data_cycle_time = (dt.datetime.now() - get_data_time)
data_cycle_time = (dt.datetime.min + data_cycle_time).time()
self.logger.debug(u'[ {0} download: {1} seconds ]'.format(dev.name, data_cycle_time.strftime('%S.%f')))
else:
self.logger.error(u'Error downloading image file: {0}'.format(r.status_code))
raise NameError
except requests.exceptions.ConnectionError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Error downloading satellite image. (No comm.)')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return
except NameError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
urllib.urlretrieve(source, destination)
self.callCount()
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Error downloading satellite image.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | Get radar image through WU API
The getWUradar() method will download a satellite image from Weather
Underground. The construction of the image is based upon user preferences
defined in the WUnderground Radar device type.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | getWUradar | DaveL17/WUnderground7 | 0 | python | def getWUradar(self, dev):
'\n Get radar image through WU API\n\n The getWUradar() method will download a satellite image from Weather\n Underground. The construction of the image is based upon user preferences\n defined in the WUnderground Radar device type.\n\n -----\n\n :param indigo.Device dev:\n '
location = u
name = unicode(dev.pluginProps['imagename'])
parms = u
parms_dict = {'apiref': 'EXAMPLE_KEY', 'centerlat': float(dev.pluginProps.get('centerlat', 41.25)), 'centerlon': float(dev.pluginProps.get('centerlon', (- 87.65))), 'delay': int(dev.pluginProps.get('delay', 25)), 'feature': dev.pluginProps.get('feature', True), 'height': int(dev.pluginProps.get('height', 500)), 'imagetype': dev.pluginProps.get('imagetype', 'radius'), 'maxlat': float(dev.pluginProps.get('maxlat', 43.0)), 'maxlon': float(dev.pluginProps.get('maxlon', (- 90.5))), 'minlat': float(dev.pluginProps.get('minlat', 39.0)), 'minlon': float(dev.pluginProps.get('minlon', (- 86.5))), 'newmaps': dev.pluginProps.get('newmaps', False), 'noclutter': dev.pluginProps.get('noclutter', True), 'num': int(dev.pluginProps.get('num', 10)), 'radius': float(dev.pluginProps.get('radius', 150)), 'radunits': dev.pluginProps.get('radunits', 'nm'), 'rainsnow': dev.pluginProps.get('rainsnow', True), 'reproj.automerc': dev.pluginProps.get('Mercator', False), 'smooth': dev.pluginProps.get('smooth', 1), 'timelabel.x': int(dev.pluginProps.get('timelabelx', 10)), 'timelabel.y': int(dev.pluginProps.get('timelabely', 20)), 'timelabel': dev.pluginProps.get('timelabel', True), 'width': int(dev.pluginProps.get('width', 500))}
try:
if parms_dict['feature']:
radartype = 'animatedradar'
else:
radartype = 'radar'
if (parms_dict['imagetype'] == 'radius'):
for key in ('minlat', 'minlon', 'maxlat', 'maxlon', 'imagetype'):
del parms_dict[key]
elif (parms_dict['imagetype'] == 'boundingbox'):
for key in ('centerlat', 'centerlon', 'radius', 'imagetype'):
del parms_dict[key]
else:
for key in ('minlat', 'minlon', 'maxlat', 'maxlon', 'imagetype', 'centerlat', 'centerlon', 'radius'):
location = u'q/{0}'.format(dev.pluginProps['location'])
name =
del parms_dict[key]
if (not parms_dict['reproj.automerc']):
del parms_dict['reproj.automerc']
for (k, v) in parms_dict.iteritems():
if (str(v) == 'False'):
v = 0
elif (str(v) == 'True'):
v = 1
if (len(parms) < 1):
parms += '{0}={1}'.format(k, v)
else:
parms += '&{0}={1}'.format(k, v)
source = 'http://api.wunderground.com/api/{0}/{1}/{2}{3}{4}?{5}'.format(self.pluginPrefs['apiKey'], radartype, location, name, '.gif', parms)
destination = '{0}/IndigoWebServer/images/controls/static/{1}.gif'.format(indigo.server.getInstallFolderPath(), dev.pluginProps['imagename'])
try:
get_data_time = dt.datetime.now()
self.logger.debug(u'URL: {0}'.format(source))
r = requests.get(source, stream=True, timeout=20)
self.logger.debug(u'Status code: {0}'.format(r.status_code))
if (r.status_code == 200):
with open(destination, 'wb') as img:
for chunk in r.iter_content(1024):
img.write(chunk)
dev.updateStateOnServer('onOffState', value=True, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
data_cycle_time = (dt.datetime.now() - get_data_time)
data_cycle_time = (dt.datetime.min + data_cycle_time).time()
self.logger.debug(u'[ {0} download: {1} seconds ]'.format(dev.name, data_cycle_time.strftime('%S.%f')))
else:
self.logger.error(u'Error downloading image file: {0}'.format(r.status_code))
raise NameError
except requests.exceptions.ConnectionError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Error downloading satellite image. (No comm.)')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return
except NameError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
urllib.urlretrieve(source, destination)
self.callCount()
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Error downloading satellite image.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | def getWUradar(self, dev):
'\n Get radar image through WU API\n\n The getWUradar() method will download a satellite image from Weather\n Underground. The construction of the image is based upon user preferences\n defined in the WUnderground Radar device type.\n\n -----\n\n :param indigo.Device dev:\n '
location = u
name = unicode(dev.pluginProps['imagename'])
parms = u
parms_dict = {'apiref': 'EXAMPLE_KEY', 'centerlat': float(dev.pluginProps.get('centerlat', 41.25)), 'centerlon': float(dev.pluginProps.get('centerlon', (- 87.65))), 'delay': int(dev.pluginProps.get('delay', 25)), 'feature': dev.pluginProps.get('feature', True), 'height': int(dev.pluginProps.get('height', 500)), 'imagetype': dev.pluginProps.get('imagetype', 'radius'), 'maxlat': float(dev.pluginProps.get('maxlat', 43.0)), 'maxlon': float(dev.pluginProps.get('maxlon', (- 90.5))), 'minlat': float(dev.pluginProps.get('minlat', 39.0)), 'minlon': float(dev.pluginProps.get('minlon', (- 86.5))), 'newmaps': dev.pluginProps.get('newmaps', False), 'noclutter': dev.pluginProps.get('noclutter', True), 'num': int(dev.pluginProps.get('num', 10)), 'radius': float(dev.pluginProps.get('radius', 150)), 'radunits': dev.pluginProps.get('radunits', 'nm'), 'rainsnow': dev.pluginProps.get('rainsnow', True), 'reproj.automerc': dev.pluginProps.get('Mercator', False), 'smooth': dev.pluginProps.get('smooth', 1), 'timelabel.x': int(dev.pluginProps.get('timelabelx', 10)), 'timelabel.y': int(dev.pluginProps.get('timelabely', 20)), 'timelabel': dev.pluginProps.get('timelabel', True), 'width': int(dev.pluginProps.get('width', 500))}
try:
if parms_dict['feature']:
radartype = 'animatedradar'
else:
radartype = 'radar'
if (parms_dict['imagetype'] == 'radius'):
for key in ('minlat', 'minlon', 'maxlat', 'maxlon', 'imagetype'):
del parms_dict[key]
elif (parms_dict['imagetype'] == 'boundingbox'):
for key in ('centerlat', 'centerlon', 'radius', 'imagetype'):
del parms_dict[key]
else:
for key in ('minlat', 'minlon', 'maxlat', 'maxlon', 'imagetype', 'centerlat', 'centerlon', 'radius'):
location = u'q/{0}'.format(dev.pluginProps['location'])
name =
del parms_dict[key]
if (not parms_dict['reproj.automerc']):
del parms_dict['reproj.automerc']
for (k, v) in parms_dict.iteritems():
if (str(v) == 'False'):
v = 0
elif (str(v) == 'True'):
v = 1
if (len(parms) < 1):
parms += '{0}={1}'.format(k, v)
else:
parms += '&{0}={1}'.format(k, v)
source = 'http://api.wunderground.com/api/{0}/{1}/{2}{3}{4}?{5}'.format(self.pluginPrefs['apiKey'], radartype, location, name, '.gif', parms)
destination = '{0}/IndigoWebServer/images/controls/static/{1}.gif'.format(indigo.server.getInstallFolderPath(), dev.pluginProps['imagename'])
try:
get_data_time = dt.datetime.now()
self.logger.debug(u'URL: {0}'.format(source))
r = requests.get(source, stream=True, timeout=20)
self.logger.debug(u'Status code: {0}'.format(r.status_code))
if (r.status_code == 200):
with open(destination, 'wb') as img:
for chunk in r.iter_content(1024):
img.write(chunk)
dev.updateStateOnServer('onOffState', value=True, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
data_cycle_time = (dt.datetime.now() - get_data_time)
data_cycle_time = (dt.datetime.min + data_cycle_time).time()
self.logger.debug(u'[ {0} download: {1} seconds ]'.format(dev.name, data_cycle_time.strftime('%S.%f')))
else:
self.logger.error(u'Error downloading image file: {0}'.format(r.status_code))
raise NameError
except requests.exceptions.ConnectionError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Error downloading satellite image. (No comm.)')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return
except NameError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
urllib.urlretrieve(source, destination)
self.callCount()
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Error downloading satellite image.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)<|docstring|>Get radar image through WU API
The getWUradar() method will download a satellite image from Weather
Underground. The construction of the image is based upon user preferences
defined in the WUnderground Radar device type.
-----
:param indigo.Device dev:<|endoftext|> |
466164a2fbb7de35490423628dbddc6360c080bdfb8316a075296d7c1c790699 | def getWeatherData(self, dev):
'\n Reach out to Weather Underground and download data for this location\n\n Grab the JSON return for the device. A separate call must be made for each\n weather device because the data are location specific.\n\n -----\n\n :param indigo.Device dev:\n '
try:
location = dev.pluginProps.get('location', 'autoip')
if (location == 'autoip'):
self.logger.warning(u"[{0}]. Automatically determining your location using 'autoip'.".format(dev.name))
if (location in self.masterWeatherDict.keys()):
self.logger.debug(u'Location [{0}] already in master weather dictionary.'.format(location))
else:
url = u'http://api.wunderground.com/api/{0}/geolookup/alerts_v11/almanac_v11/astronomy_v11/conditions_v11/forecast10day_v11/hourly_v11/lang:{1}/yesterday_v11/tide_v11/q/{2}.json?apiref=EXAMPLE_KEY'.format(self.pluginPrefs['apiKey'], self.pluginPrefs['language'], location)
self.logger.debug(u'URL for {0}: {1}'.format(location, url))
get_data_time = dt.datetime.now()
try:
f = requests.get(url, timeout=20)
simplejson_string = f.text
except NameError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
try:
socket.setdefaulttimeout(20)
f = urllib2.urlopen(url)
simplejson_string = f.read()
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Unable to reach Weather Underground. Sleeping until next scheduled poll.')
self.logger.debug(u'Unable to reach Weather Underground after 20 seconds.')
for dev in indigo.devices.itervalues('self'):
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return
data_cycle_time = (dt.datetime.now() - get_data_time)
data_cycle_time = (dt.datetime.min + data_cycle_time).time()
if (simplejson_string != ''):
self.logger.debug(u'[ {0} download: {1} seconds ]'.format(location, data_cycle_time.strftime('%S.%f')))
try:
parsed_simplejson = simplejson.loads(simplejson_string, encoding='utf-8')
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Unable to decode data.')
parsed_simplejson = {}
self.logger.debug(u'Adding weather data for {0} to Master Weather Dictionary.'.format(location))
self.masterWeatherDict[location] = parsed_simplejson
self.callCount()
dev.updateStateOnServer('onOffState', value=True)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Unable to reach Weather Underground. Sleeping until next scheduled poll.')
self.logger.debug(u'Unable to reach Weather Underground after 20 seconds.')
for dev in indigo.devices.itervalues('self'):
if dev.enabled:
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
self.wuOnline = False
self.wuOnline = True
return self.masterWeatherDict | Reach out to Weather Underground and download data for this location
Grab the JSON return for the device. A separate call must be made for each
weather device because the data are location specific.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | getWeatherData | DaveL17/WUnderground7 | 0 | python | def getWeatherData(self, dev):
'\n Reach out to Weather Underground and download data for this location\n\n Grab the JSON return for the device. A separate call must be made for each\n weather device because the data are location specific.\n\n -----\n\n :param indigo.Device dev:\n '
try:
location = dev.pluginProps.get('location', 'autoip')
if (location == 'autoip'):
self.logger.warning(u"[{0}]. Automatically determining your location using 'autoip'.".format(dev.name))
if (location in self.masterWeatherDict.keys()):
self.logger.debug(u'Location [{0}] already in master weather dictionary.'.format(location))
else:
url = u'http://api.wunderground.com/api/{0}/geolookup/alerts_v11/almanac_v11/astronomy_v11/conditions_v11/forecast10day_v11/hourly_v11/lang:{1}/yesterday_v11/tide_v11/q/{2}.json?apiref=EXAMPLE_KEY'.format(self.pluginPrefs['apiKey'], self.pluginPrefs['language'], location)
self.logger.debug(u'URL for {0}: {1}'.format(location, url))
get_data_time = dt.datetime.now()
try:
f = requests.get(url, timeout=20)
simplejson_string = f.text
except NameError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
try:
socket.setdefaulttimeout(20)
f = urllib2.urlopen(url)
simplejson_string = f.read()
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Unable to reach Weather Underground. Sleeping until next scheduled poll.')
self.logger.debug(u'Unable to reach Weather Underground after 20 seconds.')
for dev in indigo.devices.itervalues('self'):
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return
data_cycle_time = (dt.datetime.now() - get_data_time)
data_cycle_time = (dt.datetime.min + data_cycle_time).time()
if (simplejson_string != ):
self.logger.debug(u'[ {0} download: {1} seconds ]'.format(location, data_cycle_time.strftime('%S.%f')))
try:
parsed_simplejson = simplejson.loads(simplejson_string, encoding='utf-8')
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Unable to decode data.')
parsed_simplejson = {}
self.logger.debug(u'Adding weather data for {0} to Master Weather Dictionary.'.format(location))
self.masterWeatherDict[location] = parsed_simplejson
self.callCount()
dev.updateStateOnServer('onOffState', value=True)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Unable to reach Weather Underground. Sleeping until next scheduled poll.')
self.logger.debug(u'Unable to reach Weather Underground after 20 seconds.')
for dev in indigo.devices.itervalues('self'):
if dev.enabled:
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
self.wuOnline = False
self.wuOnline = True
return self.masterWeatherDict | def getWeatherData(self, dev):
'\n Reach out to Weather Underground and download data for this location\n\n Grab the JSON return for the device. A separate call must be made for each\n weather device because the data are location specific.\n\n -----\n\n :param indigo.Device dev:\n '
try:
location = dev.pluginProps.get('location', 'autoip')
if (location == 'autoip'):
self.logger.warning(u"[{0}]. Automatically determining your location using 'autoip'.".format(dev.name))
if (location in self.masterWeatherDict.keys()):
self.logger.debug(u'Location [{0}] already in master weather dictionary.'.format(location))
else:
url = u'http://api.wunderground.com/api/{0}/geolookup/alerts_v11/almanac_v11/astronomy_v11/conditions_v11/forecast10day_v11/hourly_v11/lang:{1}/yesterday_v11/tide_v11/q/{2}.json?apiref=EXAMPLE_KEY'.format(self.pluginPrefs['apiKey'], self.pluginPrefs['language'], location)
self.logger.debug(u'URL for {0}: {1}'.format(location, url))
get_data_time = dt.datetime.now()
try:
f = requests.get(url, timeout=20)
simplejson_string = f.text
except NameError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
try:
socket.setdefaulttimeout(20)
f = urllib2.urlopen(url)
simplejson_string = f.read()
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Unable to reach Weather Underground. Sleeping until next scheduled poll.')
self.logger.debug(u'Unable to reach Weather Underground after 20 seconds.')
for dev in indigo.devices.itervalues('self'):
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
return
data_cycle_time = (dt.datetime.now() - get_data_time)
data_cycle_time = (dt.datetime.min + data_cycle_time).time()
if (simplejson_string != ):
self.logger.debug(u'[ {0} download: {1} seconds ]'.format(location, data_cycle_time.strftime('%S.%f')))
try:
parsed_simplejson = simplejson.loads(simplejson_string, encoding='utf-8')
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Unable to decode data.')
parsed_simplejson = {}
self.logger.debug(u'Adding weather data for {0} to Master Weather Dictionary.'.format(location))
self.masterWeatherDict[location] = parsed_simplejson
self.callCount()
dev.updateStateOnServer('onOffState', value=True)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.warning(u'Unable to reach Weather Underground. Sleeping until next scheduled poll.')
self.logger.debug(u'Unable to reach Weather Underground after 20 seconds.')
for dev in indigo.devices.itervalues('self'):
if dev.enabled:
dev.updateStateOnServer('onOffState', value=False, uiValue=u'No comm')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
self.wuOnline = False
self.wuOnline = True
return self.masterWeatherDict<|docstring|>Reach out to Weather Underground and download data for this location
Grab the JSON return for the device. A separate call must be made for each
weather device because the data are location specific.
-----
:param indigo.Device dev:<|endoftext|> |
ac82605587c441a3a93a25787f744b281e471cbc3e990b4f46cbbe734d3367fb | def listOfDevices(self, filter, values_dict, target_id, trigger_id):
'\n Generate list of devices for offline trigger\n\n listOfDevices returns a list of plugin devices limited to weather\n devices only (not forecast devices, etc.) when the Weather Location Offline\n trigger is fired.\n\n -----\n\n :param str filter:\n :param indigo.Dict values_dict:\n :param str target_id:\n :param int trigger_id:\n '
return self.Fogbert.deviceList() | Generate list of devices for offline trigger
listOfDevices returns a list of plugin devices limited to weather
devices only (not forecast devices, etc.) when the Weather Location Offline
trigger is fired.
-----
:param str filter:
:param indigo.Dict values_dict:
:param str target_id:
:param int trigger_id: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | listOfDevices | DaveL17/WUnderground7 | 0 | python | def listOfDevices(self, filter, values_dict, target_id, trigger_id):
'\n Generate list of devices for offline trigger\n\n listOfDevices returns a list of plugin devices limited to weather\n devices only (not forecast devices, etc.) when the Weather Location Offline\n trigger is fired.\n\n -----\n\n :param str filter:\n :param indigo.Dict values_dict:\n :param str target_id:\n :param int trigger_id:\n '
return self.Fogbert.deviceList() | def listOfDevices(self, filter, values_dict, target_id, trigger_id):
'\n Generate list of devices for offline trigger\n\n listOfDevices returns a list of plugin devices limited to weather\n devices only (not forecast devices, etc.) when the Weather Location Offline\n trigger is fired.\n\n -----\n\n :param str filter:\n :param indigo.Dict values_dict:\n :param str target_id:\n :param int trigger_id:\n '
return self.Fogbert.deviceList()<|docstring|>Generate list of devices for offline trigger
listOfDevices returns a list of plugin devices limited to weather
devices only (not forecast devices, etc.) when the Weather Location Offline
trigger is fired.
-----
:param str filter:
:param indigo.Dict values_dict:
:param str target_id:
:param int trigger_id:<|endoftext|> |
56bcd9cc9398c42bcb232e0a6f4081e660907db8656bb13ce0aabe49678ced33 | def listOfWeatherDevices(self, filter, values_dict, target_id, trigger_id):
'\n Generate list of devices for severe weather alert trigger\n\n listOfDevices returns a list of plugin devices limited to weather devices only\n (not forecast devices, etc.) when severe weather alert trigger is fired.\n\n -----\n\n :param str filter:\n :param indigo.Dict values_dict:\n :param str target_id:\n :param int trigger_id:\n '
return self.Fogbert.deviceList(filter='self.wunderground') | Generate list of devices for severe weather alert trigger
listOfDevices returns a list of plugin devices limited to weather devices only
(not forecast devices, etc.) when severe weather alert trigger is fired.
-----
:param str filter:
:param indigo.Dict values_dict:
:param str target_id:
:param int trigger_id: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | listOfWeatherDevices | DaveL17/WUnderground7 | 0 | python | def listOfWeatherDevices(self, filter, values_dict, target_id, trigger_id):
'\n Generate list of devices for severe weather alert trigger\n\n listOfDevices returns a list of plugin devices limited to weather devices only\n (not forecast devices, etc.) when severe weather alert trigger is fired.\n\n -----\n\n :param str filter:\n :param indigo.Dict values_dict:\n :param str target_id:\n :param int trigger_id:\n '
return self.Fogbert.deviceList(filter='self.wunderground') | def listOfWeatherDevices(self, filter, values_dict, target_id, trigger_id):
'\n Generate list of devices for severe weather alert trigger\n\n listOfDevices returns a list of plugin devices limited to weather devices only\n (not forecast devices, etc.) when severe weather alert trigger is fired.\n\n -----\n\n :param str filter:\n :param indigo.Dict values_dict:\n :param str target_id:\n :param int trigger_id:\n '
return self.Fogbert.deviceList(filter='self.wunderground')<|docstring|>Generate list of devices for severe weather alert trigger
listOfDevices returns a list of plugin devices limited to weather devices only
(not forecast devices, etc.) when severe weather alert trigger is fired.
-----
:param str filter:
:param indigo.Dict values_dict:
:param str target_id:
:param int trigger_id:<|endoftext|> |
3bcb85dfc303979a41c903224569c1305aead53f4803d757041f2b9ba9d259c4 | def nestedLookup(self, obj, keys, default=u'Not available'):
"\n Do a nested lookup of the WU JSON\n\n The nestedLookup() method is used to extract the relevant data from the Weather\n Underground JSON return. The JSON is known to be inconsistent in the form of\n sometimes missing keys. This method allows for a default value to be used in\n instances where a key is missing. The method call can rely on the default\n return, or send an optional 'default=some_value' parameter.\n\n Credit: Jared Goguen at StackOverflow for initial implementation.\n\n -----\n\n :param obj:\n :param keys:\n :param default:\n "
current = obj
for key in keys:
current = (current if isinstance(current, list) else [current])
try:
current = next((sub[key] for sub in current if (key in sub)))
except StopIteration:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
return default
return current | Do a nested lookup of the WU JSON
The nestedLookup() method is used to extract the relevant data from the Weather
Underground JSON return. The JSON is known to be inconsistent in the form of
sometimes missing keys. This method allows for a default value to be used in
instances where a key is missing. The method call can rely on the default
return, or send an optional 'default=some_value' parameter.
Credit: Jared Goguen at StackOverflow for initial implementation.
-----
:param obj:
:param keys:
:param default: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | nestedLookup | DaveL17/WUnderground7 | 0 | python | def nestedLookup(self, obj, keys, default=u'Not available'):
"\n Do a nested lookup of the WU JSON\n\n The nestedLookup() method is used to extract the relevant data from the Weather\n Underground JSON return. The JSON is known to be inconsistent in the form of\n sometimes missing keys. This method allows for a default value to be used in\n instances where a key is missing. The method call can rely on the default\n return, or send an optional 'default=some_value' parameter.\n\n Credit: Jared Goguen at StackOverflow for initial implementation.\n\n -----\n\n :param obj:\n :param keys:\n :param default:\n "
current = obj
for key in keys:
current = (current if isinstance(current, list) else [current])
try:
current = next((sub[key] for sub in current if (key in sub)))
except StopIteration:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
return default
return current | def nestedLookup(self, obj, keys, default=u'Not available'):
"\n Do a nested lookup of the WU JSON\n\n The nestedLookup() method is used to extract the relevant data from the Weather\n Underground JSON return. The JSON is known to be inconsistent in the form of\n sometimes missing keys. This method allows for a default value to be used in\n instances where a key is missing. The method call can rely on the default\n return, or send an optional 'default=some_value' parameter.\n\n Credit: Jared Goguen at StackOverflow for initial implementation.\n\n -----\n\n :param obj:\n :param keys:\n :param default:\n "
current = obj
for key in keys:
current = (current if isinstance(current, list) else [current])
try:
current = next((sub[key] for sub in current if (key in sub)))
except StopIteration:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
return default
return current<|docstring|>Do a nested lookup of the WU JSON
The nestedLookup() method is used to extract the relevant data from the Weather
Underground JSON return. The JSON is known to be inconsistent in the form of
sometimes missing keys. This method allows for a default value to be used in
instances where a key is missing. The method call can rely on the default
return, or send an optional 'default=some_value' parameter.
Credit: Jared Goguen at StackOverflow for initial implementation.
-----
:param obj:
:param keys:
:param default:<|endoftext|> |
a6f3cffc8d950114d678fa4e778eeeb291319a37eb5e01dff5562f5187cbeb79 | def parseAlmanacData(self, dev):
'\n Parse almanac data to devices\n\n The parseAlmanacData() method takes selected almanac data and parses it\n to device states.\n\n -----\n\n :param indigo.Device dev:\n '
try:
almanac_states_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
airport_code = self.nestedLookup(weather_data, keys=('almanac', 'airport_code'))
current_observation = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
no_ui_format = {'tempHighRecordYear': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'recordyear')), 'tempLowRecordYear': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'recordyear'))}
ui_format_temp = {'tempHighNormalC': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'normal', 'C')), 'tempHighNormalF': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'normal', 'F')), 'tempHighRecordC': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'C')), 'tempHighRecordF': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'F')), 'tempLowNormalC': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'normal', 'C')), 'tempLowNormalF': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'normal', 'F')), 'tempLowRecordC': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'C')), 'tempLowRecordF': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'F'))}
almanac_states_list.append({'key': 'airportCode', 'value': airport_code, 'uiValue': airport_code})
almanac_states_list.append({'key': 'currentObservation', 'value': current_observation, 'uiValue': current_observation})
almanac_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
almanac_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr, 'uiValue': current_observation_24hr})
for (key, value) in no_ui_format.iteritems():
(value, ui_value) = self.fixCorruptedData(state_name=key, val=value)
almanac_states_list.append({'key': key, 'value': int(value), 'uiValue': ui_value})
for (key, value) in ui_format_temp.iteritems():
(value, ui_value) = self.fixCorruptedData(state_name=key, val=value)
ui_value = self.uiFormatTemperature(dev=dev, state_name=key, val=ui_value)
almanac_states_list.append({'key': key, 'value': value, 'uiValue': ui_value})
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
almanac_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(almanac_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except (KeyError, ValueError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing almanac data.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | Parse almanac data to devices
The parseAlmanacData() method takes selected almanac data and parses it
to device states.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | parseAlmanacData | DaveL17/WUnderground7 | 0 | python | def parseAlmanacData(self, dev):
'\n Parse almanac data to devices\n\n The parseAlmanacData() method takes selected almanac data and parses it\n to device states.\n\n -----\n\n :param indigo.Device dev:\n '
try:
almanac_states_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
airport_code = self.nestedLookup(weather_data, keys=('almanac', 'airport_code'))
current_observation = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
no_ui_format = {'tempHighRecordYear': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'recordyear')), 'tempLowRecordYear': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'recordyear'))}
ui_format_temp = {'tempHighNormalC': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'normal', 'C')), 'tempHighNormalF': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'normal', 'F')), 'tempHighRecordC': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'C')), 'tempHighRecordF': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'F')), 'tempLowNormalC': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'normal', 'C')), 'tempLowNormalF': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'normal', 'F')), 'tempLowRecordC': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'C')), 'tempLowRecordF': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'F'))}
almanac_states_list.append({'key': 'airportCode', 'value': airport_code, 'uiValue': airport_code})
almanac_states_list.append({'key': 'currentObservation', 'value': current_observation, 'uiValue': current_observation})
almanac_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
almanac_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr, 'uiValue': current_observation_24hr})
for (key, value) in no_ui_format.iteritems():
(value, ui_value) = self.fixCorruptedData(state_name=key, val=value)
almanac_states_list.append({'key': key, 'value': int(value), 'uiValue': ui_value})
for (key, value) in ui_format_temp.iteritems():
(value, ui_value) = self.fixCorruptedData(state_name=key, val=value)
ui_value = self.uiFormatTemperature(dev=dev, state_name=key, val=ui_value)
almanac_states_list.append({'key': key, 'value': value, 'uiValue': ui_value})
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
almanac_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(almanac_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except (KeyError, ValueError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing almanac data.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | def parseAlmanacData(self, dev):
'\n Parse almanac data to devices\n\n The parseAlmanacData() method takes selected almanac data and parses it\n to device states.\n\n -----\n\n :param indigo.Device dev:\n '
try:
almanac_states_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
airport_code = self.nestedLookup(weather_data, keys=('almanac', 'airport_code'))
current_observation = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
no_ui_format = {'tempHighRecordYear': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'recordyear')), 'tempLowRecordYear': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'recordyear'))}
ui_format_temp = {'tempHighNormalC': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'normal', 'C')), 'tempHighNormalF': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'normal', 'F')), 'tempHighRecordC': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'C')), 'tempHighRecordF': self.nestedLookup(weather_data, keys=('almanac', 'temp_high', 'record', 'F')), 'tempLowNormalC': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'normal', 'C')), 'tempLowNormalF': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'normal', 'F')), 'tempLowRecordC': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'C')), 'tempLowRecordF': self.nestedLookup(weather_data, keys=('almanac', 'temp_low', 'record', 'F'))}
almanac_states_list.append({'key': 'airportCode', 'value': airport_code, 'uiValue': airport_code})
almanac_states_list.append({'key': 'currentObservation', 'value': current_observation, 'uiValue': current_observation})
almanac_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
almanac_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr, 'uiValue': current_observation_24hr})
for (key, value) in no_ui_format.iteritems():
(value, ui_value) = self.fixCorruptedData(state_name=key, val=value)
almanac_states_list.append({'key': key, 'value': int(value), 'uiValue': ui_value})
for (key, value) in ui_format_temp.iteritems():
(value, ui_value) = self.fixCorruptedData(state_name=key, val=value)
ui_value = self.uiFormatTemperature(dev=dev, state_name=key, val=ui_value)
almanac_states_list.append({'key': key, 'value': value, 'uiValue': ui_value})
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
almanac_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(almanac_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except (KeyError, ValueError):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing almanac data.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)<|docstring|>Parse almanac data to devices
The parseAlmanacData() method takes selected almanac data and parses it
to device states.
-----
:param indigo.Device dev:<|endoftext|> |
8ee83792ae4107607c1b21dc8cf385905515a57a43d111bdf1b02284aae4e8b2 | def parseAlertsData(self, dev):
'\n Parse alerts data to devices\n\n The parseAlertsData() method takes weather alert data and parses it to device\n states.\n\n -----\n\n :param indigo.Device dev:\n '
attribution = u''
alerts_states_list = []
alerts_suppressed = dev.pluginProps.get('suppressWeatherAlerts', False)
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
alert_logging = self.pluginPrefs.get('alertLogging', True)
no_alert_logging = self.pluginPrefs.get('noAlertLogging', False)
alerts_data = self.nestedLookup(weather_data, keys=('alerts',))
location_city = self.nestedLookup(weather_data, keys=('location', 'city'))
current_observation = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
try:
alerts_states_list.append({'key': 'currentObservation', 'value': current_observation, 'uiValue': current_observation})
alerts_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
alerts_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
for alert_counter in range(1, 6):
alerts_states_list.append({'key': 'alertDescription{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
alerts_states_list.append({'key': 'alertExpires{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
alerts_states_list.append({'key': 'alertMessage{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
alerts_states_list.append({'key': 'alertType{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
if (not alerts_data):
alerts_states_list.append({'key': 'alertStatus', 'value': 'false', 'uiValue': u'False'})
if (alert_logging and (not no_alert_logging) and (not alerts_suppressed)):
self.logger.info(u'There are no severe weather alerts for the {0} location.'.format(location_city))
else:
alert_array = []
alerts_states_list.append({'key': 'alertStatus', 'value': 'true', 'uiValue': u'True'})
for item in alerts_data:
alert_text = u'{0}'.format(item['message'].strip())
alert_tuple = (u'{0}'.format(item['type']), u'{0}'.format(item['description']), u'{0}'.format(alert_text), u'{0}'.format(item['expires']))
alert_array.append(alert_tuple)
try:
tag_re = re.compile('(<!--.*?-->|<[^>]*>)')
no_tags = tag_re.sub('', item['attribution'])
clean = cgi.escape(no_tags)
attribution = u'European weather alert {0}'.format(clean)
except (KeyError, Exception):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
attribution = u''
if (len(alert_array) == 1):
if (alert_logging and (not alerts_suppressed)):
self.logger.info(u'There is 1 severe weather alert for the {0} location:'.format(location_city))
else:
if (alert_logging and (not alerts_suppressed)):
self.logger.info(u'There are {0} severe weather alerts for the {1} location:'.format(len(alert_array), u'{0}'.format(location_city)))
if (alert_logging and (not alerts_suppressed) and (len(alert_array) > 4)):
self.logger.info(u'The plugin only retains information for the first 5 alerts.')
self.logger.debug(u'{0}'.format(alert_array))
alert_counter = 1
for alert in range(len(alert_array)):
if (alert_counter < 6):
alerts_states_list.append({'key': u'alertType{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][0])})
alerts_states_list.append({'key': u'alertDescription{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][1])})
alerts_states_list.append({'key': u'alertMessage{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][2])})
alerts_states_list.append({'key': u'alertExpires{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][3])})
alert_counter += 1
if (alert_logging and (not alerts_suppressed)):
self.logger.info(u'\n{0}'.format(alert_array[alert][2]))
if (attribution != u''):
self.logger.info(attribution)
dev.updateStatesOnServer(alerts_states_list)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing weather alert data:')
alerts_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | Parse alerts data to devices
The parseAlertsData() method takes weather alert data and parses it to device
states.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | parseAlertsData | DaveL17/WUnderground7 | 0 | python | def parseAlertsData(self, dev):
'\n Parse alerts data to devices\n\n The parseAlertsData() method takes weather alert data and parses it to device\n states.\n\n -----\n\n :param indigo.Device dev:\n '
attribution = u
alerts_states_list = []
alerts_suppressed = dev.pluginProps.get('suppressWeatherAlerts', False)
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
alert_logging = self.pluginPrefs.get('alertLogging', True)
no_alert_logging = self.pluginPrefs.get('noAlertLogging', False)
alerts_data = self.nestedLookup(weather_data, keys=('alerts',))
location_city = self.nestedLookup(weather_data, keys=('location', 'city'))
current_observation = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
try:
alerts_states_list.append({'key': 'currentObservation', 'value': current_observation, 'uiValue': current_observation})
alerts_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
alerts_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
for alert_counter in range(1, 6):
alerts_states_list.append({'key': 'alertDescription{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
alerts_states_list.append({'key': 'alertExpires{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
alerts_states_list.append({'key': 'alertMessage{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
alerts_states_list.append({'key': 'alertType{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
if (not alerts_data):
alerts_states_list.append({'key': 'alertStatus', 'value': 'false', 'uiValue': u'False'})
if (alert_logging and (not no_alert_logging) and (not alerts_suppressed)):
self.logger.info(u'There are no severe weather alerts for the {0} location.'.format(location_city))
else:
alert_array = []
alerts_states_list.append({'key': 'alertStatus', 'value': 'true', 'uiValue': u'True'})
for item in alerts_data:
alert_text = u'{0}'.format(item['message'].strip())
alert_tuple = (u'{0}'.format(item['type']), u'{0}'.format(item['description']), u'{0}'.format(alert_text), u'{0}'.format(item['expires']))
alert_array.append(alert_tuple)
try:
tag_re = re.compile('(<!--.*?-->|<[^>]*>)')
no_tags = tag_re.sub(, item['attribution'])
clean = cgi.escape(no_tags)
attribution = u'European weather alert {0}'.format(clean)
except (KeyError, Exception):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
attribution = u
if (len(alert_array) == 1):
if (alert_logging and (not alerts_suppressed)):
self.logger.info(u'There is 1 severe weather alert for the {0} location:'.format(location_city))
else:
if (alert_logging and (not alerts_suppressed)):
self.logger.info(u'There are {0} severe weather alerts for the {1} location:'.format(len(alert_array), u'{0}'.format(location_city)))
if (alert_logging and (not alerts_suppressed) and (len(alert_array) > 4)):
self.logger.info(u'The plugin only retains information for the first 5 alerts.')
self.logger.debug(u'{0}'.format(alert_array))
alert_counter = 1
for alert in range(len(alert_array)):
if (alert_counter < 6):
alerts_states_list.append({'key': u'alertType{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][0])})
alerts_states_list.append({'key': u'alertDescription{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][1])})
alerts_states_list.append({'key': u'alertMessage{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][2])})
alerts_states_list.append({'key': u'alertExpires{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][3])})
alert_counter += 1
if (alert_logging and (not alerts_suppressed)):
self.logger.info(u'\n{0}'.format(alert_array[alert][2]))
if (attribution != u):
self.logger.info(attribution)
dev.updateStatesOnServer(alerts_states_list)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing weather alert data:')
alerts_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | def parseAlertsData(self, dev):
'\n Parse alerts data to devices\n\n The parseAlertsData() method takes weather alert data and parses it to device\n states.\n\n -----\n\n :param indigo.Device dev:\n '
attribution = u
alerts_states_list = []
alerts_suppressed = dev.pluginProps.get('suppressWeatherAlerts', False)
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
alert_logging = self.pluginPrefs.get('alertLogging', True)
no_alert_logging = self.pluginPrefs.get('noAlertLogging', False)
alerts_data = self.nestedLookup(weather_data, keys=('alerts',))
location_city = self.nestedLookup(weather_data, keys=('location', 'city'))
current_observation = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
try:
alerts_states_list.append({'key': 'currentObservation', 'value': current_observation, 'uiValue': current_observation})
alerts_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
alerts_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
for alert_counter in range(1, 6):
alerts_states_list.append({'key': 'alertDescription{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
alerts_states_list.append({'key': 'alertExpires{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
alerts_states_list.append({'key': 'alertMessage{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
alerts_states_list.append({'key': 'alertType{0}'.format(alert_counter), 'value': u' ', 'uiValue': u' '})
if (not alerts_data):
alerts_states_list.append({'key': 'alertStatus', 'value': 'false', 'uiValue': u'False'})
if (alert_logging and (not no_alert_logging) and (not alerts_suppressed)):
self.logger.info(u'There are no severe weather alerts for the {0} location.'.format(location_city))
else:
alert_array = []
alerts_states_list.append({'key': 'alertStatus', 'value': 'true', 'uiValue': u'True'})
for item in alerts_data:
alert_text = u'{0}'.format(item['message'].strip())
alert_tuple = (u'{0}'.format(item['type']), u'{0}'.format(item['description']), u'{0}'.format(alert_text), u'{0}'.format(item['expires']))
alert_array.append(alert_tuple)
try:
tag_re = re.compile('(<!--.*?-->|<[^>]*>)')
no_tags = tag_re.sub(, item['attribution'])
clean = cgi.escape(no_tags)
attribution = u'European weather alert {0}'.format(clean)
except (KeyError, Exception):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
attribution = u
if (len(alert_array) == 1):
if (alert_logging and (not alerts_suppressed)):
self.logger.info(u'There is 1 severe weather alert for the {0} location:'.format(location_city))
else:
if (alert_logging and (not alerts_suppressed)):
self.logger.info(u'There are {0} severe weather alerts for the {1} location:'.format(len(alert_array), u'{0}'.format(location_city)))
if (alert_logging and (not alerts_suppressed) and (len(alert_array) > 4)):
self.logger.info(u'The plugin only retains information for the first 5 alerts.')
self.logger.debug(u'{0}'.format(alert_array))
alert_counter = 1
for alert in range(len(alert_array)):
if (alert_counter < 6):
alerts_states_list.append({'key': u'alertType{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][0])})
alerts_states_list.append({'key': u'alertDescription{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][1])})
alerts_states_list.append({'key': u'alertMessage{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][2])})
alerts_states_list.append({'key': u'alertExpires{0}'.format(alert_counter), 'value': u'{0}'.format(alert_array[alert][3])})
alert_counter += 1
if (alert_logging and (not alerts_suppressed)):
self.logger.info(u'\n{0}'.format(alert_array[alert][2]))
if (attribution != u):
self.logger.info(attribution)
dev.updateStatesOnServer(alerts_states_list)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing weather alert data:')
alerts_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)<|docstring|>Parse alerts data to devices
The parseAlertsData() method takes weather alert data and parses it to device
states.
-----
:param indigo.Device dev:<|endoftext|> |
3c1272014e20658d41f75e2fa190d59a192e807b85278740a59b7e662b93c034 | def parseAstronomyData(self, dev):
'\n Parse astronomy data to devices\n\n The parseAstronomyData() method takes astronomy data and parses it to device\n states::\n\n Age of Moon (Integer: 0 - 31, units: days)\n Current Time Hour (Integer: 0 - 23, units: hours)\n Current Time Minute (Integer: 0 - 59, units: minutes)\n Hemisphere (String: North, South)\n Percent Illuminated (Integer: 0 - 100, units: percentage)\n Phase of Moon (String: Full, Waning Crescent...)\n\n Phase of Moon Icon (String, no spaces) 8 principal and intermediate phases::\n\n =========================================================\n 1. New Moon (P): + New_Moon\n 2. Waxing Crescent (I): + Waxing_Crescent\n 3. First Quarter (P): + First_Quarter\n 4. Waxing Gibbous (I): + Waxing_Gibbous\n 5. Full Moon (P): + Full_Moon\n 6. Waning Gibbous (I): + Waning_Gibbous\n 7. Last Quarter (P): + Last_Quarter\n 8. Waning Crescent (I): + Waning_Crescent\n\n -----\n\n :param indigo.Device dev:\n '
astronomy_states_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
current_observation = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
percent_illuminated = self.nestedLookup(weather_data, keys=('moon_phase', 'percentIlluminated'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
astronomy_dict = {'ageOfMoon': self.nestedLookup(weather_data, keys=('moon_phase', 'ageOfMoon')), 'currentTimeHour': self.nestedLookup(weather_data, keys=('moon_phase', 'current_time', 'hour')), 'currentTimeMinute': self.nestedLookup(weather_data, keys=('moon_phase', 'current_time', 'minute')), 'hemisphere': self.nestedLookup(weather_data, keys=('moon_phase', 'hemisphere')), 'phaseOfMoon': self.nestedLookup(weather_data, keys=('moon_phase', 'phaseofMoon')), 'sunriseHourMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunrise', 'hour')), 'sunriseHourSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunrise', 'hour')), 'sunriseMinuteMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunrise', 'minute')), 'sunriseMinuteSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunrise', 'minute')), 'sunsetHourMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunset', 'hour')), 'sunsetHourSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunset', 'hour')), 'sunsetMinuteMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunset', 'minute')), 'sunsetMinuteSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunset', 'minute'))}
try:
astronomy_states_list.append({'key': 'currentObservation', 'value': current_observation, 'uiValue': current_observation})
astronomy_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
astronomy_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr, 'uiValue': current_observation_24hr})
for (key, value) in astronomy_dict.iteritems():
astronomy_states_list.append({'key': key, 'value': value, 'uiValue': value})
phase_of_moon = astronomy_dict['phaseOfMoon'].replace(' ', '_')
astronomy_states_list.append({'key': 'phaseOfMoonIcon', 'value': phase_of_moon, 'uiValue': phase_of_moon})
percent_illuminated = self.floatEverything(state_name='Percent Illuminated', val=percent_illuminated)
astronomy_states_list.append({'key': 'percentIlluminated', 'value': percent_illuminated, 'uiValue': u'{0}'.format(percent_illuminated)})
year = dt.datetime.today().year
month = dt.datetime.today().month
day = dt.datetime.today().day
datetime_formatter = '{0} {1}'.format(self.date_format, self.time_format)
sunrise = dt.datetime(year, month, day, int(astronomy_dict['sunriseHourMoonphase']), int(astronomy_dict['sunriseMinuteMoonphase']))
sunset = dt.datetime(year, month, day, int(astronomy_dict['sunsetHourMoonphase']), int(astronomy_dict['sunsetMinuteMoonphase']))
sunrise_string = dt.datetime.strftime(sunrise, datetime_formatter)
astronomy_states_list.append({'key': 'sunriseString', 'value': sunrise_string})
sunset_string = dt.datetime.strftime(sunset, datetime_formatter)
astronomy_states_list.append({'key': 'sunsetString', 'value': sunset_string})
sunrise_epoch = int(time.mktime(sunrise.timetuple()))
astronomy_states_list.append({'key': 'sunriseEpoch', 'value': sunrise_epoch})
sunset_epoch = int(time.mktime(sunset.timetuple()))
astronomy_states_list.append({'key': 'sunsetEpoch', 'value': sunset_epoch})
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
astronomy_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(astronomy_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing astronomy data.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | Parse astronomy data to devices
The parseAstronomyData() method takes astronomy data and parses it to device
states::
Age of Moon (Integer: 0 - 31, units: days)
Current Time Hour (Integer: 0 - 23, units: hours)
Current Time Minute (Integer: 0 - 59, units: minutes)
Hemisphere (String: North, South)
Percent Illuminated (Integer: 0 - 100, units: percentage)
Phase of Moon (String: Full, Waning Crescent...)
Phase of Moon Icon (String, no spaces) 8 principal and intermediate phases::
=========================================================
1. New Moon (P): + New_Moon
2. Waxing Crescent (I): + Waxing_Crescent
3. First Quarter (P): + First_Quarter
4. Waxing Gibbous (I): + Waxing_Gibbous
5. Full Moon (P): + Full_Moon
6. Waning Gibbous (I): + Waning_Gibbous
7. Last Quarter (P): + Last_Quarter
8. Waning Crescent (I): + Waning_Crescent
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | parseAstronomyData | DaveL17/WUnderground7 | 0 | python | def parseAstronomyData(self, dev):
'\n Parse astronomy data to devices\n\n The parseAstronomyData() method takes astronomy data and parses it to device\n states::\n\n Age of Moon (Integer: 0 - 31, units: days)\n Current Time Hour (Integer: 0 - 23, units: hours)\n Current Time Minute (Integer: 0 - 59, units: minutes)\n Hemisphere (String: North, South)\n Percent Illuminated (Integer: 0 - 100, units: percentage)\n Phase of Moon (String: Full, Waning Crescent...)\n\n Phase of Moon Icon (String, no spaces) 8 principal and intermediate phases::\n\n =========================================================\n 1. New Moon (P): + New_Moon\n 2. Waxing Crescent (I): + Waxing_Crescent\n 3. First Quarter (P): + First_Quarter\n 4. Waxing Gibbous (I): + Waxing_Gibbous\n 5. Full Moon (P): + Full_Moon\n 6. Waning Gibbous (I): + Waning_Gibbous\n 7. Last Quarter (P): + Last_Quarter\n 8. Waning Crescent (I): + Waning_Crescent\n\n -----\n\n :param indigo.Device dev:\n '
astronomy_states_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
current_observation = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
percent_illuminated = self.nestedLookup(weather_data, keys=('moon_phase', 'percentIlluminated'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
astronomy_dict = {'ageOfMoon': self.nestedLookup(weather_data, keys=('moon_phase', 'ageOfMoon')), 'currentTimeHour': self.nestedLookup(weather_data, keys=('moon_phase', 'current_time', 'hour')), 'currentTimeMinute': self.nestedLookup(weather_data, keys=('moon_phase', 'current_time', 'minute')), 'hemisphere': self.nestedLookup(weather_data, keys=('moon_phase', 'hemisphere')), 'phaseOfMoon': self.nestedLookup(weather_data, keys=('moon_phase', 'phaseofMoon')), 'sunriseHourMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunrise', 'hour')), 'sunriseHourSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunrise', 'hour')), 'sunriseMinuteMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunrise', 'minute')), 'sunriseMinuteSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunrise', 'minute')), 'sunsetHourMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunset', 'hour')), 'sunsetHourSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunset', 'hour')), 'sunsetMinuteMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunset', 'minute')), 'sunsetMinuteSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunset', 'minute'))}
try:
astronomy_states_list.append({'key': 'currentObservation', 'value': current_observation, 'uiValue': current_observation})
astronomy_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
astronomy_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr, 'uiValue': current_observation_24hr})
for (key, value) in astronomy_dict.iteritems():
astronomy_states_list.append({'key': key, 'value': value, 'uiValue': value})
phase_of_moon = astronomy_dict['phaseOfMoon'].replace(' ', '_')
astronomy_states_list.append({'key': 'phaseOfMoonIcon', 'value': phase_of_moon, 'uiValue': phase_of_moon})
percent_illuminated = self.floatEverything(state_name='Percent Illuminated', val=percent_illuminated)
astronomy_states_list.append({'key': 'percentIlluminated', 'value': percent_illuminated, 'uiValue': u'{0}'.format(percent_illuminated)})
year = dt.datetime.today().year
month = dt.datetime.today().month
day = dt.datetime.today().day
datetime_formatter = '{0} {1}'.format(self.date_format, self.time_format)
sunrise = dt.datetime(year, month, day, int(astronomy_dict['sunriseHourMoonphase']), int(astronomy_dict['sunriseMinuteMoonphase']))
sunset = dt.datetime(year, month, day, int(astronomy_dict['sunsetHourMoonphase']), int(astronomy_dict['sunsetMinuteMoonphase']))
sunrise_string = dt.datetime.strftime(sunrise, datetime_formatter)
astronomy_states_list.append({'key': 'sunriseString', 'value': sunrise_string})
sunset_string = dt.datetime.strftime(sunset, datetime_formatter)
astronomy_states_list.append({'key': 'sunsetString', 'value': sunset_string})
sunrise_epoch = int(time.mktime(sunrise.timetuple()))
astronomy_states_list.append({'key': 'sunriseEpoch', 'value': sunrise_epoch})
sunset_epoch = int(time.mktime(sunset.timetuple()))
astronomy_states_list.append({'key': 'sunsetEpoch', 'value': sunset_epoch})
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
astronomy_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(astronomy_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing astronomy data.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | def parseAstronomyData(self, dev):
'\n Parse astronomy data to devices\n\n The parseAstronomyData() method takes astronomy data and parses it to device\n states::\n\n Age of Moon (Integer: 0 - 31, units: days)\n Current Time Hour (Integer: 0 - 23, units: hours)\n Current Time Minute (Integer: 0 - 59, units: minutes)\n Hemisphere (String: North, South)\n Percent Illuminated (Integer: 0 - 100, units: percentage)\n Phase of Moon (String: Full, Waning Crescent...)\n\n Phase of Moon Icon (String, no spaces) 8 principal and intermediate phases::\n\n =========================================================\n 1. New Moon (P): + New_Moon\n 2. Waxing Crescent (I): + Waxing_Crescent\n 3. First Quarter (P): + First_Quarter\n 4. Waxing Gibbous (I): + Waxing_Gibbous\n 5. Full Moon (P): + Full_Moon\n 6. Waning Gibbous (I): + Waning_Gibbous\n 7. Last Quarter (P): + Last_Quarter\n 8. Waning Crescent (I): + Waning_Crescent\n\n -----\n\n :param indigo.Device dev:\n '
astronomy_states_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
current_observation = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
percent_illuminated = self.nestedLookup(weather_data, keys=('moon_phase', 'percentIlluminated'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
astronomy_dict = {'ageOfMoon': self.nestedLookup(weather_data, keys=('moon_phase', 'ageOfMoon')), 'currentTimeHour': self.nestedLookup(weather_data, keys=('moon_phase', 'current_time', 'hour')), 'currentTimeMinute': self.nestedLookup(weather_data, keys=('moon_phase', 'current_time', 'minute')), 'hemisphere': self.nestedLookup(weather_data, keys=('moon_phase', 'hemisphere')), 'phaseOfMoon': self.nestedLookup(weather_data, keys=('moon_phase', 'phaseofMoon')), 'sunriseHourMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunrise', 'hour')), 'sunriseHourSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunrise', 'hour')), 'sunriseMinuteMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunrise', 'minute')), 'sunriseMinuteSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunrise', 'minute')), 'sunsetHourMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunset', 'hour')), 'sunsetHourSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunset', 'hour')), 'sunsetMinuteMoonphase': self.nestedLookup(weather_data, keys=('moon_phase', 'sunset', 'minute')), 'sunsetMinuteSunphase': self.nestedLookup(weather_data, keys=('sun_phase', 'sunset', 'minute'))}
try:
astronomy_states_list.append({'key': 'currentObservation', 'value': current_observation, 'uiValue': current_observation})
astronomy_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
astronomy_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr, 'uiValue': current_observation_24hr})
for (key, value) in astronomy_dict.iteritems():
astronomy_states_list.append({'key': key, 'value': value, 'uiValue': value})
phase_of_moon = astronomy_dict['phaseOfMoon'].replace(' ', '_')
astronomy_states_list.append({'key': 'phaseOfMoonIcon', 'value': phase_of_moon, 'uiValue': phase_of_moon})
percent_illuminated = self.floatEverything(state_name='Percent Illuminated', val=percent_illuminated)
astronomy_states_list.append({'key': 'percentIlluminated', 'value': percent_illuminated, 'uiValue': u'{0}'.format(percent_illuminated)})
year = dt.datetime.today().year
month = dt.datetime.today().month
day = dt.datetime.today().day
datetime_formatter = '{0} {1}'.format(self.date_format, self.time_format)
sunrise = dt.datetime(year, month, day, int(astronomy_dict['sunriseHourMoonphase']), int(astronomy_dict['sunriseMinuteMoonphase']))
sunset = dt.datetime(year, month, day, int(astronomy_dict['sunsetHourMoonphase']), int(astronomy_dict['sunsetMinuteMoonphase']))
sunrise_string = dt.datetime.strftime(sunrise, datetime_formatter)
astronomy_states_list.append({'key': 'sunriseString', 'value': sunrise_string})
sunset_string = dt.datetime.strftime(sunset, datetime_formatter)
astronomy_states_list.append({'key': 'sunsetString', 'value': sunset_string})
sunrise_epoch = int(time.mktime(sunrise.timetuple()))
astronomy_states_list.append({'key': 'sunriseEpoch', 'value': sunrise_epoch})
sunset_epoch = int(time.mktime(sunset.timetuple()))
astronomy_states_list.append({'key': 'sunsetEpoch', 'value': sunset_epoch})
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
astronomy_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(astronomy_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing astronomy data.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)<|docstring|>Parse astronomy data to devices
The parseAstronomyData() method takes astronomy data and parses it to device
states::
Age of Moon (Integer: 0 - 31, units: days)
Current Time Hour (Integer: 0 - 23, units: hours)
Current Time Minute (Integer: 0 - 59, units: minutes)
Hemisphere (String: North, South)
Percent Illuminated (Integer: 0 - 100, units: percentage)
Phase of Moon (String: Full, Waning Crescent...)
Phase of Moon Icon (String, no spaces) 8 principal and intermediate phases::
=========================================================
1. New Moon (P): + New_Moon
2. Waxing Crescent (I): + Waxing_Crescent
3. First Quarter (P): + First_Quarter
4. Waxing Gibbous (I): + Waxing_Gibbous
5. Full Moon (P): + Full_Moon
6. Waning Gibbous (I): + Waning_Gibbous
7. Last Quarter (P): + Last_Quarter
8. Waning Crescent (I): + Waning_Crescent
-----
:param indigo.Device dev:<|endoftext|> |
738c3d5d76802f8fabb209d9cd25142f53cbe8093a29190651ac6ea7a5266123 | def parseForecastData(self, dev):
"\n Parse forecast data to devices\n\n The parseForecastData() method takes weather forecast data and parses it to\n device states. (Note that this is only for the weather device and not for the\n hourly or 10 day forecast devices which have their own methods.) Note that we\n round most of the values because some PWSs report decimal precision (even\n though that doesn't make sense since it's unlikely that a site would forecast\n with that level of precision.\n\n -----\n\n :param indigo.Device dev:\n "
forecast_states_list = []
config_menu_units = dev.pluginProps.get('configMenuUnits', '')
location = dev.pluginProps['location']
wind_units = dev.pluginProps.get('windUnits', '')
weather_data = self.masterWeatherDict[location]
forecast_data_text = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))
forecast_data_simple = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday'))
try:
if (config_menu_units in ['M', 'MS']):
fore_counter = 1
for day in forecast_data_text:
if (fore_counter <= 8):
fore_text = self.nestedLookup(day, keys=('fcttext_metric',)).lstrip('\n')
icon = self.nestedLookup(day, keys=('icon',))
title = self.nestedLookup(day, keys=('title',))
forecast_states_list.append({'key': u'foreText{0}'.format(fore_counter), 'value': fore_text, 'uiValue': fore_text})
forecast_states_list.append({'key': u'icon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
forecast_states_list.append({'key': u'foreTitle{0}'.format(fore_counter), 'value': title, 'uiValue': title})
fore_counter += 1
fore_counter = 1
for day in forecast_data_simple:
if (fore_counter <= 4):
average_wind = self.nestedLookup(day, keys=('avewind', 'kph'))
conditions = self.nestedLookup(day, keys=('conditions',))
fore_day = self.nestedLookup(day, keys=('date', 'weekday'))
fore_high = self.nestedLookup(day, keys=('high', 'celsius'))
fore_low = self.nestedLookup(day, keys=('low', 'celsius'))
icon = self.nestedLookup(day, keys=('icon',))
max_humidity = self.nestedLookup(day, keys=('maxhumidity',))
pop = self.nestedLookup(day, keys=('pop',))
(value, ui_value) = self.fixCorruptedData(state_name='foreWind{0}'.format(fore_counter), val=average_wind)
if (config_menu_units == 'MS'):
value = (value / 3.6)
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
else:
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'conditions{0}'.format(fore_counter), 'value': conditions, 'uiValue': conditions})
forecast_states_list.append({'key': u'foreDay{0}'.format(fore_counter), 'value': fore_day, 'uiValue': fore_day})
(value, ui_value) = self.fixCorruptedData(state_name='foreHigh{0}'.format(fore_counter), val=fore_high)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreHigh{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHigh{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreLow{0}'.format(fore_counter), val=fore_low)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreLow{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreLow{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreHum{0}'.format(fore_counter), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='foreHum{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHum{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'foreIcon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
(value, ui_value) = self.fixCorruptedData(state_name='forePop{0}'.format(fore_counter), val=pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='forePop{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'forePop{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
fore_counter += 1
elif (config_menu_units == 'I'):
fore_counter = 1
for day in forecast_data_text:
if (fore_counter <= 8):
fore_text = self.nestedLookup(day, keys=('fcttext_metric',)).lstrip('\n')
icon = self.nestedLookup(day, keys=('icon',))
title = self.nestedLookup(day, keys=('title',))
forecast_states_list.append({'key': u'foreText{0}'.format(fore_counter), 'value': fore_text, 'uiValue': fore_text})
forecast_states_list.append({'key': u'icon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
forecast_states_list.append({'key': u'foreTitle{0}'.format(fore_counter), 'value': title, 'uiValue': title})
fore_counter += 1
fore_counter = 1
for day in forecast_data_simple:
if (fore_counter <= 4):
average_wind = self.nestedLookup(day, keys=('avewind', 'mph'))
conditions = self.nestedLookup(day, keys=('conditions',))
fore_day = self.nestedLookup(day, keys=('date', 'weekday'))
fore_high = self.nestedLookup(day, keys=('high', 'celsius'))
fore_low = self.nestedLookup(day, keys=('low', 'celsius'))
icon = self.nestedLookup(day, keys=('icon',))
max_humidity = self.nestedLookup(day, keys=('maxhumidity',))
pop = self.nestedLookup(day, keys=('pop',))
(value, ui_value) = self.fixCorruptedData(state_name='foreWind{0}'.format(fore_counter), val=average_wind)
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': u'{0}'.format(ui_value, wind_units)})
forecast_states_list.append({'key': u'conditions{0}'.format(fore_counter), 'value': conditions, 'uiValue': conditions})
forecast_states_list.append({'key': u'foreDay{0}'.format(fore_counter), 'value': fore_day, 'uiValue': fore_day})
(value, ui_value) = self.fixCorruptedData(state_name='foreHigh{0}'.format(fore_counter), val=fore_high)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreHigh{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHigh{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreLow{0}'.format(fore_counter), val=fore_low)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreLow{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreLow{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreHum{0}'.format(fore_counter), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='foreHum{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHum{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'foreIcon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
(value, ui_value) = self.fixCorruptedData(state_name='forePop{0}'.format(fore_counter), val=pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='forePop{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'forePop{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
fore_counter += 1
else:
fore_counter = 1
for day in forecast_data_text:
if (fore_counter <= 8):
fore_text = self.nestedLookup(day, keys=('fcttext',)).lstrip('\n')
icon = self.nestedLookup(day, keys=('icon',))
title = self.nestedLookup(day, keys=('title',))
forecast_states_list.append({'key': u'foreText{0}'.format(fore_counter), 'value': fore_text, 'uiValue': fore_text})
forecast_states_list.append({'key': u'icon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
forecast_states_list.append({'key': u'foreTitle{0}'.format(fore_counter), 'value': title, 'uiValue': title})
fore_counter += 1
fore_counter = 1
for day in forecast_data_simple:
if (fore_counter <= 4):
average_wind = self.nestedLookup(day, keys=('avewind', 'mph'))
conditions = self.nestedLookup(day, keys=('conditions',))
fore_day = self.nestedLookup(day, keys=('date', 'weekday'))
fore_high = self.nestedLookup(day, keys=('high', 'fahrenheit'))
fore_low = self.nestedLookup(day, keys=('low', 'fahrenheit'))
max_humidity = self.nestedLookup(day, keys=('maxhumidity',))
icon = self.nestedLookup(day, keys=('icon',))
pop = self.nestedLookup(day, keys=('pop',))
(value, ui_value) = self.fixCorruptedData(state_name='foreWind{0}'.format(fore_counter), val=average_wind)
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'conditions{0}'.format(fore_counter), 'value': conditions, 'uiValue': conditions})
forecast_states_list.append({'key': u'foreDay{0}'.format(fore_counter), 'value': fore_day, 'uiValue': fore_day})
(value, ui_value) = self.fixCorruptedData(state_name='foreHigh{0}'.format(fore_counter), val=fore_high)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreHigh{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHigh{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreLow{0}'.format(fore_counter), val=fore_low)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreLow{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreLow{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreHum{0}'.format(fore_counter), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='foreHum{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHum{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'foreIcon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
(value, ui_value) = self.fixCorruptedData(state_name='forePop{0}'.format(fore_counter), val=pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='forePop{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'forePop{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
fore_counter += 1
except (KeyError, Exception):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing weather forecast data.')
try:
diff_text = u''
try:
difference = (float(dev.states['foreHigh1']) - float(dev.states['historyHigh']))
except ValueError:
difference = (- 99)
if (difference == (- 99)):
diff_text = u'unknown'
elif (difference <= (- 5)):
diff_text = u'much colder'
elif ((- 5) < difference <= (- 1)):
diff_text = u'colder'
elif ((- 1) < difference <= 1):
diff_text = u'about the same'
elif (1 < difference <= 5):
diff_text = u'warmer'
elif (5 < difference):
diff_text = u'much warmer'
forecast_states_list.append({'key': 'foreTextShort', 'value': diff_text, 'uiValue': diff_text})
if (diff_text != u'unknown'):
forecast_states_list.append({'key': 'foreTextLong', 'value': u'Today is forecast to be {0} than yesterday.'.format(diff_text)})
else:
forecast_states_list.append({'key': 'foreTextLong', 'value': u"Unable to compare today's forecast with yesterday's high temperature."})
dev.updateStatesOnServer(forecast_states_list)
except (KeyError, Exception):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem comparing forecast and history data.')
for state in ['foreTextShort', 'foreTextLong']:
forecast_states_list.append({'key': state, 'value': u'Unknown', 'uiValue': u'Unknown'})
dev.updateStatesOnServer(forecast_states_list) | Parse forecast data to devices
The parseForecastData() method takes weather forecast data and parses it to
device states. (Note that this is only for the weather device and not for the
hourly or 10 day forecast devices which have their own methods.) Note that we
round most of the values because some PWSs report decimal precision (even
though that doesn't make sense since it's unlikely that a site would forecast
with that level of precision.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | parseForecastData | DaveL17/WUnderground7 | 0 | python | def parseForecastData(self, dev):
"\n Parse forecast data to devices\n\n The parseForecastData() method takes weather forecast data and parses it to\n device states. (Note that this is only for the weather device and not for the\n hourly or 10 day forecast devices which have their own methods.) Note that we\n round most of the values because some PWSs report decimal precision (even\n though that doesn't make sense since it's unlikely that a site would forecast\n with that level of precision.\n\n -----\n\n :param indigo.Device dev:\n "
forecast_states_list = []
config_menu_units = dev.pluginProps.get('configMenuUnits', )
location = dev.pluginProps['location']
wind_units = dev.pluginProps.get('windUnits', )
weather_data = self.masterWeatherDict[location]
forecast_data_text = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))
forecast_data_simple = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday'))
try:
if (config_menu_units in ['M', 'MS']):
fore_counter = 1
for day in forecast_data_text:
if (fore_counter <= 8):
fore_text = self.nestedLookup(day, keys=('fcttext_metric',)).lstrip('\n')
icon = self.nestedLookup(day, keys=('icon',))
title = self.nestedLookup(day, keys=('title',))
forecast_states_list.append({'key': u'foreText{0}'.format(fore_counter), 'value': fore_text, 'uiValue': fore_text})
forecast_states_list.append({'key': u'icon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
forecast_states_list.append({'key': u'foreTitle{0}'.format(fore_counter), 'value': title, 'uiValue': title})
fore_counter += 1
fore_counter = 1
for day in forecast_data_simple:
if (fore_counter <= 4):
average_wind = self.nestedLookup(day, keys=('avewind', 'kph'))
conditions = self.nestedLookup(day, keys=('conditions',))
fore_day = self.nestedLookup(day, keys=('date', 'weekday'))
fore_high = self.nestedLookup(day, keys=('high', 'celsius'))
fore_low = self.nestedLookup(day, keys=('low', 'celsius'))
icon = self.nestedLookup(day, keys=('icon',))
max_humidity = self.nestedLookup(day, keys=('maxhumidity',))
pop = self.nestedLookup(day, keys=('pop',))
(value, ui_value) = self.fixCorruptedData(state_name='foreWind{0}'.format(fore_counter), val=average_wind)
if (config_menu_units == 'MS'):
value = (value / 3.6)
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
else:
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'conditions{0}'.format(fore_counter), 'value': conditions, 'uiValue': conditions})
forecast_states_list.append({'key': u'foreDay{0}'.format(fore_counter), 'value': fore_day, 'uiValue': fore_day})
(value, ui_value) = self.fixCorruptedData(state_name='foreHigh{0}'.format(fore_counter), val=fore_high)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreHigh{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHigh{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreLow{0}'.format(fore_counter), val=fore_low)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreLow{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreLow{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreHum{0}'.format(fore_counter), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='foreHum{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHum{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'foreIcon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
(value, ui_value) = self.fixCorruptedData(state_name='forePop{0}'.format(fore_counter), val=pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='forePop{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'forePop{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
fore_counter += 1
elif (config_menu_units == 'I'):
fore_counter = 1
for day in forecast_data_text:
if (fore_counter <= 8):
fore_text = self.nestedLookup(day, keys=('fcttext_metric',)).lstrip('\n')
icon = self.nestedLookup(day, keys=('icon',))
title = self.nestedLookup(day, keys=('title',))
forecast_states_list.append({'key': u'foreText{0}'.format(fore_counter), 'value': fore_text, 'uiValue': fore_text})
forecast_states_list.append({'key': u'icon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
forecast_states_list.append({'key': u'foreTitle{0}'.format(fore_counter), 'value': title, 'uiValue': title})
fore_counter += 1
fore_counter = 1
for day in forecast_data_simple:
if (fore_counter <= 4):
average_wind = self.nestedLookup(day, keys=('avewind', 'mph'))
conditions = self.nestedLookup(day, keys=('conditions',))
fore_day = self.nestedLookup(day, keys=('date', 'weekday'))
fore_high = self.nestedLookup(day, keys=('high', 'celsius'))
fore_low = self.nestedLookup(day, keys=('low', 'celsius'))
icon = self.nestedLookup(day, keys=('icon',))
max_humidity = self.nestedLookup(day, keys=('maxhumidity',))
pop = self.nestedLookup(day, keys=('pop',))
(value, ui_value) = self.fixCorruptedData(state_name='foreWind{0}'.format(fore_counter), val=average_wind)
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': u'{0}'.format(ui_value, wind_units)})
forecast_states_list.append({'key': u'conditions{0}'.format(fore_counter), 'value': conditions, 'uiValue': conditions})
forecast_states_list.append({'key': u'foreDay{0}'.format(fore_counter), 'value': fore_day, 'uiValue': fore_day})
(value, ui_value) = self.fixCorruptedData(state_name='foreHigh{0}'.format(fore_counter), val=fore_high)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreHigh{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHigh{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreLow{0}'.format(fore_counter), val=fore_low)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreLow{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreLow{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreHum{0}'.format(fore_counter), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='foreHum{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHum{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'foreIcon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
(value, ui_value) = self.fixCorruptedData(state_name='forePop{0}'.format(fore_counter), val=pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='forePop{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'forePop{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
fore_counter += 1
else:
fore_counter = 1
for day in forecast_data_text:
if (fore_counter <= 8):
fore_text = self.nestedLookup(day, keys=('fcttext',)).lstrip('\n')
icon = self.nestedLookup(day, keys=('icon',))
title = self.nestedLookup(day, keys=('title',))
forecast_states_list.append({'key': u'foreText{0}'.format(fore_counter), 'value': fore_text, 'uiValue': fore_text})
forecast_states_list.append({'key': u'icon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
forecast_states_list.append({'key': u'foreTitle{0}'.format(fore_counter), 'value': title, 'uiValue': title})
fore_counter += 1
fore_counter = 1
for day in forecast_data_simple:
if (fore_counter <= 4):
average_wind = self.nestedLookup(day, keys=('avewind', 'mph'))
conditions = self.nestedLookup(day, keys=('conditions',))
fore_day = self.nestedLookup(day, keys=('date', 'weekday'))
fore_high = self.nestedLookup(day, keys=('high', 'fahrenheit'))
fore_low = self.nestedLookup(day, keys=('low', 'fahrenheit'))
max_humidity = self.nestedLookup(day, keys=('maxhumidity',))
icon = self.nestedLookup(day, keys=('icon',))
pop = self.nestedLookup(day, keys=('pop',))
(value, ui_value) = self.fixCorruptedData(state_name='foreWind{0}'.format(fore_counter), val=average_wind)
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'conditions{0}'.format(fore_counter), 'value': conditions, 'uiValue': conditions})
forecast_states_list.append({'key': u'foreDay{0}'.format(fore_counter), 'value': fore_day, 'uiValue': fore_day})
(value, ui_value) = self.fixCorruptedData(state_name='foreHigh{0}'.format(fore_counter), val=fore_high)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreHigh{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHigh{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreLow{0}'.format(fore_counter), val=fore_low)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreLow{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreLow{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreHum{0}'.format(fore_counter), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='foreHum{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHum{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'foreIcon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
(value, ui_value) = self.fixCorruptedData(state_name='forePop{0}'.format(fore_counter), val=pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='forePop{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'forePop{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
fore_counter += 1
except (KeyError, Exception):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing weather forecast data.')
try:
diff_text = u
try:
difference = (float(dev.states['foreHigh1']) - float(dev.states['historyHigh']))
except ValueError:
difference = (- 99)
if (difference == (- 99)):
diff_text = u'unknown'
elif (difference <= (- 5)):
diff_text = u'much colder'
elif ((- 5) < difference <= (- 1)):
diff_text = u'colder'
elif ((- 1) < difference <= 1):
diff_text = u'about the same'
elif (1 < difference <= 5):
diff_text = u'warmer'
elif (5 < difference):
diff_text = u'much warmer'
forecast_states_list.append({'key': 'foreTextShort', 'value': diff_text, 'uiValue': diff_text})
if (diff_text != u'unknown'):
forecast_states_list.append({'key': 'foreTextLong', 'value': u'Today is forecast to be {0} than yesterday.'.format(diff_text)})
else:
forecast_states_list.append({'key': 'foreTextLong', 'value': u"Unable to compare today's forecast with yesterday's high temperature."})
dev.updateStatesOnServer(forecast_states_list)
except (KeyError, Exception):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem comparing forecast and history data.')
for state in ['foreTextShort', 'foreTextLong']:
forecast_states_list.append({'key': state, 'value': u'Unknown', 'uiValue': u'Unknown'})
dev.updateStatesOnServer(forecast_states_list) | def parseForecastData(self, dev):
"\n Parse forecast data to devices\n\n The parseForecastData() method takes weather forecast data and parses it to\n device states. (Note that this is only for the weather device and not for the\n hourly or 10 day forecast devices which have their own methods.) Note that we\n round most of the values because some PWSs report decimal precision (even\n though that doesn't make sense since it's unlikely that a site would forecast\n with that level of precision.\n\n -----\n\n :param indigo.Device dev:\n "
forecast_states_list = []
config_menu_units = dev.pluginProps.get('configMenuUnits', )
location = dev.pluginProps['location']
wind_units = dev.pluginProps.get('windUnits', )
weather_data = self.masterWeatherDict[location]
forecast_data_text = self.nestedLookup(weather_data, keys=('forecast', 'txt_forecast', 'forecastday'))
forecast_data_simple = self.nestedLookup(weather_data, keys=('forecast', 'simpleforecast', 'forecastday'))
try:
if (config_menu_units in ['M', 'MS']):
fore_counter = 1
for day in forecast_data_text:
if (fore_counter <= 8):
fore_text = self.nestedLookup(day, keys=('fcttext_metric',)).lstrip('\n')
icon = self.nestedLookup(day, keys=('icon',))
title = self.nestedLookup(day, keys=('title',))
forecast_states_list.append({'key': u'foreText{0}'.format(fore_counter), 'value': fore_text, 'uiValue': fore_text})
forecast_states_list.append({'key': u'icon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
forecast_states_list.append({'key': u'foreTitle{0}'.format(fore_counter), 'value': title, 'uiValue': title})
fore_counter += 1
fore_counter = 1
for day in forecast_data_simple:
if (fore_counter <= 4):
average_wind = self.nestedLookup(day, keys=('avewind', 'kph'))
conditions = self.nestedLookup(day, keys=('conditions',))
fore_day = self.nestedLookup(day, keys=('date', 'weekday'))
fore_high = self.nestedLookup(day, keys=('high', 'celsius'))
fore_low = self.nestedLookup(day, keys=('low', 'celsius'))
icon = self.nestedLookup(day, keys=('icon',))
max_humidity = self.nestedLookup(day, keys=('maxhumidity',))
pop = self.nestedLookup(day, keys=('pop',))
(value, ui_value) = self.fixCorruptedData(state_name='foreWind{0}'.format(fore_counter), val=average_wind)
if (config_menu_units == 'MS'):
value = (value / 3.6)
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
else:
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'conditions{0}'.format(fore_counter), 'value': conditions, 'uiValue': conditions})
forecast_states_list.append({'key': u'foreDay{0}'.format(fore_counter), 'value': fore_day, 'uiValue': fore_day})
(value, ui_value) = self.fixCorruptedData(state_name='foreHigh{0}'.format(fore_counter), val=fore_high)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreHigh{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHigh{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreLow{0}'.format(fore_counter), val=fore_low)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreLow{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreLow{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreHum{0}'.format(fore_counter), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='foreHum{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHum{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'foreIcon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
(value, ui_value) = self.fixCorruptedData(state_name='forePop{0}'.format(fore_counter), val=pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='forePop{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'forePop{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
fore_counter += 1
elif (config_menu_units == 'I'):
fore_counter = 1
for day in forecast_data_text:
if (fore_counter <= 8):
fore_text = self.nestedLookup(day, keys=('fcttext_metric',)).lstrip('\n')
icon = self.nestedLookup(day, keys=('icon',))
title = self.nestedLookup(day, keys=('title',))
forecast_states_list.append({'key': u'foreText{0}'.format(fore_counter), 'value': fore_text, 'uiValue': fore_text})
forecast_states_list.append({'key': u'icon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
forecast_states_list.append({'key': u'foreTitle{0}'.format(fore_counter), 'value': title, 'uiValue': title})
fore_counter += 1
fore_counter = 1
for day in forecast_data_simple:
if (fore_counter <= 4):
average_wind = self.nestedLookup(day, keys=('avewind', 'mph'))
conditions = self.nestedLookup(day, keys=('conditions',))
fore_day = self.nestedLookup(day, keys=('date', 'weekday'))
fore_high = self.nestedLookup(day, keys=('high', 'celsius'))
fore_low = self.nestedLookup(day, keys=('low', 'celsius'))
icon = self.nestedLookup(day, keys=('icon',))
max_humidity = self.nestedLookup(day, keys=('maxhumidity',))
pop = self.nestedLookup(day, keys=('pop',))
(value, ui_value) = self.fixCorruptedData(state_name='foreWind{0}'.format(fore_counter), val=average_wind)
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': u'{0}'.format(ui_value, wind_units)})
forecast_states_list.append({'key': u'conditions{0}'.format(fore_counter), 'value': conditions, 'uiValue': conditions})
forecast_states_list.append({'key': u'foreDay{0}'.format(fore_counter), 'value': fore_day, 'uiValue': fore_day})
(value, ui_value) = self.fixCorruptedData(state_name='foreHigh{0}'.format(fore_counter), val=fore_high)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreHigh{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHigh{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreLow{0}'.format(fore_counter), val=fore_low)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreLow{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreLow{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreHum{0}'.format(fore_counter), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='foreHum{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHum{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'foreIcon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
(value, ui_value) = self.fixCorruptedData(state_name='forePop{0}'.format(fore_counter), val=pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='forePop{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'forePop{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
fore_counter += 1
else:
fore_counter = 1
for day in forecast_data_text:
if (fore_counter <= 8):
fore_text = self.nestedLookup(day, keys=('fcttext',)).lstrip('\n')
icon = self.nestedLookup(day, keys=('icon',))
title = self.nestedLookup(day, keys=('title',))
forecast_states_list.append({'key': u'foreText{0}'.format(fore_counter), 'value': fore_text, 'uiValue': fore_text})
forecast_states_list.append({'key': u'icon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
forecast_states_list.append({'key': u'foreTitle{0}'.format(fore_counter), 'value': title, 'uiValue': title})
fore_counter += 1
fore_counter = 1
for day in forecast_data_simple:
if (fore_counter <= 4):
average_wind = self.nestedLookup(day, keys=('avewind', 'mph'))
conditions = self.nestedLookup(day, keys=('conditions',))
fore_day = self.nestedLookup(day, keys=('date', 'weekday'))
fore_high = self.nestedLookup(day, keys=('high', 'fahrenheit'))
fore_low = self.nestedLookup(day, keys=('low', 'fahrenheit'))
max_humidity = self.nestedLookup(day, keys=('maxhumidity',))
icon = self.nestedLookup(day, keys=('icon',))
pop = self.nestedLookup(day, keys=('pop',))
(value, ui_value) = self.fixCorruptedData(state_name='foreWind{0}'.format(fore_counter), val=average_wind)
ui_value = self.uiFormatWind(dev=dev, state_name='foreWind{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreWind{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'conditions{0}'.format(fore_counter), 'value': conditions, 'uiValue': conditions})
forecast_states_list.append({'key': u'foreDay{0}'.format(fore_counter), 'value': fore_day, 'uiValue': fore_day})
(value, ui_value) = self.fixCorruptedData(state_name='foreHigh{0}'.format(fore_counter), val=fore_high)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreHigh{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHigh{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreLow{0}'.format(fore_counter), val=fore_low)
ui_value = self.uiFormatTemperature(dev=dev, state_name='foreLow{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreLow{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='foreHum{0}'.format(fore_counter), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='foreHum{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'foreHum{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
forecast_states_list.append({'key': u'foreIcon{0}'.format(fore_counter), 'value': icon, 'uiValue': icon})
(value, ui_value) = self.fixCorruptedData(state_name='forePop{0}'.format(fore_counter), val=pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='forePop{0}'.format(fore_counter), val=ui_value)
forecast_states_list.append({'key': u'forePop{0}'.format(fore_counter), 'value': round(value), 'uiValue': ui_value})
fore_counter += 1
except (KeyError, Exception):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing weather forecast data.')
try:
diff_text = u
try:
difference = (float(dev.states['foreHigh1']) - float(dev.states['historyHigh']))
except ValueError:
difference = (- 99)
if (difference == (- 99)):
diff_text = u'unknown'
elif (difference <= (- 5)):
diff_text = u'much colder'
elif ((- 5) < difference <= (- 1)):
diff_text = u'colder'
elif ((- 1) < difference <= 1):
diff_text = u'about the same'
elif (1 < difference <= 5):
diff_text = u'warmer'
elif (5 < difference):
diff_text = u'much warmer'
forecast_states_list.append({'key': 'foreTextShort', 'value': diff_text, 'uiValue': diff_text})
if (diff_text != u'unknown'):
forecast_states_list.append({'key': 'foreTextLong', 'value': u'Today is forecast to be {0} than yesterday.'.format(diff_text)})
else:
forecast_states_list.append({'key': 'foreTextLong', 'value': u"Unable to compare today's forecast with yesterday's high temperature."})
dev.updateStatesOnServer(forecast_states_list)
except (KeyError, Exception):
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem comparing forecast and history data.')
for state in ['foreTextShort', 'foreTextLong']:
forecast_states_list.append({'key': state, 'value': u'Unknown', 'uiValue': u'Unknown'})
dev.updateStatesOnServer(forecast_states_list)<|docstring|>Parse forecast data to devices
The parseForecastData() method takes weather forecast data and parses it to
device states. (Note that this is only for the weather device and not for the
hourly or 10 day forecast devices which have their own methods.) Note that we
round most of the values because some PWSs report decimal precision (even
though that doesn't make sense since it's unlikely that a site would forecast
with that level of precision.
-----
:param indigo.Device dev:<|endoftext|> |
56e5a7ab3af0ea22c4c63334ea165e3c0b4ba556f0c956ecd3f1904704757e43 | def parseHourlyData(self, dev):
'\n Parse hourly forecast data to devices\n\n The parseHourlyData() method takes hourly weather forecast data and parses it\n to device states.\n\n -----\n\n :param indigo.Device dev:\n '
hourly_forecast_states_list = []
config_menu_units = dev.pluginProps.get('configMenuUnits', '')
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
forecast_data = self.nestedLookup(weather_data, keys=('hourly_forecast',))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
try:
hourly_forecast_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
hourly_forecast_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
hourly_forecast_states_list.append({'key': 'currentObservation24hr', 'value': u'{0}'.format(current_observation_24hr)})
fore_counter = 1
for observation in forecast_data:
if (fore_counter <= 24):
civil_time = self.nestedLookup(observation, keys=('FCTTIME', 'civil'))
condition = self.nestedLookup(observation, keys=('condition',))
day = self.nestedLookup(observation, keys=('FCTTIME', 'mday_padded'))
fore_humidity = self.nestedLookup(observation, keys=('humidity',))
fore_pop = self.nestedLookup(observation, keys=('pop',))
fore_qpf_metric = self.nestedLookup(observation, keys=('qpf', 'metric'))
fore_qpf_standard = self.nestedLookup(observation, keys=('qpf', 'english'))
fore_snow_metric = self.nestedLookup(observation, keys=('snow', 'metric'))
fore_snow_standard = self.nestedLookup(observation, keys=('snow', 'english'))
fore_temp_metric = self.nestedLookup(observation, keys=('temp', 'metric'))
fore_temp_standard = self.nestedLookup(observation, keys=('temp', 'english'))
hour = self.nestedLookup(observation, keys=('FCTTIME', 'hour_padded'))
icon = self.nestedLookup(observation, keys=('icon',))
minute = self.nestedLookup(observation, keys=('FCTTIME', 'min'))
month = self.nestedLookup(observation, keys=('FCTTIME', 'mon_padded'))
wind_degrees = self.nestedLookup(observation, keys=('wdir', 'degrees'))
wind_dir = self.nestedLookup(observation, keys=('wdir', 'dir'))
wind_speed_metric = self.nestedLookup(observation, keys=('wspd', 'metric'))
wind_speed_standard = self.nestedLookup(observation, keys=('wspd', 'english'))
year = self.nestedLookup(observation, keys=('FCTTIME', 'year'))
wind_speed_mps = '{0}'.format((float(wind_speed_metric) * 0.277778))
if (fore_counter < 10):
fore_counter_text = u'0{0}'.format(fore_counter)
else:
fore_counter_text = fore_counter
hourly_forecast_states_list.append({'key': u'h{0}_cond'.format(fore_counter_text), 'value': condition, 'uiValue': condition})
hourly_forecast_states_list.append({'key': u'h{0}_icon'.format(fore_counter_text), 'value': icon, 'uiValue': icon})
hourly_forecast_states_list.append({'key': u'h{0}_proper_icon'.format(fore_counter_text), 'value': icon, 'uiValue': icon})
hourly_forecast_states_list.append({'key': u'h{0}_time'.format(fore_counter_text), 'value': civil_time, 'uiValue': civil_time})
hourly_forecast_states_list.append({'key': u'h{0}_windDirLong'.format(fore_counter_text), 'value': self.verboseWindNames('h{0}_windDirLong'.format(fore_counter_text), wind_dir)})
hourly_forecast_states_list.append({'key': u'h{0}_windDegrees'.format(fore_counter_text), 'value': int(wind_degrees), 'uiValue': str(int(wind_degrees))})
time_long = u'{0}-{1}-{2} {3}:{4}'.format(year, month, day, hour, minute)
hourly_forecast_states_list.append({'key': u'h{0}_timeLong'.format(fore_counter_text), 'value': time_long, 'uiValue': time_long})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_humidity'.format(fore_counter_text), val=fore_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='h{0}_humidity'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_humidity'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_precip'.format(fore_counter_text), val=fore_pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='h{0}_precip'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_precip'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units in ('M', 'MS', 'I')):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_temp'.format(fore_counter_text), val=fore_temp_metric)
ui_value = self.uiFormatTemperature(dev=dev, state_name='h{0}_temp'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_temp'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units == 'S'):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_temp'.format(fore_counter_text), val=fore_temp_standard)
ui_value = self.uiFormatTemperature(dev=dev, state_name='h{0}_temp'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_temp'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units == 'M'):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_windSpeed'.format(fore_counter_text), val=wind_speed_metric)
ui_value = self.uiFormatWind(dev=dev, state_name='h{0}_windSpeed'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
hourly_forecast_states_list.append({'key': u'h{0}_windSpeedIcon'.format(fore_counter_text), 'value': '{0}'.format(wind_speed_metric).replace('.', '')})
if (config_menu_units == 'MS'):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_windSpeed'.format(fore_counter_text), val=wind_speed_mps)
ui_value = self.uiFormatWind(dev=dev, state_name='h{0}_windSpeed'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
hourly_forecast_states_list.append({'key': u'h{0}_windSpeedIcon'.format(fore_counter_text), 'value': u'{0}'.format(wind_speed_mps).replace('.', '')})
if (config_menu_units in ('M', 'MS')):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_qpf'.format(fore_counter_text), val=fore_qpf_metric)
ui_value = self.uiFormatRain(dev=dev, state_name='h{0}_qpf'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_snow'.format(fore_counter_text), val=fore_snow_metric)
ui_value = self.uiFormatSnow(dev=dev, state_name='h{0}_snow'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units in ('I', 'S')):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_qpf'.format(fore_counter_text), val=fore_qpf_standard)
ui_value = self.uiFormatRain(dev=dev, state_name='h{0}_qpf'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_snow'.format(fore_counter_text), val=fore_snow_standard)
ui_value = self.uiFormatSnow(dev=dev, state_name='h{0}_snow'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_windSpeed'.format(fore_counter_text), val=wind_speed_standard)
ui_value = self.uiFormatWind(dev=dev, state_name='h{0}_windSpeed'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
hourly_forecast_states_list.append({'key': u'h{0}_windSpeedIcon'.format(fore_counter_text), 'value': u'{0}'.format(wind_speed_standard).replace('.', '')})
if (dev.pluginProps.get('configWindDirUnits', '') == 'DIR'):
hourly_forecast_states_list.append({'key': u'h{0}_windDir'.format(fore_counter_text), 'value': wind_dir, 'uiValue': wind_dir})
else:
hourly_forecast_states_list.append({'key': u'h{0}_windDir'.format(fore_counter_text), 'value': wind_degrees, 'uiValue': wind_degrees})
fore_counter += 1
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
hourly_forecast_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(hourly_forecast_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing hourly forecast data.')
hourly_forecast_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStatesOnServer(hourly_forecast_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | Parse hourly forecast data to devices
The parseHourlyData() method takes hourly weather forecast data and parses it
to device states.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | parseHourlyData | DaveL17/WUnderground7 | 0 | python | def parseHourlyData(self, dev):
'\n Parse hourly forecast data to devices\n\n The parseHourlyData() method takes hourly weather forecast data and parses it\n to device states.\n\n -----\n\n :param indigo.Device dev:\n '
hourly_forecast_states_list = []
config_menu_units = dev.pluginProps.get('configMenuUnits', )
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
forecast_data = self.nestedLookup(weather_data, keys=('hourly_forecast',))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
try:
hourly_forecast_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
hourly_forecast_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
hourly_forecast_states_list.append({'key': 'currentObservation24hr', 'value': u'{0}'.format(current_observation_24hr)})
fore_counter = 1
for observation in forecast_data:
if (fore_counter <= 24):
civil_time = self.nestedLookup(observation, keys=('FCTTIME', 'civil'))
condition = self.nestedLookup(observation, keys=('condition',))
day = self.nestedLookup(observation, keys=('FCTTIME', 'mday_padded'))
fore_humidity = self.nestedLookup(observation, keys=('humidity',))
fore_pop = self.nestedLookup(observation, keys=('pop',))
fore_qpf_metric = self.nestedLookup(observation, keys=('qpf', 'metric'))
fore_qpf_standard = self.nestedLookup(observation, keys=('qpf', 'english'))
fore_snow_metric = self.nestedLookup(observation, keys=('snow', 'metric'))
fore_snow_standard = self.nestedLookup(observation, keys=('snow', 'english'))
fore_temp_metric = self.nestedLookup(observation, keys=('temp', 'metric'))
fore_temp_standard = self.nestedLookup(observation, keys=('temp', 'english'))
hour = self.nestedLookup(observation, keys=('FCTTIME', 'hour_padded'))
icon = self.nestedLookup(observation, keys=('icon',))
minute = self.nestedLookup(observation, keys=('FCTTIME', 'min'))
month = self.nestedLookup(observation, keys=('FCTTIME', 'mon_padded'))
wind_degrees = self.nestedLookup(observation, keys=('wdir', 'degrees'))
wind_dir = self.nestedLookup(observation, keys=('wdir', 'dir'))
wind_speed_metric = self.nestedLookup(observation, keys=('wspd', 'metric'))
wind_speed_standard = self.nestedLookup(observation, keys=('wspd', 'english'))
year = self.nestedLookup(observation, keys=('FCTTIME', 'year'))
wind_speed_mps = '{0}'.format((float(wind_speed_metric) * 0.277778))
if (fore_counter < 10):
fore_counter_text = u'0{0}'.format(fore_counter)
else:
fore_counter_text = fore_counter
hourly_forecast_states_list.append({'key': u'h{0}_cond'.format(fore_counter_text), 'value': condition, 'uiValue': condition})
hourly_forecast_states_list.append({'key': u'h{0}_icon'.format(fore_counter_text), 'value': icon, 'uiValue': icon})
hourly_forecast_states_list.append({'key': u'h{0}_proper_icon'.format(fore_counter_text), 'value': icon, 'uiValue': icon})
hourly_forecast_states_list.append({'key': u'h{0}_time'.format(fore_counter_text), 'value': civil_time, 'uiValue': civil_time})
hourly_forecast_states_list.append({'key': u'h{0}_windDirLong'.format(fore_counter_text), 'value': self.verboseWindNames('h{0}_windDirLong'.format(fore_counter_text), wind_dir)})
hourly_forecast_states_list.append({'key': u'h{0}_windDegrees'.format(fore_counter_text), 'value': int(wind_degrees), 'uiValue': str(int(wind_degrees))})
time_long = u'{0}-{1}-{2} {3}:{4}'.format(year, month, day, hour, minute)
hourly_forecast_states_list.append({'key': u'h{0}_timeLong'.format(fore_counter_text), 'value': time_long, 'uiValue': time_long})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_humidity'.format(fore_counter_text), val=fore_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='h{0}_humidity'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_humidity'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_precip'.format(fore_counter_text), val=fore_pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='h{0}_precip'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_precip'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units in ('M', 'MS', 'I')):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_temp'.format(fore_counter_text), val=fore_temp_metric)
ui_value = self.uiFormatTemperature(dev=dev, state_name='h{0}_temp'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_temp'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units == 'S'):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_temp'.format(fore_counter_text), val=fore_temp_standard)
ui_value = self.uiFormatTemperature(dev=dev, state_name='h{0}_temp'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_temp'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units == 'M'):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_windSpeed'.format(fore_counter_text), val=wind_speed_metric)
ui_value = self.uiFormatWind(dev=dev, state_name='h{0}_windSpeed'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
hourly_forecast_states_list.append({'key': u'h{0}_windSpeedIcon'.format(fore_counter_text), 'value': '{0}'.format(wind_speed_metric).replace('.', )})
if (config_menu_units == 'MS'):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_windSpeed'.format(fore_counter_text), val=wind_speed_mps)
ui_value = self.uiFormatWind(dev=dev, state_name='h{0}_windSpeed'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
hourly_forecast_states_list.append({'key': u'h{0}_windSpeedIcon'.format(fore_counter_text), 'value': u'{0}'.format(wind_speed_mps).replace('.', )})
if (config_menu_units in ('M', 'MS')):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_qpf'.format(fore_counter_text), val=fore_qpf_metric)
ui_value = self.uiFormatRain(dev=dev, state_name='h{0}_qpf'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_snow'.format(fore_counter_text), val=fore_snow_metric)
ui_value = self.uiFormatSnow(dev=dev, state_name='h{0}_snow'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units in ('I', 'S')):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_qpf'.format(fore_counter_text), val=fore_qpf_standard)
ui_value = self.uiFormatRain(dev=dev, state_name='h{0}_qpf'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_snow'.format(fore_counter_text), val=fore_snow_standard)
ui_value = self.uiFormatSnow(dev=dev, state_name='h{0}_snow'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_windSpeed'.format(fore_counter_text), val=wind_speed_standard)
ui_value = self.uiFormatWind(dev=dev, state_name='h{0}_windSpeed'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
hourly_forecast_states_list.append({'key': u'h{0}_windSpeedIcon'.format(fore_counter_text), 'value': u'{0}'.format(wind_speed_standard).replace('.', )})
if (dev.pluginProps.get('configWindDirUnits', ) == 'DIR'):
hourly_forecast_states_list.append({'key': u'h{0}_windDir'.format(fore_counter_text), 'value': wind_dir, 'uiValue': wind_dir})
else:
hourly_forecast_states_list.append({'key': u'h{0}_windDir'.format(fore_counter_text), 'value': wind_degrees, 'uiValue': wind_degrees})
fore_counter += 1
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
hourly_forecast_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(hourly_forecast_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing hourly forecast data.')
hourly_forecast_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStatesOnServer(hourly_forecast_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | def parseHourlyData(self, dev):
'\n Parse hourly forecast data to devices\n\n The parseHourlyData() method takes hourly weather forecast data and parses it\n to device states.\n\n -----\n\n :param indigo.Device dev:\n '
hourly_forecast_states_list = []
config_menu_units = dev.pluginProps.get('configMenuUnits', )
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
forecast_data = self.nestedLookup(weather_data, keys=('hourly_forecast',))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
try:
hourly_forecast_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
hourly_forecast_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(int(current_observation_epoch)))
hourly_forecast_states_list.append({'key': 'currentObservation24hr', 'value': u'{0}'.format(current_observation_24hr)})
fore_counter = 1
for observation in forecast_data:
if (fore_counter <= 24):
civil_time = self.nestedLookup(observation, keys=('FCTTIME', 'civil'))
condition = self.nestedLookup(observation, keys=('condition',))
day = self.nestedLookup(observation, keys=('FCTTIME', 'mday_padded'))
fore_humidity = self.nestedLookup(observation, keys=('humidity',))
fore_pop = self.nestedLookup(observation, keys=('pop',))
fore_qpf_metric = self.nestedLookup(observation, keys=('qpf', 'metric'))
fore_qpf_standard = self.nestedLookup(observation, keys=('qpf', 'english'))
fore_snow_metric = self.nestedLookup(observation, keys=('snow', 'metric'))
fore_snow_standard = self.nestedLookup(observation, keys=('snow', 'english'))
fore_temp_metric = self.nestedLookup(observation, keys=('temp', 'metric'))
fore_temp_standard = self.nestedLookup(observation, keys=('temp', 'english'))
hour = self.nestedLookup(observation, keys=('FCTTIME', 'hour_padded'))
icon = self.nestedLookup(observation, keys=('icon',))
minute = self.nestedLookup(observation, keys=('FCTTIME', 'min'))
month = self.nestedLookup(observation, keys=('FCTTIME', 'mon_padded'))
wind_degrees = self.nestedLookup(observation, keys=('wdir', 'degrees'))
wind_dir = self.nestedLookup(observation, keys=('wdir', 'dir'))
wind_speed_metric = self.nestedLookup(observation, keys=('wspd', 'metric'))
wind_speed_standard = self.nestedLookup(observation, keys=('wspd', 'english'))
year = self.nestedLookup(observation, keys=('FCTTIME', 'year'))
wind_speed_mps = '{0}'.format((float(wind_speed_metric) * 0.277778))
if (fore_counter < 10):
fore_counter_text = u'0{0}'.format(fore_counter)
else:
fore_counter_text = fore_counter
hourly_forecast_states_list.append({'key': u'h{0}_cond'.format(fore_counter_text), 'value': condition, 'uiValue': condition})
hourly_forecast_states_list.append({'key': u'h{0}_icon'.format(fore_counter_text), 'value': icon, 'uiValue': icon})
hourly_forecast_states_list.append({'key': u'h{0}_proper_icon'.format(fore_counter_text), 'value': icon, 'uiValue': icon})
hourly_forecast_states_list.append({'key': u'h{0}_time'.format(fore_counter_text), 'value': civil_time, 'uiValue': civil_time})
hourly_forecast_states_list.append({'key': u'h{0}_windDirLong'.format(fore_counter_text), 'value': self.verboseWindNames('h{0}_windDirLong'.format(fore_counter_text), wind_dir)})
hourly_forecast_states_list.append({'key': u'h{0}_windDegrees'.format(fore_counter_text), 'value': int(wind_degrees), 'uiValue': str(int(wind_degrees))})
time_long = u'{0}-{1}-{2} {3}:{4}'.format(year, month, day, hour, minute)
hourly_forecast_states_list.append({'key': u'h{0}_timeLong'.format(fore_counter_text), 'value': time_long, 'uiValue': time_long})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_humidity'.format(fore_counter_text), val=fore_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='h{0}_humidity'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_humidity'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_precip'.format(fore_counter_text), val=fore_pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='h{0}_precip'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_precip'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units in ('M', 'MS', 'I')):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_temp'.format(fore_counter_text), val=fore_temp_metric)
ui_value = self.uiFormatTemperature(dev=dev, state_name='h{0}_temp'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_temp'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units == 'S'):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_temp'.format(fore_counter_text), val=fore_temp_standard)
ui_value = self.uiFormatTemperature(dev=dev, state_name='h{0}_temp'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_temp'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units == 'M'):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_windSpeed'.format(fore_counter_text), val=wind_speed_metric)
ui_value = self.uiFormatWind(dev=dev, state_name='h{0}_windSpeed'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
hourly_forecast_states_list.append({'key': u'h{0}_windSpeedIcon'.format(fore_counter_text), 'value': '{0}'.format(wind_speed_metric).replace('.', )})
if (config_menu_units == 'MS'):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_windSpeed'.format(fore_counter_text), val=wind_speed_mps)
ui_value = self.uiFormatWind(dev=dev, state_name='h{0}_windSpeed'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
hourly_forecast_states_list.append({'key': u'h{0}_windSpeedIcon'.format(fore_counter_text), 'value': u'{0}'.format(wind_speed_mps).replace('.', )})
if (config_menu_units in ('M', 'MS')):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_qpf'.format(fore_counter_text), val=fore_qpf_metric)
ui_value = self.uiFormatRain(dev=dev, state_name='h{0}_qpf'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_snow'.format(fore_counter_text), val=fore_snow_metric)
ui_value = self.uiFormatSnow(dev=dev, state_name='h{0}_snow'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units in ('I', 'S')):
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_qpf'.format(fore_counter_text), val=fore_qpf_standard)
ui_value = self.uiFormatRain(dev=dev, state_name='h{0}_qpf'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_snow'.format(fore_counter_text), val=fore_snow_standard)
ui_value = self.uiFormatSnow(dev=dev, state_name='h{0}_snow'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='h{0}_windSpeed'.format(fore_counter_text), val=wind_speed_standard)
ui_value = self.uiFormatWind(dev=dev, state_name='h{0}_windSpeed'.format(fore_counter_text), val=ui_value)
hourly_forecast_states_list.append({'key': u'h{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
hourly_forecast_states_list.append({'key': u'h{0}_windSpeedIcon'.format(fore_counter_text), 'value': u'{0}'.format(wind_speed_standard).replace('.', )})
if (dev.pluginProps.get('configWindDirUnits', ) == 'DIR'):
hourly_forecast_states_list.append({'key': u'h{0}_windDir'.format(fore_counter_text), 'value': wind_dir, 'uiValue': wind_dir})
else:
hourly_forecast_states_list.append({'key': u'h{0}_windDir'.format(fore_counter_text), 'value': wind_degrees, 'uiValue': wind_degrees})
fore_counter += 1
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
hourly_forecast_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(hourly_forecast_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing hourly forecast data.')
hourly_forecast_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStatesOnServer(hourly_forecast_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)<|docstring|>Parse hourly forecast data to devices
The parseHourlyData() method takes hourly weather forecast data and parses it
to device states.
-----
:param indigo.Device dev:<|endoftext|> |
24f031c4dbf5c338453eedc4d638aaa3f982ad21e233fd4c00c21486a7f246b2 | def parseTenDayData(self, dev):
'\n Parse ten day forecase data to devices\n\n The parseTenDayData() method takes 10 day forecast data and parses it to device\n states.\n\n -----\n\n :param indigo.Device dev:\n '
ten_day_forecast_states_list = []
config_menu_units = dev.pluginProps.get('configMenuUnits', '')
location = dev.pluginProps['location']
wind_speed_units = dev.pluginProps.get('configWindSpdUnits', '')
weather_data = self.masterWeatherDict[location]
forecast_day = self.masterWeatherDict[location].get('forecast', {}).get('simpleforecast', {}).get('forecastday', {})
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
try:
ten_day_forecast_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
ten_day_forecast_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(float(current_observation_epoch)))
ten_day_forecast_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
fore_counter = 1
for observation in forecast_day:
conditions = self.nestedLookup(observation, keys=('conditions',))
forecast_date = self.nestedLookup(observation, keys=('date', 'epoch'))
fore_pop = self.nestedLookup(observation, keys=('pop',))
fore_qpf_metric = self.nestedLookup(observation, keys=('qpf_allday', 'mm'))
fore_qpf_standard = self.nestedLookup(observation, keys=('qpf_allday', 'in'))
fore_snow_metric = self.nestedLookup(observation, keys=('snow_allday', 'cm'))
fore_snow_standard = self.nestedLookup(observation, keys=('snow_allday', 'in'))
high_temp_metric = self.nestedLookup(observation, keys=('high', 'celsius'))
high_temp_standard = self.nestedLookup(observation, keys=('high', 'fahrenheit'))
icon = self.nestedLookup(observation, keys=('icon',))
low_temp_metric = self.nestedLookup(observation, keys=('low', 'celsius'))
low_temp_standard = self.nestedLookup(observation, keys=('low', 'fahrenheit'))
max_humidity = self.nestedLookup(observation, keys=('maxhumidity',))
weekday = self.nestedLookup(observation, keys=('date', 'weekday'))
wind_avg_degrees = self.nestedLookup(observation, keys=('avewind', 'degrees'))
wind_avg_dir = self.nestedLookup(observation, keys=('avewind', 'dir'))
wind_avg_metric = self.nestedLookup(observation, keys=('avewind', 'kph'))
wind_avg_standard = self.nestedLookup(observation, keys=('avewind', 'mph'))
wind_max_degrees = self.nestedLookup(observation, keys=('maxwind', 'degrees'))
wind_max_dir = self.nestedLookup(observation, keys=('maxwind', 'dir'))
wind_max_metric = self.nestedLookup(observation, keys=('maxwind', 'kph'))
wind_max_standard = self.nestedLookup(observation, keys=('maxwind', 'mph'))
if (fore_counter <= 10):
if (fore_counter < 10):
fore_counter_text = '0{0}'.format(fore_counter)
else:
fore_counter_text = fore_counter
ten_day_forecast_states_list.append({'key': u'd{0}_conditions'.format(fore_counter_text), 'value': conditions, 'uiValue': conditions})
ten_day_forecast_states_list.append({'key': u'd{0}_day'.format(fore_counter_text), 'value': weekday, 'uiValue': weekday})
forecast_date = time.strftime('%Y-%m-%d', time.localtime(float(forecast_date)))
ten_day_forecast_states_list.append({'key': u'd{0}_date'.format(fore_counter_text), 'value': forecast_date, 'uiValue': forecast_date})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_pop'.format(fore_counter_text), val=fore_pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='d{0}_pop'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_pop'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_humidity'.format(fore_counter_text), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='d{0}_humidity'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_humidity'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
ten_day_forecast_states_list.append({'key': u'd{0}_icon'.format(fore_counter_text), 'value': u'{0}'.format(icon)})
if (wind_speed_units == 'AVG'):
wind_degrees = wind_avg_degrees
wind_dir = wind_avg_dir
else:
wind_degrees = wind_max_degrees
wind_dir = wind_max_dir
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_windDegrees'.format(fore_counter_text), val=wind_degrees)
ten_day_forecast_states_list.append({'key': u'd{0}_windDegrees'.format(fore_counter_text), 'value': int(value), 'uiValue': str(int(value))})
ten_day_forecast_states_list.append({'key': u'd{0}_windDir'.format(fore_counter_text), 'value': wind_dir, 'uiValue': wind_dir})
wind_long_name = self.verboseWindNames(state_name='d{0}_windDirLong'.format(fore_counter_text), val=wind_dir)
ten_day_forecast_states_list.append({'key': u'd{0}_windDirLong'.format(fore_counter_text), 'value': wind_long_name, 'uiValue': wind_long_name})
if (config_menu_units in ['I', 'M', 'MS']):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_high'.format(fore_counter_text), val=high_temp_metric)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_high'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_high'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_low'.format(fore_counter_text), val=low_temp_metric)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_low'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_low'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units in ['M', 'MS']):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_qpf'.format(fore_counter_text), val=fore_qpf_metric)
ui_value = self.uiFormatRain(dev=dev, state_name='d{0}_qpf'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_snow'.format(fore_counter_text), val=fore_snow_metric)
ui_value = self.uiFormatSnow(dev=dev, state_name='d{0}_snow'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (wind_speed_units == 'AVG'):
wind_value = wind_avg_metric
else:
wind_value = wind_max_metric
if (config_menu_units == 'MS'):
wind_value *= 0.277778
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_windSpeed'.format(fore_counter_text), val=wind_value)
ui_value = self.uiFormatWind(dev=dev, state_name='d{0}_windSpeed'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeedIcon'.format(fore_counter_text), 'value': unicode(wind_value).replace('.', '')})
if (config_menu_units in ['I', 'S']):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_qpf'.format(fore_counter_text), val=fore_qpf_standard)
ui_value = self.uiFormatRain(dev=dev, state_name='d{0}_qpf'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_snow'.format(fore_counter_text), val=fore_snow_standard)
ui_value = self.uiFormatSnow(dev=dev, state_name='d{0}_snow'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (wind_speed_units == 'AVG'):
wind_value = wind_avg_standard
else:
wind_value = wind_max_standard
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_windSpeed'.format(fore_counter_text), val=wind_value)
ui_value = self.uiFormatWind(dev=dev, state_name='d{0}_windSpeed'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeedIcon'.format(fore_counter_text), 'value': unicode(wind_value).replace('.', '')})
if (config_menu_units == 'S'):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_high'.format(fore_counter_text), val=high_temp_standard)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_high'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_high'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_low'.format(fore_counter_text), val=low_temp_standard)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_low'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_low'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
fore_counter += 1
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
ten_day_forecast_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(ten_day_forecast_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing 10-day forecast data.')
ten_day_forecast_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
dev.updateStatesOnServer(ten_day_forecast_states_list) | Parse ten day forecase data to devices
The parseTenDayData() method takes 10 day forecast data and parses it to device
states.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | parseTenDayData | DaveL17/WUnderground7 | 0 | python | def parseTenDayData(self, dev):
'\n Parse ten day forecase data to devices\n\n The parseTenDayData() method takes 10 day forecast data and parses it to device\n states.\n\n -----\n\n :param indigo.Device dev:\n '
ten_day_forecast_states_list = []
config_menu_units = dev.pluginProps.get('configMenuUnits', )
location = dev.pluginProps['location']
wind_speed_units = dev.pluginProps.get('configWindSpdUnits', )
weather_data = self.masterWeatherDict[location]
forecast_day = self.masterWeatherDict[location].get('forecast', {}).get('simpleforecast', {}).get('forecastday', {})
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
try:
ten_day_forecast_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
ten_day_forecast_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(float(current_observation_epoch)))
ten_day_forecast_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
fore_counter = 1
for observation in forecast_day:
conditions = self.nestedLookup(observation, keys=('conditions',))
forecast_date = self.nestedLookup(observation, keys=('date', 'epoch'))
fore_pop = self.nestedLookup(observation, keys=('pop',))
fore_qpf_metric = self.nestedLookup(observation, keys=('qpf_allday', 'mm'))
fore_qpf_standard = self.nestedLookup(observation, keys=('qpf_allday', 'in'))
fore_snow_metric = self.nestedLookup(observation, keys=('snow_allday', 'cm'))
fore_snow_standard = self.nestedLookup(observation, keys=('snow_allday', 'in'))
high_temp_metric = self.nestedLookup(observation, keys=('high', 'celsius'))
high_temp_standard = self.nestedLookup(observation, keys=('high', 'fahrenheit'))
icon = self.nestedLookup(observation, keys=('icon',))
low_temp_metric = self.nestedLookup(observation, keys=('low', 'celsius'))
low_temp_standard = self.nestedLookup(observation, keys=('low', 'fahrenheit'))
max_humidity = self.nestedLookup(observation, keys=('maxhumidity',))
weekday = self.nestedLookup(observation, keys=('date', 'weekday'))
wind_avg_degrees = self.nestedLookup(observation, keys=('avewind', 'degrees'))
wind_avg_dir = self.nestedLookup(observation, keys=('avewind', 'dir'))
wind_avg_metric = self.nestedLookup(observation, keys=('avewind', 'kph'))
wind_avg_standard = self.nestedLookup(observation, keys=('avewind', 'mph'))
wind_max_degrees = self.nestedLookup(observation, keys=('maxwind', 'degrees'))
wind_max_dir = self.nestedLookup(observation, keys=('maxwind', 'dir'))
wind_max_metric = self.nestedLookup(observation, keys=('maxwind', 'kph'))
wind_max_standard = self.nestedLookup(observation, keys=('maxwind', 'mph'))
if (fore_counter <= 10):
if (fore_counter < 10):
fore_counter_text = '0{0}'.format(fore_counter)
else:
fore_counter_text = fore_counter
ten_day_forecast_states_list.append({'key': u'd{0}_conditions'.format(fore_counter_text), 'value': conditions, 'uiValue': conditions})
ten_day_forecast_states_list.append({'key': u'd{0}_day'.format(fore_counter_text), 'value': weekday, 'uiValue': weekday})
forecast_date = time.strftime('%Y-%m-%d', time.localtime(float(forecast_date)))
ten_day_forecast_states_list.append({'key': u'd{0}_date'.format(fore_counter_text), 'value': forecast_date, 'uiValue': forecast_date})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_pop'.format(fore_counter_text), val=fore_pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='d{0}_pop'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_pop'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_humidity'.format(fore_counter_text), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='d{0}_humidity'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_humidity'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
ten_day_forecast_states_list.append({'key': u'd{0}_icon'.format(fore_counter_text), 'value': u'{0}'.format(icon)})
if (wind_speed_units == 'AVG'):
wind_degrees = wind_avg_degrees
wind_dir = wind_avg_dir
else:
wind_degrees = wind_max_degrees
wind_dir = wind_max_dir
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_windDegrees'.format(fore_counter_text), val=wind_degrees)
ten_day_forecast_states_list.append({'key': u'd{0}_windDegrees'.format(fore_counter_text), 'value': int(value), 'uiValue': str(int(value))})
ten_day_forecast_states_list.append({'key': u'd{0}_windDir'.format(fore_counter_text), 'value': wind_dir, 'uiValue': wind_dir})
wind_long_name = self.verboseWindNames(state_name='d{0}_windDirLong'.format(fore_counter_text), val=wind_dir)
ten_day_forecast_states_list.append({'key': u'd{0}_windDirLong'.format(fore_counter_text), 'value': wind_long_name, 'uiValue': wind_long_name})
if (config_menu_units in ['I', 'M', 'MS']):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_high'.format(fore_counter_text), val=high_temp_metric)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_high'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_high'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_low'.format(fore_counter_text), val=low_temp_metric)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_low'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_low'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units in ['M', 'MS']):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_qpf'.format(fore_counter_text), val=fore_qpf_metric)
ui_value = self.uiFormatRain(dev=dev, state_name='d{0}_qpf'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_snow'.format(fore_counter_text), val=fore_snow_metric)
ui_value = self.uiFormatSnow(dev=dev, state_name='d{0}_snow'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (wind_speed_units == 'AVG'):
wind_value = wind_avg_metric
else:
wind_value = wind_max_metric
if (config_menu_units == 'MS'):
wind_value *= 0.277778
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_windSpeed'.format(fore_counter_text), val=wind_value)
ui_value = self.uiFormatWind(dev=dev, state_name='d{0}_windSpeed'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeedIcon'.format(fore_counter_text), 'value': unicode(wind_value).replace('.', )})
if (config_menu_units in ['I', 'S']):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_qpf'.format(fore_counter_text), val=fore_qpf_standard)
ui_value = self.uiFormatRain(dev=dev, state_name='d{0}_qpf'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_snow'.format(fore_counter_text), val=fore_snow_standard)
ui_value = self.uiFormatSnow(dev=dev, state_name='d{0}_snow'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (wind_speed_units == 'AVG'):
wind_value = wind_avg_standard
else:
wind_value = wind_max_standard
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_windSpeed'.format(fore_counter_text), val=wind_value)
ui_value = self.uiFormatWind(dev=dev, state_name='d{0}_windSpeed'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeedIcon'.format(fore_counter_text), 'value': unicode(wind_value).replace('.', )})
if (config_menu_units == 'S'):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_high'.format(fore_counter_text), val=high_temp_standard)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_high'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_high'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_low'.format(fore_counter_text), val=low_temp_standard)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_low'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_low'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
fore_counter += 1
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
ten_day_forecast_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(ten_day_forecast_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing 10-day forecast data.')
ten_day_forecast_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
dev.updateStatesOnServer(ten_day_forecast_states_list) | def parseTenDayData(self, dev):
'\n Parse ten day forecase data to devices\n\n The parseTenDayData() method takes 10 day forecast data and parses it to device\n states.\n\n -----\n\n :param indigo.Device dev:\n '
ten_day_forecast_states_list = []
config_menu_units = dev.pluginProps.get('configMenuUnits', )
location = dev.pluginProps['location']
wind_speed_units = dev.pluginProps.get('configWindSpdUnits', )
weather_data = self.masterWeatherDict[location]
forecast_day = self.masterWeatherDict[location].get('forecast', {}).get('simpleforecast', {}).get('forecastday', {})
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
try:
ten_day_forecast_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
ten_day_forecast_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(float(current_observation_epoch)))
ten_day_forecast_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
fore_counter = 1
for observation in forecast_day:
conditions = self.nestedLookup(observation, keys=('conditions',))
forecast_date = self.nestedLookup(observation, keys=('date', 'epoch'))
fore_pop = self.nestedLookup(observation, keys=('pop',))
fore_qpf_metric = self.nestedLookup(observation, keys=('qpf_allday', 'mm'))
fore_qpf_standard = self.nestedLookup(observation, keys=('qpf_allday', 'in'))
fore_snow_metric = self.nestedLookup(observation, keys=('snow_allday', 'cm'))
fore_snow_standard = self.nestedLookup(observation, keys=('snow_allday', 'in'))
high_temp_metric = self.nestedLookup(observation, keys=('high', 'celsius'))
high_temp_standard = self.nestedLookup(observation, keys=('high', 'fahrenheit'))
icon = self.nestedLookup(observation, keys=('icon',))
low_temp_metric = self.nestedLookup(observation, keys=('low', 'celsius'))
low_temp_standard = self.nestedLookup(observation, keys=('low', 'fahrenheit'))
max_humidity = self.nestedLookup(observation, keys=('maxhumidity',))
weekday = self.nestedLookup(observation, keys=('date', 'weekday'))
wind_avg_degrees = self.nestedLookup(observation, keys=('avewind', 'degrees'))
wind_avg_dir = self.nestedLookup(observation, keys=('avewind', 'dir'))
wind_avg_metric = self.nestedLookup(observation, keys=('avewind', 'kph'))
wind_avg_standard = self.nestedLookup(observation, keys=('avewind', 'mph'))
wind_max_degrees = self.nestedLookup(observation, keys=('maxwind', 'degrees'))
wind_max_dir = self.nestedLookup(observation, keys=('maxwind', 'dir'))
wind_max_metric = self.nestedLookup(observation, keys=('maxwind', 'kph'))
wind_max_standard = self.nestedLookup(observation, keys=('maxwind', 'mph'))
if (fore_counter <= 10):
if (fore_counter < 10):
fore_counter_text = '0{0}'.format(fore_counter)
else:
fore_counter_text = fore_counter
ten_day_forecast_states_list.append({'key': u'd{0}_conditions'.format(fore_counter_text), 'value': conditions, 'uiValue': conditions})
ten_day_forecast_states_list.append({'key': u'd{0}_day'.format(fore_counter_text), 'value': weekday, 'uiValue': weekday})
forecast_date = time.strftime('%Y-%m-%d', time.localtime(float(forecast_date)))
ten_day_forecast_states_list.append({'key': u'd{0}_date'.format(fore_counter_text), 'value': forecast_date, 'uiValue': forecast_date})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_pop'.format(fore_counter_text), val=fore_pop)
ui_value = self.uiFormatPercentage(dev=dev, state_name='d{0}_pop'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_pop'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_humidity'.format(fore_counter_text), val=max_humidity)
ui_value = self.uiFormatPercentage(dev=dev, state_name='d{0}_humidity'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_humidity'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
ten_day_forecast_states_list.append({'key': u'd{0}_icon'.format(fore_counter_text), 'value': u'{0}'.format(icon)})
if (wind_speed_units == 'AVG'):
wind_degrees = wind_avg_degrees
wind_dir = wind_avg_dir
else:
wind_degrees = wind_max_degrees
wind_dir = wind_max_dir
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_windDegrees'.format(fore_counter_text), val=wind_degrees)
ten_day_forecast_states_list.append({'key': u'd{0}_windDegrees'.format(fore_counter_text), 'value': int(value), 'uiValue': str(int(value))})
ten_day_forecast_states_list.append({'key': u'd{0}_windDir'.format(fore_counter_text), 'value': wind_dir, 'uiValue': wind_dir})
wind_long_name = self.verboseWindNames(state_name='d{0}_windDirLong'.format(fore_counter_text), val=wind_dir)
ten_day_forecast_states_list.append({'key': u'd{0}_windDirLong'.format(fore_counter_text), 'value': wind_long_name, 'uiValue': wind_long_name})
if (config_menu_units in ['I', 'M', 'MS']):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_high'.format(fore_counter_text), val=high_temp_metric)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_high'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_high'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_low'.format(fore_counter_text), val=low_temp_metric)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_low'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_low'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (config_menu_units in ['M', 'MS']):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_qpf'.format(fore_counter_text), val=fore_qpf_metric)
ui_value = self.uiFormatRain(dev=dev, state_name='d{0}_qpf'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_snow'.format(fore_counter_text), val=fore_snow_metric)
ui_value = self.uiFormatSnow(dev=dev, state_name='d{0}_snow'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (wind_speed_units == 'AVG'):
wind_value = wind_avg_metric
else:
wind_value = wind_max_metric
if (config_menu_units == 'MS'):
wind_value *= 0.277778
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_windSpeed'.format(fore_counter_text), val=wind_value)
ui_value = self.uiFormatWind(dev=dev, state_name='d{0}_windSpeed'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeedIcon'.format(fore_counter_text), 'value': unicode(wind_value).replace('.', )})
if (config_menu_units in ['I', 'S']):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_qpf'.format(fore_counter_text), val=fore_qpf_standard)
ui_value = self.uiFormatRain(dev=dev, state_name='d{0}_qpf'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_qpf'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_snow'.format(fore_counter_text), val=fore_snow_standard)
ui_value = self.uiFormatSnow(dev=dev, state_name='d{0}_snow'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_snow'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
if (wind_speed_units == 'AVG'):
wind_value = wind_avg_standard
else:
wind_value = wind_max_standard
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_windSpeed'.format(fore_counter_text), val=wind_value)
ui_value = self.uiFormatWind(dev=dev, state_name='d{0}_windSpeed'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeed'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
ten_day_forecast_states_list.append({'key': u'd{0}_windSpeedIcon'.format(fore_counter_text), 'value': unicode(wind_value).replace('.', )})
if (config_menu_units == 'S'):
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_high'.format(fore_counter_text), val=high_temp_standard)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_high'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_high'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
(value, ui_value) = self.fixCorruptedData(state_name='d{0}_low'.format(fore_counter_text), val=low_temp_standard)
ui_value = self.uiFormatTemperature(dev=dev, state_name='d{0}_low'.format(fore_counter_text), val=ui_value)
ten_day_forecast_states_list.append({'key': u'd{0}_low'.format(fore_counter_text), 'value': value, 'uiValue': ui_value})
fore_counter += 1
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
ten_day_forecast_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(ten_day_forecast_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing 10-day forecast data.')
ten_day_forecast_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
dev.updateStatesOnServer(ten_day_forecast_states_list)<|docstring|>Parse ten day forecase data to devices
The parseTenDayData() method takes 10 day forecast data and parses it to device
states.
-----
:param indigo.Device dev:<|endoftext|> |
4d0189cebbe13b26146fabf1b391af8a34d3a1cfbba326e5171e7d3694d31e17 | def parseTidesData(self, dev):
'\n Parse tides data to devices\n\n The parseTidesData() method takes tide data and parses it to device states.\n\n -----\n\n :param indigo.Device dev:\n '
tide_states_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
tide_min_height = self.nestedLookup(weather_data, keys=('tide', 'tideSummaryStats', 'minheight'))
tide_max_height = self.nestedLookup(weather_data, keys=('tide', 'tideSummaryStats', 'maxheight'))
tide_site = self.nestedLookup(weather_data, keys=('tide', 'tideInfo', 'tideSite'))
tide_summary = self.nestedLookup(weather_data, keys=('tide', 'tideSummary'))
try:
tide_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
tide_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(float(current_observation_epoch)))
tide_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
if (tide_site in [u'', u' ']):
tide_states_list.append({'key': 'tideSite', 'value': u'No tide info.'})
else:
tide_states_list.append({'key': 'tideSite', 'value': tide_site, 'uiValue': tide_site})
if (tide_min_height == 99):
tide_states_list.append({'key': 'minHeight', 'value': tide_min_height, 'uiValue': u'--'})
else:
tide_states_list.append({'key': 'minHeight', 'value': tide_min_height, 'uiValue': tide_min_height})
if (tide_max_height == (- 99)):
tide_states_list.append({'key': 'maxHeight', 'value': tide_max_height, 'uiValue': u'--'})
else:
tide_states_list.append({'key': 'maxHeight', 'value': tide_max_height})
tide_counter = 1
if len(tide_summary):
for observation in tide_summary:
if (tide_counter < 32):
pretty = self.nestedLookup(observation, keys=('date', 'pretty'))
tide_height = self.nestedLookup(observation, keys=('data', 'height'))
tide_type = self.nestedLookup(observation, keys=('data', 'type'))
tide_states_list.append({'key': u'p{0}_height'.format(tide_counter), 'value': tide_height, 'uiValue': tide_height})
tide_states_list.append({'key': u'p{0}_pretty'.format(tide_counter), 'value': pretty, 'uiValue': pretty})
tide_states_list.append({'key': u'p{0}_type'.format(tide_counter), 'value': tide_type, 'uiValue': tide_type})
tide_counter += 1
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
tide_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(tide_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing tide data.')
self.logger.error(u'Note: Tide information may not be available in your area. Check Weather Underground for more information.')
tide_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
dev.updateStatesOnServer(tide_states_list) | Parse tides data to devices
The parseTidesData() method takes tide data and parses it to device states.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | parseTidesData | DaveL17/WUnderground7 | 0 | python | def parseTidesData(self, dev):
'\n Parse tides data to devices\n\n The parseTidesData() method takes tide data and parses it to device states.\n\n -----\n\n :param indigo.Device dev:\n '
tide_states_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
tide_min_height = self.nestedLookup(weather_data, keys=('tide', 'tideSummaryStats', 'minheight'))
tide_max_height = self.nestedLookup(weather_data, keys=('tide', 'tideSummaryStats', 'maxheight'))
tide_site = self.nestedLookup(weather_data, keys=('tide', 'tideInfo', 'tideSite'))
tide_summary = self.nestedLookup(weather_data, keys=('tide', 'tideSummary'))
try:
tide_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
tide_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(float(current_observation_epoch)))
tide_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
if (tide_site in [u, u' ']):
tide_states_list.append({'key': 'tideSite', 'value': u'No tide info.'})
else:
tide_states_list.append({'key': 'tideSite', 'value': tide_site, 'uiValue': tide_site})
if (tide_min_height == 99):
tide_states_list.append({'key': 'minHeight', 'value': tide_min_height, 'uiValue': u'--'})
else:
tide_states_list.append({'key': 'minHeight', 'value': tide_min_height, 'uiValue': tide_min_height})
if (tide_max_height == (- 99)):
tide_states_list.append({'key': 'maxHeight', 'value': tide_max_height, 'uiValue': u'--'})
else:
tide_states_list.append({'key': 'maxHeight', 'value': tide_max_height})
tide_counter = 1
if len(tide_summary):
for observation in tide_summary:
if (tide_counter < 32):
pretty = self.nestedLookup(observation, keys=('date', 'pretty'))
tide_height = self.nestedLookup(observation, keys=('data', 'height'))
tide_type = self.nestedLookup(observation, keys=('data', 'type'))
tide_states_list.append({'key': u'p{0}_height'.format(tide_counter), 'value': tide_height, 'uiValue': tide_height})
tide_states_list.append({'key': u'p{0}_pretty'.format(tide_counter), 'value': pretty, 'uiValue': pretty})
tide_states_list.append({'key': u'p{0}_type'.format(tide_counter), 'value': tide_type, 'uiValue': tide_type})
tide_counter += 1
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
tide_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(tide_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing tide data.')
self.logger.error(u'Note: Tide information may not be available in your area. Check Weather Underground for more information.')
tide_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
dev.updateStatesOnServer(tide_states_list) | def parseTidesData(self, dev):
'\n Parse tides data to devices\n\n The parseTidesData() method takes tide data and parses it to device states.\n\n -----\n\n :param indigo.Device dev:\n '
tide_states_list = []
location = dev.pluginProps['location']
weather_data = self.masterWeatherDict[location]
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
tide_min_height = self.nestedLookup(weather_data, keys=('tide', 'tideSummaryStats', 'minheight'))
tide_max_height = self.nestedLookup(weather_data, keys=('tide', 'tideSummaryStats', 'maxheight'))
tide_site = self.nestedLookup(weather_data, keys=('tide', 'tideInfo', 'tideSite'))
tide_summary = self.nestedLookup(weather_data, keys=('tide', 'tideSummary'))
try:
tide_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
tide_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(float(current_observation_epoch)))
tide_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
if (tide_site in [u, u' ']):
tide_states_list.append({'key': 'tideSite', 'value': u'No tide info.'})
else:
tide_states_list.append({'key': 'tideSite', 'value': tide_site, 'uiValue': tide_site})
if (tide_min_height == 99):
tide_states_list.append({'key': 'minHeight', 'value': tide_min_height, 'uiValue': u'--'})
else:
tide_states_list.append({'key': 'minHeight', 'value': tide_min_height, 'uiValue': tide_min_height})
if (tide_max_height == (- 99)):
tide_states_list.append({'key': 'maxHeight', 'value': tide_max_height, 'uiValue': u'--'})
else:
tide_states_list.append({'key': 'maxHeight', 'value': tide_max_height})
tide_counter = 1
if len(tide_summary):
for observation in tide_summary:
if (tide_counter < 32):
pretty = self.nestedLookup(observation, keys=('date', 'pretty'))
tide_height = self.nestedLookup(observation, keys=('data', 'height'))
tide_type = self.nestedLookup(observation, keys=('data', 'type'))
tide_states_list.append({'key': u'p{0}_height'.format(tide_counter), 'value': tide_height, 'uiValue': tide_height})
tide_states_list.append({'key': u'p{0}_pretty'.format(tide_counter), 'value': pretty, 'uiValue': pretty})
tide_states_list.append({'key': u'p{0}_type'.format(tide_counter), 'value': tide_type, 'uiValue': tide_type})
tide_counter += 1
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
tide_states_list.append({'key': 'onOffState', 'value': True, 'uiValue': u' '})
dev.updateStatesOnServer(tide_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOn)
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing tide data.')
self.logger.error(u'Note: Tide information may not be available in your area. Check Weather Underground for more information.')
tide_states_list.append({'key': 'onOffState', 'value': False, 'uiValue': u' '})
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
dev.updateStatesOnServer(tide_states_list)<|docstring|>Parse tides data to devices
The parseTidesData() method takes tide data and parses it to device states.
-----
:param indigo.Device dev:<|endoftext|> |
505651cb17dec78c161f583e22394565b3129d28c4aa6d13faa887052555e256 | def parseWeatherData(self, dev):
'\n Parse weather data to devices\n\n The parseWeatherData() method takes weather data and parses it to Weather\n Device states.\n\n -----\n\n :param indigo.Device dev:\n '
self.date_format = self.Formatter.dateFormat()
self.time_format = self.Formatter.timeFormat()
weather_states_list = []
try:
config_itemlist_ui_units = dev.pluginProps.get('itemListUiUnits', '')
config_menu_units = dev.pluginProps.get('configMenuUnits', '')
config_distance_units = dev.pluginProps.get('distanceUnits', '')
location = dev.pluginProps['location']
pressure_units = dev.pluginProps.get('pressureUnits', '')
weather_data = self.masterWeatherDict[location]
history_data = self.nestedLookup(weather_data, keys=('history', 'dailysummary'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_temp_c = self.nestedLookup(weather_data, keys=('current_observation', 'temp_c'))
current_temp_f = self.nestedLookup(weather_data, keys=('current_observation', 'temp_f'))
current_weather = self.nestedLookup(weather_data, keys=('current_observation', 'weather'))
dew_point_c = self.nestedLookup(weather_data, keys=('current_observation', 'dewpoint_c'))
dew_point_f = self.nestedLookup(weather_data, keys=('current_observation', 'dewpoint_f'))
feels_like_c = self.nestedLookup(weather_data, keys=('current_observation', 'feelslike_c'))
feels_like_f = self.nestedLookup(weather_data, keys=('current_observation', 'feelslike_f'))
heat_index_c = self.nestedLookup(weather_data, keys=('current_observation', 'heat_index_c'))
heat_index_f = self.nestedLookup(weather_data, keys=('current_observation', 'heat_index_f'))
icon = self.nestedLookup(weather_data, keys=('current_observation', 'icon'))
location_city = self.nestedLookup(weather_data, keys=('location', 'city'))
nearby_stations = self.nestedLookup(weather_data, keys=('location', 'nearby_weather_stations', 'pws', 'station'))
precip_1hr_m = self.nestedLookup(weather_data, keys=('current_observation', 'precip_1hr_metric'))
precip_1hr_in = self.nestedLookup(weather_data, keys=('current_observation', 'precip_1hr_in'))
precip_today_m = self.nestedLookup(weather_data, keys=('current_observation', 'precip_today_metric'))
precip_today_in = self.nestedLookup(weather_data, keys=('current_observation', 'precip_today_in'))
pressure_mb = self.nestedLookup(weather_data, keys=('current_observation', 'pressure_mb'))
pressure_in = self.nestedLookup(weather_data, keys=('current_observation', 'pressure_in'))
pressure_trend = self.nestedLookup(weather_data, keys=('current_observation', 'pressure_trend'))
relative_humidity = self.nestedLookup(weather_data, keys=('current_observation', 'relative_humidity'))
solar_radiation = self.nestedLookup(weather_data, keys=('current_observation', 'solarradiation'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
uv_index = self.nestedLookup(weather_data, keys=('current_observation', 'UV'))
visibility_km = self.nestedLookup(weather_data, keys=('current_observation', 'visibility_km'))
visibility_mi = self.nestedLookup(weather_data, keys=('current_observation', 'visibility_mi'))
wind_chill_c = self.nestedLookup(weather_data, keys=('current_observation', 'windchill_c'))
wind_chill_f = self.nestedLookup(weather_data, keys=('current_observation', 'windchill_f'))
wind_degrees = self.nestedLookup(weather_data, keys=('current_observation', 'wind_degrees'))
wind_dir = self.nestedLookup(weather_data, keys=('current_observation', 'wind_dir'))
wind_gust_kph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_gust_kph'))
wind_gust_mph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_gust_mph'))
wind_speed_kph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_kph'))
wind_speed_mph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_mph'))
(temp_c, temp_c_ui) = self.fixCorruptedData(state_name='temp_c', val=current_temp_c)
temp_c_ui = self.uiFormatTemperature(dev=dev, state_name='tempC (M, MS, I)', val=temp_c_ui)
(temp_f, temp_f_ui) = self.fixCorruptedData(state_name='temp_f', val=current_temp_f)
temp_f_ui = self.uiFormatTemperature(dev=dev, state_name='tempF (S)', val=temp_f_ui)
if (config_menu_units in ['M', 'MS', 'I']):
dev.updateStateOnServer('temp', value=temp_c, uiValue=temp_c_ui)
icon_value = u'{0}'.format(str(round(temp_c, 0)).replace('.', ''))
dev.updateStateOnServer('tempIcon', value=icon_value)
else:
dev.updateStateOnServer('temp', value=temp_f, uiValue=temp_f_ui)
icon_value = u'{0}'.format(str(round(temp_f, 0)).replace('.', ''))
dev.updateStateOnServer('tempIcon', value=icon_value)
if (config_itemlist_ui_units == 'M'):
display_value = u'{0} °C'.format(self.uiFormatItemListTemperature(val=temp_c))
elif (config_itemlist_ui_units == 'S'):
display_value = u'{0} °F'.format(self.uiFormatItemListTemperature(val=temp_f))
elif (config_itemlist_ui_units == 'SM'):
display_value = u'{0} °F ({1} °C)'.format(self.uiFormatItemListTemperature(val=temp_f), self.uiFormatItemListTemperature(val=temp_c))
elif (config_itemlist_ui_units == 'MS'):
display_value = u'{0} °C ({1} °F)'.format(self.uiFormatItemListTemperature(val=temp_c), self.uiFormatItemListTemperature(val=temp_f))
elif (config_itemlist_ui_units == 'MN'):
display_value = self.uiFormatItemListTemperature(temp_c)
else:
display_value = self.uiFormatItemListTemperature(temp_f)
dev.updateStateOnServer('onOffState', value=True, uiValue=display_value)
weather_states_list.append({'key': 'locationCity', 'value': location_city, 'uiValue': location_city})
weather_states_list.append({'key': 'stationID', 'value': station_id, 'uiValue': station_id})
neighborhood = u'Location not found.'
for key in nearby_stations:
if (key['id'] == station_id):
neighborhood = key['neighborhood']
break
weather_states_list.append({'key': 'neighborhood', 'value': neighborhood, 'uiValue': neighborhood})
weather_states_list.append({'key': 'properIconNameAllDay', 'value': icon, 'uiValue': icon})
weather_states_list.append({'key': 'properIconName', 'value': icon, 'uiValue': icon})
weather_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(float(current_observation_epoch)))
weather_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
weather_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
weather_states_list.append({'key': 'currentWeather', 'value': current_weather, 'uiValue': current_weather})
pressure_trend = self.uiFormatPressureSymbol(state_name='Pressure Trend', val=pressure_trend)
weather_states_list.append({'key': 'pressureTrend', 'value': pressure_trend, 'uiValue': pressure_trend})
(s_rad, s_rad_ui) = self.fixCorruptedData(state_name='Solar Radiation', val=solar_radiation)
weather_states_list.append({'key': 'solarradiation', 'value': s_rad, 'uiValue': s_rad_ui})
(uv, uv_ui) = self.fixCorruptedData(state_name='Solar Radiation', val=uv_index)
weather_states_list.append({'key': 'uv', 'value': uv, 'uiValue': uv_ui})
weather_states_list.append({'key': 'windDIR', 'value': wind_dir, 'uiValue': wind_dir})
wind_dir_long = self.verboseWindNames(state_name='windDIRlong', val=wind_dir)
weather_states_list.append({'key': 'windDIRlong', 'value': wind_dir_long, 'uiValue': wind_dir_long})
(wind_degrees, wind_degrees_ui) = self.fixCorruptedData(state_name='windDegrees', val=wind_degrees)
weather_states_list.append({'key': 'windDegrees', 'value': int(wind_degrees), 'uiValue': str(int(wind_degrees))})
(relative_humidity, relative_humidity_ui) = self.fixCorruptedData(state_name='relativeHumidity', val=str(relative_humidity).strip('%'))
relative_humidity_ui = self.uiFormatPercentage(dev=dev, state_name='relativeHumidity', val=relative_humidity_ui)
weather_states_list.append({'key': 'relativeHumidity', 'value': relative_humidity, 'uiValue': relative_humidity_ui})
(wind_gust_kph, wind_gust_kph_ui) = self.fixCorruptedData(state_name='windGust (KPH)', val=wind_gust_kph)
(wind_gust_mph, wind_gust_mph_ui) = self.fixCorruptedData(state_name='windGust (MPH)', val=wind_gust_mph)
(wind_gust_mps, wind_gust_mps_ui) = self.fixCorruptedData(state_name='windGust (MPS)', val=int((wind_gust_kph * 0.277778)))
(wind_speed_kph, wind_speed_kph_ui) = self.fixCorruptedData(state_name='windGust (KPH)', val=wind_speed_kph)
(wind_speed_mph, wind_speed_mph_ui) = self.fixCorruptedData(state_name='windGust (MPH)', val=wind_speed_mph)
(wind_speed_mps, wind_speed_mps_ui) = self.fixCorruptedData(state_name='windGust (MPS)', val=int((wind_speed_kph * 0.277778)))
try:
history_max_temp_m = self.nestedLookup(history_data, keys=('maxtempm',))
history_max_temp_i = self.nestedLookup(history_data, keys=('maxtempi',))
history_min_temp_m = self.nestedLookup(history_data, keys=('mintempm',))
history_min_temp_i = self.nestedLookup(history_data, keys=('mintempi',))
history_precip_m = self.nestedLookup(history_data, keys=('precipm',))
history_precip_i = self.nestedLookup(history_data, keys=('precipi',))
history_pretty_date = self.nestedLookup(history_data, keys=('date', 'pretty'))
weather_states_list.append({'key': 'historyDate', 'value': history_pretty_date})
if (config_menu_units in ['M', 'MS', 'I']):
(history_high, history_high_ui) = self.fixCorruptedData(state_name='historyHigh (M)', val=history_max_temp_m)
history_high_ui = self.uiFormatTemperature(dev=dev, state_name='historyHigh (M)', val=history_high_ui)
weather_states_list.append({'key': 'historyHigh', 'value': history_high, 'uiValue': history_high_ui})
(history_low, history_low_ui) = self.fixCorruptedData(state_name='historyLow (M)', val=history_min_temp_m)
history_low_ui = self.uiFormatTemperature(dev=dev, state_name='historyLow (M)', val=history_low_ui)
weather_states_list.append({'key': 'historyLow', 'value': history_low, 'uiValue': history_low_ui})
if (config_menu_units in ['M', 'MS']):
(history_pop, history_pop_ui) = self.fixCorruptedData(state_name='historyPop (M)', val=history_precip_m)
history_pop_ui = self.uiFormatRain(dev=dev, state_name='historyPop (M)', val=history_pop_ui)
weather_states_list.append({'key': 'historyPop', 'value': history_pop, 'uiValue': history_pop_ui})
if (config_menu_units in ['I', 'S']):
(history_pop, history_pop_ui) = self.fixCorruptedData(state_name='historyPop (I)', val=history_precip_i)
history_pop_ui = self.uiFormatRain(dev=dev, state_name='historyPop (I)', val=history_pop_ui)
weather_states_list.append({'key': 'historyPop', 'value': history_pop, 'uiValue': history_pop_ui})
if (config_menu_units in ['S']):
(history_high, history_high_ui) = self.fixCorruptedData(state_name='historyHigh (S)', val=history_max_temp_i)
history_high_ui = self.uiFormatTemperature(dev=dev, state_name='historyHigh (S)', val=history_high_ui)
weather_states_list.append({'key': 'historyHigh', 'value': history_high, 'uiValue': history_high_ui})
(history_low, history_low_ui) = self.fixCorruptedData(state_name='historyLow (S)', val=history_min_temp_i)
history_low_ui = self.uiFormatTemperature(dev=dev, state_name='historyLow (S)', val=history_low_ui)
weather_states_list.append({'key': 'historyLow', 'value': history_low, 'uiValue': history_low_ui})
except IndexError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.info(u'History data not supported for {0}'.format(dev.name))
if (config_menu_units in ['M', 'MS', 'I']):
(dewpoint, dewpoint_ui) = self.fixCorruptedData(state_name='dewpointC (M, MS)', val=dew_point_c)
dewpoint_ui = self.uiFormatTemperature(dev=dev, state_name='dewpointC (M, MS)', val=dewpoint_ui)
weather_states_list.append({'key': 'dewpoint', 'value': dewpoint, 'uiValue': dewpoint_ui})
(feelslike, feelslike_ui) = self.fixCorruptedData(state_name='feelsLikeC (M, MS)', val=feels_like_c)
feelslike_ui = self.uiFormatTemperature(dev=dev, state_name='feelsLikeC (M, MS)', val=feelslike_ui)
weather_states_list.append({'key': 'feelslike', 'value': feelslike, 'uiValue': feelslike_ui})
(heat_index, heat_index_ui) = self.fixCorruptedData(state_name='heatIndexC (M, MS)', val=heat_index_c)
heat_index_ui = self.uiFormatTemperature(dev=dev, state_name='heatIndexC (M, MS)', val=heat_index_ui)
weather_states_list.append({'key': 'heatIndex', 'value': heat_index, 'uiValue': heat_index_ui})
(windchill, windchill_ui) = self.fixCorruptedData(state_name='windChillC (M, MS)', val=wind_chill_c)
windchill_ui = self.uiFormatTemperature(dev=dev, state_name='windChillC (M, MS)', val=windchill_ui)
weather_states_list.append({'key': 'windchill', 'value': windchill, 'uiValue': windchill_ui})
(visibility, visibility_ui) = self.fixCorruptedData(state_name='visibility (M, MS)', val=visibility_km)
weather_states_list.append({'key': 'visibility', 'value': visibility, 'uiValue': u'{0}{1}'.format(int(round(visibility)), config_distance_units)})
(pressure, pressure_ui) = self.fixCorruptedData(state_name='pressureMB (M, MS)', val=pressure_mb)
weather_states_list.append({'key': 'pressure', 'value': pressure, 'uiValue': u'{0}{1}'.format(pressure_ui, pressure_units)})
weather_states_list.append({'key': 'pressureIcon', 'value': u'{0}'.format(int(round(pressure, 0)))})
if (config_menu_units in ['M', 'MS']):
(precip_today, precip_today_ui) = self.fixCorruptedData(state_name='precipMM (M, MS)', val=precip_today_m)
precip_today_ui = self.uiFormatRain(dev=dev, state_name='precipToday (M, MS)', val=precip_today_ui)
weather_states_list.append({'key': 'precip_today', 'value': precip_today, 'uiValue': precip_today_ui})
(precip_1hr, precip_1hr_ui) = self.fixCorruptedData(state_name='precipOneHourMM (M, MS)', val=precip_1hr_m)
precip_1hr_ui = self.uiFormatRain(dev=dev, state_name='precipOneHour (M, MS)', val=precip_1hr_ui)
weather_states_list.append({'key': 'precip_1hr', 'value': precip_1hr, 'uiValue': precip_1hr_ui})
if (config_menu_units == 'M'):
weather_states_list.append({'key': 'windGust', 'value': wind_gust_kph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windGust', val=wind_gust_kph_ui)})
weather_states_list.append({'key': 'windSpeed', 'value': wind_speed_kph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windSpeed', val=wind_speed_kph_ui)})
weather_states_list.append({'key': 'windGustIcon', 'value': unicode(round(wind_gust_kph, 1)).replace('.', '')})
weather_states_list.append({'key': 'windSpeedIcon', 'value': unicode(round(wind_speed_kph, 1)).replace('.', '')})
weather_states_list.append({'key': 'windString', 'value': u'From the {0} at {1} KPH Gusting to {2} KPH'.format(wind_dir, wind_speed_kph, wind_gust_kph)})
weather_states_list.append({'key': 'windShortString', 'value': u'{0} at {1}'.format(wind_dir, wind_speed_kph)})
weather_states_list.append({'key': 'windStringMetric', 'value': u'From the {0} at {1} KPH Gusting to {2} KPH'.format(wind_dir, wind_speed_kph, wind_gust_kph)})
if (config_menu_units == 'MS'):
weather_states_list.append({'key': 'windGust', 'value': wind_gust_mps, 'uiValue': self.uiFormatWind(dev=dev, state_name='windGust', val=wind_gust_mps_ui)})
weather_states_list.append({'key': 'windSpeed', 'value': wind_speed_mps, 'uiValue': self.uiFormatWind(dev=dev, state_name='windSpeed', val=wind_speed_mps_ui)})
weather_states_list.append({'key': 'windGustIcon', 'value': unicode(round(wind_gust_mps, 1)).replace('.', '')})
weather_states_list.append({'key': 'windSpeedIcon', 'value': unicode(round(wind_speed_mps, 1)).replace('.', '')})
weather_states_list.append({'key': 'windString', 'value': u'From the {0} at {1} MPS Gusting to {2} MPS'.format(wind_dir, wind_speed_mps, wind_gust_mps)})
weather_states_list.append({'key': 'windShortString', 'value': u'{0} at {1}'.format(wind_dir, wind_speed_mps)})
weather_states_list.append({'key': 'windStringMetric', 'value': u'From the {0} at {1} KPH Gusting to {2} KPH'.format(wind_dir, wind_speed_mps, wind_gust_mps)})
if (config_menu_units in ['I', 'S']):
(precip_today, precip_today_ui) = self.fixCorruptedData(state_name='precipToday (I)', val=precip_today_in)
precip_today_ui = self.uiFormatRain(dev=dev, state_name='precipToday (I)', val=precip_today_ui)
weather_states_list.append({'key': 'precip_today', 'value': precip_today, 'uiValue': precip_today_ui})
(precip_1hr, precip_1hr_ui) = self.fixCorruptedData(state_name='precipOneHour (I)', val=precip_1hr_in)
precip_1hr_ui = self.uiFormatRain(dev=dev, state_name='precipOneHour (I)', val=precip_1hr_ui)
weather_states_list.append({'key': 'precip_1hr', 'value': precip_1hr, 'uiValue': precip_1hr_ui})
weather_states_list.append({'key': 'windGust', 'value': wind_gust_mph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windGust', val=wind_gust_mph_ui)})
weather_states_list.append({'key': 'windSpeed', 'value': wind_speed_mph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windSpeed', val=wind_speed_mph_ui)})
weather_states_list.append({'key': 'windGustIcon', 'value': unicode(round(wind_gust_mph, 1)).replace('.', '')})
weather_states_list.append({'key': 'windSpeedIcon', 'value': unicode(round(wind_speed_mph, 1)).replace('.', '')})
weather_states_list.append({'key': 'windString', 'value': u'From the {0} at {1} MPH Gusting to {2} MPH'.format(wind_dir, wind_speed_mph, wind_gust_mph)})
weather_states_list.append({'key': 'windShortString', 'value': u'{0} at {1}'.format(wind_dir, wind_speed_mph)})
weather_states_list.append({'key': 'windStringMetric', 'value': ' '})
if (config_menu_units in ['S']):
(dewpoint, dewpoint_ui) = self.fixCorruptedData(state_name='dewpointF (S)', val=dew_point_f)
dewpoint_ui = self.uiFormatTemperature(dev=dev, state_name='dewpointF (S)', val=dewpoint_ui)
weather_states_list.append({'key': 'dewpoint', 'value': dewpoint, 'uiValue': dewpoint_ui})
(feelslike, feelslike_ui) = self.fixCorruptedData(state_name='feelsLikeF (S)', val=feels_like_f)
feelslike_ui = self.uiFormatTemperature(dev=dev, state_name='feelsLikeF (S)', val=feelslike_ui)
weather_states_list.append({'key': 'feelslike', 'value': feelslike, 'uiValue': feelslike_ui})
(heat_index, heat_index_ui) = self.fixCorruptedData(state_name='heatIndexF (S)', val=heat_index_f)
heat_index_ui = self.uiFormatTemperature(dev=dev, state_name='heatIndexF (S)', val=heat_index_ui)
weather_states_list.append({'key': 'heatIndex', 'value': heat_index, 'uiValue': heat_index_ui})
(windchill, windchill_ui) = self.fixCorruptedData(state_name='windChillF (S)', val=wind_chill_f)
windchill_ui = self.uiFormatTemperature(dev=dev, state_name='windChillF (S)', val=windchill_ui)
weather_states_list.append({'key': 'windchill', 'value': windchill, 'uiValue': windchill_ui})
(pressure, pressure_ui) = self.fixCorruptedData(state_name='pressure (S)', val=pressure_in)
weather_states_list.append({'key': 'pressure', 'value': pressure, 'uiValue': u'{0}{1}'.format(pressure_ui, pressure_units)})
weather_states_list.append({'key': 'pressureIcon', 'value': pressure_ui.replace('.', '')})
(visibility, visibility_ui) = self.fixCorruptedData(state_name='visibility (S)', val=visibility_mi)
weather_states_list.append({'key': 'visibility', 'value': visibility, 'uiValue': u'{0}{1}'.format(int(round(visibility)), config_distance_units)})
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
dev.updateStatesOnServer(weather_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.TemperatureSensorOn)
except IndexError:
self.logger.warning(u'Note: List index out of range. This is likely normal.')
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing weather device data.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | Parse weather data to devices
The parseWeatherData() method takes weather data and parses it to Weather
Device states.
-----
:param indigo.Device dev: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | parseWeatherData | DaveL17/WUnderground7 | 0 | python | def parseWeatherData(self, dev):
'\n Parse weather data to devices\n\n The parseWeatherData() method takes weather data and parses it to Weather\n Device states.\n\n -----\n\n :param indigo.Device dev:\n '
self.date_format = self.Formatter.dateFormat()
self.time_format = self.Formatter.timeFormat()
weather_states_list = []
try:
config_itemlist_ui_units = dev.pluginProps.get('itemListUiUnits', )
config_menu_units = dev.pluginProps.get('configMenuUnits', )
config_distance_units = dev.pluginProps.get('distanceUnits', )
location = dev.pluginProps['location']
pressure_units = dev.pluginProps.get('pressureUnits', )
weather_data = self.masterWeatherDict[location]
history_data = self.nestedLookup(weather_data, keys=('history', 'dailysummary'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_temp_c = self.nestedLookup(weather_data, keys=('current_observation', 'temp_c'))
current_temp_f = self.nestedLookup(weather_data, keys=('current_observation', 'temp_f'))
current_weather = self.nestedLookup(weather_data, keys=('current_observation', 'weather'))
dew_point_c = self.nestedLookup(weather_data, keys=('current_observation', 'dewpoint_c'))
dew_point_f = self.nestedLookup(weather_data, keys=('current_observation', 'dewpoint_f'))
feels_like_c = self.nestedLookup(weather_data, keys=('current_observation', 'feelslike_c'))
feels_like_f = self.nestedLookup(weather_data, keys=('current_observation', 'feelslike_f'))
heat_index_c = self.nestedLookup(weather_data, keys=('current_observation', 'heat_index_c'))
heat_index_f = self.nestedLookup(weather_data, keys=('current_observation', 'heat_index_f'))
icon = self.nestedLookup(weather_data, keys=('current_observation', 'icon'))
location_city = self.nestedLookup(weather_data, keys=('location', 'city'))
nearby_stations = self.nestedLookup(weather_data, keys=('location', 'nearby_weather_stations', 'pws', 'station'))
precip_1hr_m = self.nestedLookup(weather_data, keys=('current_observation', 'precip_1hr_metric'))
precip_1hr_in = self.nestedLookup(weather_data, keys=('current_observation', 'precip_1hr_in'))
precip_today_m = self.nestedLookup(weather_data, keys=('current_observation', 'precip_today_metric'))
precip_today_in = self.nestedLookup(weather_data, keys=('current_observation', 'precip_today_in'))
pressure_mb = self.nestedLookup(weather_data, keys=('current_observation', 'pressure_mb'))
pressure_in = self.nestedLookup(weather_data, keys=('current_observation', 'pressure_in'))
pressure_trend = self.nestedLookup(weather_data, keys=('current_observation', 'pressure_trend'))
relative_humidity = self.nestedLookup(weather_data, keys=('current_observation', 'relative_humidity'))
solar_radiation = self.nestedLookup(weather_data, keys=('current_observation', 'solarradiation'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
uv_index = self.nestedLookup(weather_data, keys=('current_observation', 'UV'))
visibility_km = self.nestedLookup(weather_data, keys=('current_observation', 'visibility_km'))
visibility_mi = self.nestedLookup(weather_data, keys=('current_observation', 'visibility_mi'))
wind_chill_c = self.nestedLookup(weather_data, keys=('current_observation', 'windchill_c'))
wind_chill_f = self.nestedLookup(weather_data, keys=('current_observation', 'windchill_f'))
wind_degrees = self.nestedLookup(weather_data, keys=('current_observation', 'wind_degrees'))
wind_dir = self.nestedLookup(weather_data, keys=('current_observation', 'wind_dir'))
wind_gust_kph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_gust_kph'))
wind_gust_mph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_gust_mph'))
wind_speed_kph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_kph'))
wind_speed_mph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_mph'))
(temp_c, temp_c_ui) = self.fixCorruptedData(state_name='temp_c', val=current_temp_c)
temp_c_ui = self.uiFormatTemperature(dev=dev, state_name='tempC (M, MS, I)', val=temp_c_ui)
(temp_f, temp_f_ui) = self.fixCorruptedData(state_name='temp_f', val=current_temp_f)
temp_f_ui = self.uiFormatTemperature(dev=dev, state_name='tempF (S)', val=temp_f_ui)
if (config_menu_units in ['M', 'MS', 'I']):
dev.updateStateOnServer('temp', value=temp_c, uiValue=temp_c_ui)
icon_value = u'{0}'.format(str(round(temp_c, 0)).replace('.', ))
dev.updateStateOnServer('tempIcon', value=icon_value)
else:
dev.updateStateOnServer('temp', value=temp_f, uiValue=temp_f_ui)
icon_value = u'{0}'.format(str(round(temp_f, 0)).replace('.', ))
dev.updateStateOnServer('tempIcon', value=icon_value)
if (config_itemlist_ui_units == 'M'):
display_value = u'{0} °C'.format(self.uiFormatItemListTemperature(val=temp_c))
elif (config_itemlist_ui_units == 'S'):
display_value = u'{0} °F'.format(self.uiFormatItemListTemperature(val=temp_f))
elif (config_itemlist_ui_units == 'SM'):
display_value = u'{0} °F ({1} °C)'.format(self.uiFormatItemListTemperature(val=temp_f), self.uiFormatItemListTemperature(val=temp_c))
elif (config_itemlist_ui_units == 'MS'):
display_value = u'{0} °C ({1} °F)'.format(self.uiFormatItemListTemperature(val=temp_c), self.uiFormatItemListTemperature(val=temp_f))
elif (config_itemlist_ui_units == 'MN'):
display_value = self.uiFormatItemListTemperature(temp_c)
else:
display_value = self.uiFormatItemListTemperature(temp_f)
dev.updateStateOnServer('onOffState', value=True, uiValue=display_value)
weather_states_list.append({'key': 'locationCity', 'value': location_city, 'uiValue': location_city})
weather_states_list.append({'key': 'stationID', 'value': station_id, 'uiValue': station_id})
neighborhood = u'Location not found.'
for key in nearby_stations:
if (key['id'] == station_id):
neighborhood = key['neighborhood']
break
weather_states_list.append({'key': 'neighborhood', 'value': neighborhood, 'uiValue': neighborhood})
weather_states_list.append({'key': 'properIconNameAllDay', 'value': icon, 'uiValue': icon})
weather_states_list.append({'key': 'properIconName', 'value': icon, 'uiValue': icon})
weather_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(float(current_observation_epoch)))
weather_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
weather_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
weather_states_list.append({'key': 'currentWeather', 'value': current_weather, 'uiValue': current_weather})
pressure_trend = self.uiFormatPressureSymbol(state_name='Pressure Trend', val=pressure_trend)
weather_states_list.append({'key': 'pressureTrend', 'value': pressure_trend, 'uiValue': pressure_trend})
(s_rad, s_rad_ui) = self.fixCorruptedData(state_name='Solar Radiation', val=solar_radiation)
weather_states_list.append({'key': 'solarradiation', 'value': s_rad, 'uiValue': s_rad_ui})
(uv, uv_ui) = self.fixCorruptedData(state_name='Solar Radiation', val=uv_index)
weather_states_list.append({'key': 'uv', 'value': uv, 'uiValue': uv_ui})
weather_states_list.append({'key': 'windDIR', 'value': wind_dir, 'uiValue': wind_dir})
wind_dir_long = self.verboseWindNames(state_name='windDIRlong', val=wind_dir)
weather_states_list.append({'key': 'windDIRlong', 'value': wind_dir_long, 'uiValue': wind_dir_long})
(wind_degrees, wind_degrees_ui) = self.fixCorruptedData(state_name='windDegrees', val=wind_degrees)
weather_states_list.append({'key': 'windDegrees', 'value': int(wind_degrees), 'uiValue': str(int(wind_degrees))})
(relative_humidity, relative_humidity_ui) = self.fixCorruptedData(state_name='relativeHumidity', val=str(relative_humidity).strip('%'))
relative_humidity_ui = self.uiFormatPercentage(dev=dev, state_name='relativeHumidity', val=relative_humidity_ui)
weather_states_list.append({'key': 'relativeHumidity', 'value': relative_humidity, 'uiValue': relative_humidity_ui})
(wind_gust_kph, wind_gust_kph_ui) = self.fixCorruptedData(state_name='windGust (KPH)', val=wind_gust_kph)
(wind_gust_mph, wind_gust_mph_ui) = self.fixCorruptedData(state_name='windGust (MPH)', val=wind_gust_mph)
(wind_gust_mps, wind_gust_mps_ui) = self.fixCorruptedData(state_name='windGust (MPS)', val=int((wind_gust_kph * 0.277778)))
(wind_speed_kph, wind_speed_kph_ui) = self.fixCorruptedData(state_name='windGust (KPH)', val=wind_speed_kph)
(wind_speed_mph, wind_speed_mph_ui) = self.fixCorruptedData(state_name='windGust (MPH)', val=wind_speed_mph)
(wind_speed_mps, wind_speed_mps_ui) = self.fixCorruptedData(state_name='windGust (MPS)', val=int((wind_speed_kph * 0.277778)))
try:
history_max_temp_m = self.nestedLookup(history_data, keys=('maxtempm',))
history_max_temp_i = self.nestedLookup(history_data, keys=('maxtempi',))
history_min_temp_m = self.nestedLookup(history_data, keys=('mintempm',))
history_min_temp_i = self.nestedLookup(history_data, keys=('mintempi',))
history_precip_m = self.nestedLookup(history_data, keys=('precipm',))
history_precip_i = self.nestedLookup(history_data, keys=('precipi',))
history_pretty_date = self.nestedLookup(history_data, keys=('date', 'pretty'))
weather_states_list.append({'key': 'historyDate', 'value': history_pretty_date})
if (config_menu_units in ['M', 'MS', 'I']):
(history_high, history_high_ui) = self.fixCorruptedData(state_name='historyHigh (M)', val=history_max_temp_m)
history_high_ui = self.uiFormatTemperature(dev=dev, state_name='historyHigh (M)', val=history_high_ui)
weather_states_list.append({'key': 'historyHigh', 'value': history_high, 'uiValue': history_high_ui})
(history_low, history_low_ui) = self.fixCorruptedData(state_name='historyLow (M)', val=history_min_temp_m)
history_low_ui = self.uiFormatTemperature(dev=dev, state_name='historyLow (M)', val=history_low_ui)
weather_states_list.append({'key': 'historyLow', 'value': history_low, 'uiValue': history_low_ui})
if (config_menu_units in ['M', 'MS']):
(history_pop, history_pop_ui) = self.fixCorruptedData(state_name='historyPop (M)', val=history_precip_m)
history_pop_ui = self.uiFormatRain(dev=dev, state_name='historyPop (M)', val=history_pop_ui)
weather_states_list.append({'key': 'historyPop', 'value': history_pop, 'uiValue': history_pop_ui})
if (config_menu_units in ['I', 'S']):
(history_pop, history_pop_ui) = self.fixCorruptedData(state_name='historyPop (I)', val=history_precip_i)
history_pop_ui = self.uiFormatRain(dev=dev, state_name='historyPop (I)', val=history_pop_ui)
weather_states_list.append({'key': 'historyPop', 'value': history_pop, 'uiValue': history_pop_ui})
if (config_menu_units in ['S']):
(history_high, history_high_ui) = self.fixCorruptedData(state_name='historyHigh (S)', val=history_max_temp_i)
history_high_ui = self.uiFormatTemperature(dev=dev, state_name='historyHigh (S)', val=history_high_ui)
weather_states_list.append({'key': 'historyHigh', 'value': history_high, 'uiValue': history_high_ui})
(history_low, history_low_ui) = self.fixCorruptedData(state_name='historyLow (S)', val=history_min_temp_i)
history_low_ui = self.uiFormatTemperature(dev=dev, state_name='historyLow (S)', val=history_low_ui)
weather_states_list.append({'key': 'historyLow', 'value': history_low, 'uiValue': history_low_ui})
except IndexError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.info(u'History data not supported for {0}'.format(dev.name))
if (config_menu_units in ['M', 'MS', 'I']):
(dewpoint, dewpoint_ui) = self.fixCorruptedData(state_name='dewpointC (M, MS)', val=dew_point_c)
dewpoint_ui = self.uiFormatTemperature(dev=dev, state_name='dewpointC (M, MS)', val=dewpoint_ui)
weather_states_list.append({'key': 'dewpoint', 'value': dewpoint, 'uiValue': dewpoint_ui})
(feelslike, feelslike_ui) = self.fixCorruptedData(state_name='feelsLikeC (M, MS)', val=feels_like_c)
feelslike_ui = self.uiFormatTemperature(dev=dev, state_name='feelsLikeC (M, MS)', val=feelslike_ui)
weather_states_list.append({'key': 'feelslike', 'value': feelslike, 'uiValue': feelslike_ui})
(heat_index, heat_index_ui) = self.fixCorruptedData(state_name='heatIndexC (M, MS)', val=heat_index_c)
heat_index_ui = self.uiFormatTemperature(dev=dev, state_name='heatIndexC (M, MS)', val=heat_index_ui)
weather_states_list.append({'key': 'heatIndex', 'value': heat_index, 'uiValue': heat_index_ui})
(windchill, windchill_ui) = self.fixCorruptedData(state_name='windChillC (M, MS)', val=wind_chill_c)
windchill_ui = self.uiFormatTemperature(dev=dev, state_name='windChillC (M, MS)', val=windchill_ui)
weather_states_list.append({'key': 'windchill', 'value': windchill, 'uiValue': windchill_ui})
(visibility, visibility_ui) = self.fixCorruptedData(state_name='visibility (M, MS)', val=visibility_km)
weather_states_list.append({'key': 'visibility', 'value': visibility, 'uiValue': u'{0}{1}'.format(int(round(visibility)), config_distance_units)})
(pressure, pressure_ui) = self.fixCorruptedData(state_name='pressureMB (M, MS)', val=pressure_mb)
weather_states_list.append({'key': 'pressure', 'value': pressure, 'uiValue': u'{0}{1}'.format(pressure_ui, pressure_units)})
weather_states_list.append({'key': 'pressureIcon', 'value': u'{0}'.format(int(round(pressure, 0)))})
if (config_menu_units in ['M', 'MS']):
(precip_today, precip_today_ui) = self.fixCorruptedData(state_name='precipMM (M, MS)', val=precip_today_m)
precip_today_ui = self.uiFormatRain(dev=dev, state_name='precipToday (M, MS)', val=precip_today_ui)
weather_states_list.append({'key': 'precip_today', 'value': precip_today, 'uiValue': precip_today_ui})
(precip_1hr, precip_1hr_ui) = self.fixCorruptedData(state_name='precipOneHourMM (M, MS)', val=precip_1hr_m)
precip_1hr_ui = self.uiFormatRain(dev=dev, state_name='precipOneHour (M, MS)', val=precip_1hr_ui)
weather_states_list.append({'key': 'precip_1hr', 'value': precip_1hr, 'uiValue': precip_1hr_ui})
if (config_menu_units == 'M'):
weather_states_list.append({'key': 'windGust', 'value': wind_gust_kph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windGust', val=wind_gust_kph_ui)})
weather_states_list.append({'key': 'windSpeed', 'value': wind_speed_kph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windSpeed', val=wind_speed_kph_ui)})
weather_states_list.append({'key': 'windGustIcon', 'value': unicode(round(wind_gust_kph, 1)).replace('.', )})
weather_states_list.append({'key': 'windSpeedIcon', 'value': unicode(round(wind_speed_kph, 1)).replace('.', )})
weather_states_list.append({'key': 'windString', 'value': u'From the {0} at {1} KPH Gusting to {2} KPH'.format(wind_dir, wind_speed_kph, wind_gust_kph)})
weather_states_list.append({'key': 'windShortString', 'value': u'{0} at {1}'.format(wind_dir, wind_speed_kph)})
weather_states_list.append({'key': 'windStringMetric', 'value': u'From the {0} at {1} KPH Gusting to {2} KPH'.format(wind_dir, wind_speed_kph, wind_gust_kph)})
if (config_menu_units == 'MS'):
weather_states_list.append({'key': 'windGust', 'value': wind_gust_mps, 'uiValue': self.uiFormatWind(dev=dev, state_name='windGust', val=wind_gust_mps_ui)})
weather_states_list.append({'key': 'windSpeed', 'value': wind_speed_mps, 'uiValue': self.uiFormatWind(dev=dev, state_name='windSpeed', val=wind_speed_mps_ui)})
weather_states_list.append({'key': 'windGustIcon', 'value': unicode(round(wind_gust_mps, 1)).replace('.', )})
weather_states_list.append({'key': 'windSpeedIcon', 'value': unicode(round(wind_speed_mps, 1)).replace('.', )})
weather_states_list.append({'key': 'windString', 'value': u'From the {0} at {1} MPS Gusting to {2} MPS'.format(wind_dir, wind_speed_mps, wind_gust_mps)})
weather_states_list.append({'key': 'windShortString', 'value': u'{0} at {1}'.format(wind_dir, wind_speed_mps)})
weather_states_list.append({'key': 'windStringMetric', 'value': u'From the {0} at {1} KPH Gusting to {2} KPH'.format(wind_dir, wind_speed_mps, wind_gust_mps)})
if (config_menu_units in ['I', 'S']):
(precip_today, precip_today_ui) = self.fixCorruptedData(state_name='precipToday (I)', val=precip_today_in)
precip_today_ui = self.uiFormatRain(dev=dev, state_name='precipToday (I)', val=precip_today_ui)
weather_states_list.append({'key': 'precip_today', 'value': precip_today, 'uiValue': precip_today_ui})
(precip_1hr, precip_1hr_ui) = self.fixCorruptedData(state_name='precipOneHour (I)', val=precip_1hr_in)
precip_1hr_ui = self.uiFormatRain(dev=dev, state_name='precipOneHour (I)', val=precip_1hr_ui)
weather_states_list.append({'key': 'precip_1hr', 'value': precip_1hr, 'uiValue': precip_1hr_ui})
weather_states_list.append({'key': 'windGust', 'value': wind_gust_mph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windGust', val=wind_gust_mph_ui)})
weather_states_list.append({'key': 'windSpeed', 'value': wind_speed_mph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windSpeed', val=wind_speed_mph_ui)})
weather_states_list.append({'key': 'windGustIcon', 'value': unicode(round(wind_gust_mph, 1)).replace('.', )})
weather_states_list.append({'key': 'windSpeedIcon', 'value': unicode(round(wind_speed_mph, 1)).replace('.', )})
weather_states_list.append({'key': 'windString', 'value': u'From the {0} at {1} MPH Gusting to {2} MPH'.format(wind_dir, wind_speed_mph, wind_gust_mph)})
weather_states_list.append({'key': 'windShortString', 'value': u'{0} at {1}'.format(wind_dir, wind_speed_mph)})
weather_states_list.append({'key': 'windStringMetric', 'value': ' '})
if (config_menu_units in ['S']):
(dewpoint, dewpoint_ui) = self.fixCorruptedData(state_name='dewpointF (S)', val=dew_point_f)
dewpoint_ui = self.uiFormatTemperature(dev=dev, state_name='dewpointF (S)', val=dewpoint_ui)
weather_states_list.append({'key': 'dewpoint', 'value': dewpoint, 'uiValue': dewpoint_ui})
(feelslike, feelslike_ui) = self.fixCorruptedData(state_name='feelsLikeF (S)', val=feels_like_f)
feelslike_ui = self.uiFormatTemperature(dev=dev, state_name='feelsLikeF (S)', val=feelslike_ui)
weather_states_list.append({'key': 'feelslike', 'value': feelslike, 'uiValue': feelslike_ui})
(heat_index, heat_index_ui) = self.fixCorruptedData(state_name='heatIndexF (S)', val=heat_index_f)
heat_index_ui = self.uiFormatTemperature(dev=dev, state_name='heatIndexF (S)', val=heat_index_ui)
weather_states_list.append({'key': 'heatIndex', 'value': heat_index, 'uiValue': heat_index_ui})
(windchill, windchill_ui) = self.fixCorruptedData(state_name='windChillF (S)', val=wind_chill_f)
windchill_ui = self.uiFormatTemperature(dev=dev, state_name='windChillF (S)', val=windchill_ui)
weather_states_list.append({'key': 'windchill', 'value': windchill, 'uiValue': windchill_ui})
(pressure, pressure_ui) = self.fixCorruptedData(state_name='pressure (S)', val=pressure_in)
weather_states_list.append({'key': 'pressure', 'value': pressure, 'uiValue': u'{0}{1}'.format(pressure_ui, pressure_units)})
weather_states_list.append({'key': 'pressureIcon', 'value': pressure_ui.replace('.', )})
(visibility, visibility_ui) = self.fixCorruptedData(state_name='visibility (S)', val=visibility_mi)
weather_states_list.append({'key': 'visibility', 'value': visibility, 'uiValue': u'{0}{1}'.format(int(round(visibility)), config_distance_units)})
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
dev.updateStatesOnServer(weather_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.TemperatureSensorOn)
except IndexError:
self.logger.warning(u'Note: List index out of range. This is likely normal.')
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing weather device data.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff) | def parseWeatherData(self, dev):
'\n Parse weather data to devices\n\n The parseWeatherData() method takes weather data and parses it to Weather\n Device states.\n\n -----\n\n :param indigo.Device dev:\n '
self.date_format = self.Formatter.dateFormat()
self.time_format = self.Formatter.timeFormat()
weather_states_list = []
try:
config_itemlist_ui_units = dev.pluginProps.get('itemListUiUnits', )
config_menu_units = dev.pluginProps.get('configMenuUnits', )
config_distance_units = dev.pluginProps.get('distanceUnits', )
location = dev.pluginProps['location']
pressure_units = dev.pluginProps.get('pressureUnits', )
weather_data = self.masterWeatherDict[location]
history_data = self.nestedLookup(weather_data, keys=('history', 'dailysummary'))
current_observation_epoch = self.nestedLookup(weather_data, keys=('current_observation', 'observation_epoch'))
current_observation_time = self.nestedLookup(weather_data, keys=('current_observation', 'observation_time'))
current_temp_c = self.nestedLookup(weather_data, keys=('current_observation', 'temp_c'))
current_temp_f = self.nestedLookup(weather_data, keys=('current_observation', 'temp_f'))
current_weather = self.nestedLookup(weather_data, keys=('current_observation', 'weather'))
dew_point_c = self.nestedLookup(weather_data, keys=('current_observation', 'dewpoint_c'))
dew_point_f = self.nestedLookup(weather_data, keys=('current_observation', 'dewpoint_f'))
feels_like_c = self.nestedLookup(weather_data, keys=('current_observation', 'feelslike_c'))
feels_like_f = self.nestedLookup(weather_data, keys=('current_observation', 'feelslike_f'))
heat_index_c = self.nestedLookup(weather_data, keys=('current_observation', 'heat_index_c'))
heat_index_f = self.nestedLookup(weather_data, keys=('current_observation', 'heat_index_f'))
icon = self.nestedLookup(weather_data, keys=('current_observation', 'icon'))
location_city = self.nestedLookup(weather_data, keys=('location', 'city'))
nearby_stations = self.nestedLookup(weather_data, keys=('location', 'nearby_weather_stations', 'pws', 'station'))
precip_1hr_m = self.nestedLookup(weather_data, keys=('current_observation', 'precip_1hr_metric'))
precip_1hr_in = self.nestedLookup(weather_data, keys=('current_observation', 'precip_1hr_in'))
precip_today_m = self.nestedLookup(weather_data, keys=('current_observation', 'precip_today_metric'))
precip_today_in = self.nestedLookup(weather_data, keys=('current_observation', 'precip_today_in'))
pressure_mb = self.nestedLookup(weather_data, keys=('current_observation', 'pressure_mb'))
pressure_in = self.nestedLookup(weather_data, keys=('current_observation', 'pressure_in'))
pressure_trend = self.nestedLookup(weather_data, keys=('current_observation', 'pressure_trend'))
relative_humidity = self.nestedLookup(weather_data, keys=('current_observation', 'relative_humidity'))
solar_radiation = self.nestedLookup(weather_data, keys=('current_observation', 'solarradiation'))
station_id = self.nestedLookup(weather_data, keys=('current_observation', 'station_id'))
uv_index = self.nestedLookup(weather_data, keys=('current_observation', 'UV'))
visibility_km = self.nestedLookup(weather_data, keys=('current_observation', 'visibility_km'))
visibility_mi = self.nestedLookup(weather_data, keys=('current_observation', 'visibility_mi'))
wind_chill_c = self.nestedLookup(weather_data, keys=('current_observation', 'windchill_c'))
wind_chill_f = self.nestedLookup(weather_data, keys=('current_observation', 'windchill_f'))
wind_degrees = self.nestedLookup(weather_data, keys=('current_observation', 'wind_degrees'))
wind_dir = self.nestedLookup(weather_data, keys=('current_observation', 'wind_dir'))
wind_gust_kph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_gust_kph'))
wind_gust_mph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_gust_mph'))
wind_speed_kph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_kph'))
wind_speed_mph = self.nestedLookup(weather_data, keys=('current_observation', 'wind_mph'))
(temp_c, temp_c_ui) = self.fixCorruptedData(state_name='temp_c', val=current_temp_c)
temp_c_ui = self.uiFormatTemperature(dev=dev, state_name='tempC (M, MS, I)', val=temp_c_ui)
(temp_f, temp_f_ui) = self.fixCorruptedData(state_name='temp_f', val=current_temp_f)
temp_f_ui = self.uiFormatTemperature(dev=dev, state_name='tempF (S)', val=temp_f_ui)
if (config_menu_units in ['M', 'MS', 'I']):
dev.updateStateOnServer('temp', value=temp_c, uiValue=temp_c_ui)
icon_value = u'{0}'.format(str(round(temp_c, 0)).replace('.', ))
dev.updateStateOnServer('tempIcon', value=icon_value)
else:
dev.updateStateOnServer('temp', value=temp_f, uiValue=temp_f_ui)
icon_value = u'{0}'.format(str(round(temp_f, 0)).replace('.', ))
dev.updateStateOnServer('tempIcon', value=icon_value)
if (config_itemlist_ui_units == 'M'):
display_value = u'{0} °C'.format(self.uiFormatItemListTemperature(val=temp_c))
elif (config_itemlist_ui_units == 'S'):
display_value = u'{0} °F'.format(self.uiFormatItemListTemperature(val=temp_f))
elif (config_itemlist_ui_units == 'SM'):
display_value = u'{0} °F ({1} °C)'.format(self.uiFormatItemListTemperature(val=temp_f), self.uiFormatItemListTemperature(val=temp_c))
elif (config_itemlist_ui_units == 'MS'):
display_value = u'{0} °C ({1} °F)'.format(self.uiFormatItemListTemperature(val=temp_c), self.uiFormatItemListTemperature(val=temp_f))
elif (config_itemlist_ui_units == 'MN'):
display_value = self.uiFormatItemListTemperature(temp_c)
else:
display_value = self.uiFormatItemListTemperature(temp_f)
dev.updateStateOnServer('onOffState', value=True, uiValue=display_value)
weather_states_list.append({'key': 'locationCity', 'value': location_city, 'uiValue': location_city})
weather_states_list.append({'key': 'stationID', 'value': station_id, 'uiValue': station_id})
neighborhood = u'Location not found.'
for key in nearby_stations:
if (key['id'] == station_id):
neighborhood = key['neighborhood']
break
weather_states_list.append({'key': 'neighborhood', 'value': neighborhood, 'uiValue': neighborhood})
weather_states_list.append({'key': 'properIconNameAllDay', 'value': icon, 'uiValue': icon})
weather_states_list.append({'key': 'properIconName', 'value': icon, 'uiValue': icon})
weather_states_list.append({'key': 'currentObservation', 'value': current_observation_time, 'uiValue': current_observation_time})
current_observation_24hr = time.strftime('{0} {1}'.format(self.date_format, self.time_format), time.localtime(float(current_observation_epoch)))
weather_states_list.append({'key': 'currentObservation24hr', 'value': current_observation_24hr})
weather_states_list.append({'key': 'currentObservationEpoch', 'value': current_observation_epoch, 'uiValue': current_observation_epoch})
weather_states_list.append({'key': 'currentWeather', 'value': current_weather, 'uiValue': current_weather})
pressure_trend = self.uiFormatPressureSymbol(state_name='Pressure Trend', val=pressure_trend)
weather_states_list.append({'key': 'pressureTrend', 'value': pressure_trend, 'uiValue': pressure_trend})
(s_rad, s_rad_ui) = self.fixCorruptedData(state_name='Solar Radiation', val=solar_radiation)
weather_states_list.append({'key': 'solarradiation', 'value': s_rad, 'uiValue': s_rad_ui})
(uv, uv_ui) = self.fixCorruptedData(state_name='Solar Radiation', val=uv_index)
weather_states_list.append({'key': 'uv', 'value': uv, 'uiValue': uv_ui})
weather_states_list.append({'key': 'windDIR', 'value': wind_dir, 'uiValue': wind_dir})
wind_dir_long = self.verboseWindNames(state_name='windDIRlong', val=wind_dir)
weather_states_list.append({'key': 'windDIRlong', 'value': wind_dir_long, 'uiValue': wind_dir_long})
(wind_degrees, wind_degrees_ui) = self.fixCorruptedData(state_name='windDegrees', val=wind_degrees)
weather_states_list.append({'key': 'windDegrees', 'value': int(wind_degrees), 'uiValue': str(int(wind_degrees))})
(relative_humidity, relative_humidity_ui) = self.fixCorruptedData(state_name='relativeHumidity', val=str(relative_humidity).strip('%'))
relative_humidity_ui = self.uiFormatPercentage(dev=dev, state_name='relativeHumidity', val=relative_humidity_ui)
weather_states_list.append({'key': 'relativeHumidity', 'value': relative_humidity, 'uiValue': relative_humidity_ui})
(wind_gust_kph, wind_gust_kph_ui) = self.fixCorruptedData(state_name='windGust (KPH)', val=wind_gust_kph)
(wind_gust_mph, wind_gust_mph_ui) = self.fixCorruptedData(state_name='windGust (MPH)', val=wind_gust_mph)
(wind_gust_mps, wind_gust_mps_ui) = self.fixCorruptedData(state_name='windGust (MPS)', val=int((wind_gust_kph * 0.277778)))
(wind_speed_kph, wind_speed_kph_ui) = self.fixCorruptedData(state_name='windGust (KPH)', val=wind_speed_kph)
(wind_speed_mph, wind_speed_mph_ui) = self.fixCorruptedData(state_name='windGust (MPH)', val=wind_speed_mph)
(wind_speed_mps, wind_speed_mps_ui) = self.fixCorruptedData(state_name='windGust (MPS)', val=int((wind_speed_kph * 0.277778)))
try:
history_max_temp_m = self.nestedLookup(history_data, keys=('maxtempm',))
history_max_temp_i = self.nestedLookup(history_data, keys=('maxtempi',))
history_min_temp_m = self.nestedLookup(history_data, keys=('mintempm',))
history_min_temp_i = self.nestedLookup(history_data, keys=('mintempi',))
history_precip_m = self.nestedLookup(history_data, keys=('precipm',))
history_precip_i = self.nestedLookup(history_data, keys=('precipi',))
history_pretty_date = self.nestedLookup(history_data, keys=('date', 'pretty'))
weather_states_list.append({'key': 'historyDate', 'value': history_pretty_date})
if (config_menu_units in ['M', 'MS', 'I']):
(history_high, history_high_ui) = self.fixCorruptedData(state_name='historyHigh (M)', val=history_max_temp_m)
history_high_ui = self.uiFormatTemperature(dev=dev, state_name='historyHigh (M)', val=history_high_ui)
weather_states_list.append({'key': 'historyHigh', 'value': history_high, 'uiValue': history_high_ui})
(history_low, history_low_ui) = self.fixCorruptedData(state_name='historyLow (M)', val=history_min_temp_m)
history_low_ui = self.uiFormatTemperature(dev=dev, state_name='historyLow (M)', val=history_low_ui)
weather_states_list.append({'key': 'historyLow', 'value': history_low, 'uiValue': history_low_ui})
if (config_menu_units in ['M', 'MS']):
(history_pop, history_pop_ui) = self.fixCorruptedData(state_name='historyPop (M)', val=history_precip_m)
history_pop_ui = self.uiFormatRain(dev=dev, state_name='historyPop (M)', val=history_pop_ui)
weather_states_list.append({'key': 'historyPop', 'value': history_pop, 'uiValue': history_pop_ui})
if (config_menu_units in ['I', 'S']):
(history_pop, history_pop_ui) = self.fixCorruptedData(state_name='historyPop (I)', val=history_precip_i)
history_pop_ui = self.uiFormatRain(dev=dev, state_name='historyPop (I)', val=history_pop_ui)
weather_states_list.append({'key': 'historyPop', 'value': history_pop, 'uiValue': history_pop_ui})
if (config_menu_units in ['S']):
(history_high, history_high_ui) = self.fixCorruptedData(state_name='historyHigh (S)', val=history_max_temp_i)
history_high_ui = self.uiFormatTemperature(dev=dev, state_name='historyHigh (S)', val=history_high_ui)
weather_states_list.append({'key': 'historyHigh', 'value': history_high, 'uiValue': history_high_ui})
(history_low, history_low_ui) = self.fixCorruptedData(state_name='historyLow (S)', val=history_min_temp_i)
history_low_ui = self.uiFormatTemperature(dev=dev, state_name='historyLow (S)', val=history_low_ui)
weather_states_list.append({'key': 'historyLow', 'value': history_low, 'uiValue': history_low_ui})
except IndexError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.info(u'History data not supported for {0}'.format(dev.name))
if (config_menu_units in ['M', 'MS', 'I']):
(dewpoint, dewpoint_ui) = self.fixCorruptedData(state_name='dewpointC (M, MS)', val=dew_point_c)
dewpoint_ui = self.uiFormatTemperature(dev=dev, state_name='dewpointC (M, MS)', val=dewpoint_ui)
weather_states_list.append({'key': 'dewpoint', 'value': dewpoint, 'uiValue': dewpoint_ui})
(feelslike, feelslike_ui) = self.fixCorruptedData(state_name='feelsLikeC (M, MS)', val=feels_like_c)
feelslike_ui = self.uiFormatTemperature(dev=dev, state_name='feelsLikeC (M, MS)', val=feelslike_ui)
weather_states_list.append({'key': 'feelslike', 'value': feelslike, 'uiValue': feelslike_ui})
(heat_index, heat_index_ui) = self.fixCorruptedData(state_name='heatIndexC (M, MS)', val=heat_index_c)
heat_index_ui = self.uiFormatTemperature(dev=dev, state_name='heatIndexC (M, MS)', val=heat_index_ui)
weather_states_list.append({'key': 'heatIndex', 'value': heat_index, 'uiValue': heat_index_ui})
(windchill, windchill_ui) = self.fixCorruptedData(state_name='windChillC (M, MS)', val=wind_chill_c)
windchill_ui = self.uiFormatTemperature(dev=dev, state_name='windChillC (M, MS)', val=windchill_ui)
weather_states_list.append({'key': 'windchill', 'value': windchill, 'uiValue': windchill_ui})
(visibility, visibility_ui) = self.fixCorruptedData(state_name='visibility (M, MS)', val=visibility_km)
weather_states_list.append({'key': 'visibility', 'value': visibility, 'uiValue': u'{0}{1}'.format(int(round(visibility)), config_distance_units)})
(pressure, pressure_ui) = self.fixCorruptedData(state_name='pressureMB (M, MS)', val=pressure_mb)
weather_states_list.append({'key': 'pressure', 'value': pressure, 'uiValue': u'{0}{1}'.format(pressure_ui, pressure_units)})
weather_states_list.append({'key': 'pressureIcon', 'value': u'{0}'.format(int(round(pressure, 0)))})
if (config_menu_units in ['M', 'MS']):
(precip_today, precip_today_ui) = self.fixCorruptedData(state_name='precipMM (M, MS)', val=precip_today_m)
precip_today_ui = self.uiFormatRain(dev=dev, state_name='precipToday (M, MS)', val=precip_today_ui)
weather_states_list.append({'key': 'precip_today', 'value': precip_today, 'uiValue': precip_today_ui})
(precip_1hr, precip_1hr_ui) = self.fixCorruptedData(state_name='precipOneHourMM (M, MS)', val=precip_1hr_m)
precip_1hr_ui = self.uiFormatRain(dev=dev, state_name='precipOneHour (M, MS)', val=precip_1hr_ui)
weather_states_list.append({'key': 'precip_1hr', 'value': precip_1hr, 'uiValue': precip_1hr_ui})
if (config_menu_units == 'M'):
weather_states_list.append({'key': 'windGust', 'value': wind_gust_kph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windGust', val=wind_gust_kph_ui)})
weather_states_list.append({'key': 'windSpeed', 'value': wind_speed_kph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windSpeed', val=wind_speed_kph_ui)})
weather_states_list.append({'key': 'windGustIcon', 'value': unicode(round(wind_gust_kph, 1)).replace('.', )})
weather_states_list.append({'key': 'windSpeedIcon', 'value': unicode(round(wind_speed_kph, 1)).replace('.', )})
weather_states_list.append({'key': 'windString', 'value': u'From the {0} at {1} KPH Gusting to {2} KPH'.format(wind_dir, wind_speed_kph, wind_gust_kph)})
weather_states_list.append({'key': 'windShortString', 'value': u'{0} at {1}'.format(wind_dir, wind_speed_kph)})
weather_states_list.append({'key': 'windStringMetric', 'value': u'From the {0} at {1} KPH Gusting to {2} KPH'.format(wind_dir, wind_speed_kph, wind_gust_kph)})
if (config_menu_units == 'MS'):
weather_states_list.append({'key': 'windGust', 'value': wind_gust_mps, 'uiValue': self.uiFormatWind(dev=dev, state_name='windGust', val=wind_gust_mps_ui)})
weather_states_list.append({'key': 'windSpeed', 'value': wind_speed_mps, 'uiValue': self.uiFormatWind(dev=dev, state_name='windSpeed', val=wind_speed_mps_ui)})
weather_states_list.append({'key': 'windGustIcon', 'value': unicode(round(wind_gust_mps, 1)).replace('.', )})
weather_states_list.append({'key': 'windSpeedIcon', 'value': unicode(round(wind_speed_mps, 1)).replace('.', )})
weather_states_list.append({'key': 'windString', 'value': u'From the {0} at {1} MPS Gusting to {2} MPS'.format(wind_dir, wind_speed_mps, wind_gust_mps)})
weather_states_list.append({'key': 'windShortString', 'value': u'{0} at {1}'.format(wind_dir, wind_speed_mps)})
weather_states_list.append({'key': 'windStringMetric', 'value': u'From the {0} at {1} KPH Gusting to {2} KPH'.format(wind_dir, wind_speed_mps, wind_gust_mps)})
if (config_menu_units in ['I', 'S']):
(precip_today, precip_today_ui) = self.fixCorruptedData(state_name='precipToday (I)', val=precip_today_in)
precip_today_ui = self.uiFormatRain(dev=dev, state_name='precipToday (I)', val=precip_today_ui)
weather_states_list.append({'key': 'precip_today', 'value': precip_today, 'uiValue': precip_today_ui})
(precip_1hr, precip_1hr_ui) = self.fixCorruptedData(state_name='precipOneHour (I)', val=precip_1hr_in)
precip_1hr_ui = self.uiFormatRain(dev=dev, state_name='precipOneHour (I)', val=precip_1hr_ui)
weather_states_list.append({'key': 'precip_1hr', 'value': precip_1hr, 'uiValue': precip_1hr_ui})
weather_states_list.append({'key': 'windGust', 'value': wind_gust_mph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windGust', val=wind_gust_mph_ui)})
weather_states_list.append({'key': 'windSpeed', 'value': wind_speed_mph, 'uiValue': self.uiFormatWind(dev=dev, state_name='windSpeed', val=wind_speed_mph_ui)})
weather_states_list.append({'key': 'windGustIcon', 'value': unicode(round(wind_gust_mph, 1)).replace('.', )})
weather_states_list.append({'key': 'windSpeedIcon', 'value': unicode(round(wind_speed_mph, 1)).replace('.', )})
weather_states_list.append({'key': 'windString', 'value': u'From the {0} at {1} MPH Gusting to {2} MPH'.format(wind_dir, wind_speed_mph, wind_gust_mph)})
weather_states_list.append({'key': 'windShortString', 'value': u'{0} at {1}'.format(wind_dir, wind_speed_mph)})
weather_states_list.append({'key': 'windStringMetric', 'value': ' '})
if (config_menu_units in ['S']):
(dewpoint, dewpoint_ui) = self.fixCorruptedData(state_name='dewpointF (S)', val=dew_point_f)
dewpoint_ui = self.uiFormatTemperature(dev=dev, state_name='dewpointF (S)', val=dewpoint_ui)
weather_states_list.append({'key': 'dewpoint', 'value': dewpoint, 'uiValue': dewpoint_ui})
(feelslike, feelslike_ui) = self.fixCorruptedData(state_name='feelsLikeF (S)', val=feels_like_f)
feelslike_ui = self.uiFormatTemperature(dev=dev, state_name='feelsLikeF (S)', val=feelslike_ui)
weather_states_list.append({'key': 'feelslike', 'value': feelslike, 'uiValue': feelslike_ui})
(heat_index, heat_index_ui) = self.fixCorruptedData(state_name='heatIndexF (S)', val=heat_index_f)
heat_index_ui = self.uiFormatTemperature(dev=dev, state_name='heatIndexF (S)', val=heat_index_ui)
weather_states_list.append({'key': 'heatIndex', 'value': heat_index, 'uiValue': heat_index_ui})
(windchill, windchill_ui) = self.fixCorruptedData(state_name='windChillF (S)', val=wind_chill_f)
windchill_ui = self.uiFormatTemperature(dev=dev, state_name='windChillF (S)', val=windchill_ui)
weather_states_list.append({'key': 'windchill', 'value': windchill, 'uiValue': windchill_ui})
(pressure, pressure_ui) = self.fixCorruptedData(state_name='pressure (S)', val=pressure_in)
weather_states_list.append({'key': 'pressure', 'value': pressure, 'uiValue': u'{0}{1}'.format(pressure_ui, pressure_units)})
weather_states_list.append({'key': 'pressureIcon', 'value': pressure_ui.replace('.', )})
(visibility, visibility_ui) = self.fixCorruptedData(state_name='visibility (S)', val=visibility_mi)
weather_states_list.append({'key': 'visibility', 'value': visibility, 'uiValue': u'{0}{1}'.format(int(round(visibility)), config_distance_units)})
new_props = dev.pluginProps
new_props['address'] = station_id
dev.replacePluginPropsOnServer(new_props)
dev.updateStatesOnServer(weather_states_list)
dev.updateStateImageOnServer(indigo.kStateImageSel.TemperatureSensorOn)
except IndexError:
self.logger.warning(u'Note: List index out of range. This is likely normal.')
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing weather device data.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u' ')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)<|docstring|>Parse weather data to devices
The parseWeatherData() method takes weather data and parses it to Weather
Device states.
-----
:param indigo.Device dev:<|endoftext|> |
c9eb22cb0c3a05e81f7033273fda482102ed3df9d495706a1be9408f868e7cea | def refreshWeatherData(self):
'\n Refresh data for plugin devices\n\n This method refreshes weather data for all devices based on a WUnderground\n general cycle, Action Item or Plugin Menu call.\n\n -----\n '
api_key = self.pluginPrefs['apiKey']
daily_call_limit_reached = self.pluginPrefs.get('dailyCallLimitReached', False)
self.download_interval = dt.timedelta(seconds=int(self.pluginPrefs.get('downloadInterval', '900')))
self.wuOnline = True
try:
if daily_call_limit_reached:
self.callDay()
else:
self.callDay()
self.masterWeatherDict = {}
for dev in indigo.devices.itervalues('self'):
if (not self.wuOnline):
break
if (not dev):
self.logger.info(u"There aren't any devices to poll yet. Sleeping.")
elif (not dev.configured):
self.logger.info(u'A device has been created, but is not fully configured. Sleeping for a minute while you finish.')
if (api_key in ['', 'API Key']):
self.logger.error(u'The plugin requires an API Key. See help for details.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'{0}'.format('No key.'))
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
elif (not dev.enabled):
self.logger.debug(u'{0}: device communication is disabled. Skipping.'.format(dev.name))
dev.updateStateOnServer('onOffState', value=False, uiValue=u'{0}'.format('Disabled'))
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
elif dev.enabled:
self.logger.debug(u'Processing device: {0}'.format(dev.name))
dev.updateStateOnServer('onOffState', value=True, uiValue=u' ')
if dev.pluginProps['isWeatherDevice']:
location = dev.pluginProps['location']
self.getWeatherData(dev)
try:
response = self.masterWeatherDict[location]['response']['error']['type']
if (response == 'querynotfound'):
self.logger.error(u'Location query for {0} not found. Please ensure that device location follows examples precisely.'.format(dev.name))
dev.updateStateOnServer('onOffState', value=False, uiValue=u'Bad Loc')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
except (KeyError, Exception) as error:
error = u'{0}'.format(error)
if (error == "'error'"):
pass
else:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
ignore_estimated = False
try:
estimated = self.masterWeatherDict[location]['current_observation']['estimated']['estimated']
if (estimated == 1):
self.logger.error(u'These are estimated conditions. There may be other functioning weather stations nearby. ({0})'.format(dev.name))
dev.updateStateOnServer('estimated', value='true', uiValue=u'True')
if self.pluginPrefs.get('ignoreEstimated', False):
ignore_estimated = True
except KeyError as error:
error = u'{0}'.format(error)
if (error == "'estimated'"):
dev.updateStateOnServer('estimated', value='false', uiValue=u'False')
ignore_estimated = False
else:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
ignore_estimated = False
try:
device_epoch = dev.states['currentObservationEpoch']
try:
device_epoch = int(device_epoch)
except ValueError:
device_epoch = 0
try:
weather_data_epoch = int(self.masterWeatherDict[location]['current_observation']['observation_epoch'])
except ValueError:
weather_data_epoch = 0
good_time = (device_epoch <= weather_data_epoch)
if (not good_time):
self.logger.info(u'Latest data are older than data we already have. Skipping {0} update.'.format(dev.name))
except KeyError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.info(u'{0} cannot determine age of data. Skipping until next scheduled poll.'.format(dev.name))
good_time = False
if ((self.masterWeatherDict != {}) and good_time and (not ignore_estimated)):
if (dev.model in ['Almanac', 'WUnderground Almanac']):
self.parseAlmanacData(dev)
elif (dev.model in ['Astronomy', 'WUnderground Astronomy']):
self.parseAstronomyData(dev)
elif (dev.model in ['WUnderground Hourly Forecast', 'Hourly Forecast']):
self.parseHourlyData(dev)
elif (dev.model in ['Ten Day Forecast', 'WUnderground Ten Day Forecast']):
self.parseTenDayData(dev)
elif (dev.model in ['WUnderground Tides', 'Tides']):
self.parseTidesData(dev)
elif (dev.model in ['WUnderground Device', 'WUnderground Weather', 'WUnderground Weather Device', 'Weather Underground', 'Weather']):
self.parseWeatherData(dev)
self.parseAlertsData(dev)
self.parseForecastData(dev)
if self.pluginPrefs.get('updaterEmailsEnabled', False):
self.emailForecast(dev)
elif (dev.model in ['Satellite Image Downloader', 'WUnderground Satellite Image Downloader']):
self.getSatelliteImage(dev)
elif (dev.model in ['WUnderground Radar']):
self.getWUradar(dev)
self.logger.debug(u'{0} locations polled: {1}'.format(len(self.masterWeatherDict.keys()), self.masterWeatherDict.keys()))
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing Weather data. Dev: {0}'.format(dev.name)) | Refresh data for plugin devices
This method refreshes weather data for all devices based on a WUnderground
general cycle, Action Item or Plugin Menu call.
----- | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | refreshWeatherData | DaveL17/WUnderground7 | 0 | python | def refreshWeatherData(self):
'\n Refresh data for plugin devices\n\n This method refreshes weather data for all devices based on a WUnderground\n general cycle, Action Item or Plugin Menu call.\n\n -----\n '
api_key = self.pluginPrefs['apiKey']
daily_call_limit_reached = self.pluginPrefs.get('dailyCallLimitReached', False)
self.download_interval = dt.timedelta(seconds=int(self.pluginPrefs.get('downloadInterval', '900')))
self.wuOnline = True
try:
if daily_call_limit_reached:
self.callDay()
else:
self.callDay()
self.masterWeatherDict = {}
for dev in indigo.devices.itervalues('self'):
if (not self.wuOnline):
break
if (not dev):
self.logger.info(u"There aren't any devices to poll yet. Sleeping.")
elif (not dev.configured):
self.logger.info(u'A device has been created, but is not fully configured. Sleeping for a minute while you finish.')
if (api_key in [, 'API Key']):
self.logger.error(u'The plugin requires an API Key. See help for details.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'{0}'.format('No key.'))
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
elif (not dev.enabled):
self.logger.debug(u'{0}: device communication is disabled. Skipping.'.format(dev.name))
dev.updateStateOnServer('onOffState', value=False, uiValue=u'{0}'.format('Disabled'))
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
elif dev.enabled:
self.logger.debug(u'Processing device: {0}'.format(dev.name))
dev.updateStateOnServer('onOffState', value=True, uiValue=u' ')
if dev.pluginProps['isWeatherDevice']:
location = dev.pluginProps['location']
self.getWeatherData(dev)
try:
response = self.masterWeatherDict[location]['response']['error']['type']
if (response == 'querynotfound'):
self.logger.error(u'Location query for {0} not found. Please ensure that device location follows examples precisely.'.format(dev.name))
dev.updateStateOnServer('onOffState', value=False, uiValue=u'Bad Loc')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
except (KeyError, Exception) as error:
error = u'{0}'.format(error)
if (error == "'error'"):
pass
else:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
ignore_estimated = False
try:
estimated = self.masterWeatherDict[location]['current_observation']['estimated']['estimated']
if (estimated == 1):
self.logger.error(u'These are estimated conditions. There may be other functioning weather stations nearby. ({0})'.format(dev.name))
dev.updateStateOnServer('estimated', value='true', uiValue=u'True')
if self.pluginPrefs.get('ignoreEstimated', False):
ignore_estimated = True
except KeyError as error:
error = u'{0}'.format(error)
if (error == "'estimated'"):
dev.updateStateOnServer('estimated', value='false', uiValue=u'False')
ignore_estimated = False
else:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
ignore_estimated = False
try:
device_epoch = dev.states['currentObservationEpoch']
try:
device_epoch = int(device_epoch)
except ValueError:
device_epoch = 0
try:
weather_data_epoch = int(self.masterWeatherDict[location]['current_observation']['observation_epoch'])
except ValueError:
weather_data_epoch = 0
good_time = (device_epoch <= weather_data_epoch)
if (not good_time):
self.logger.info(u'Latest data are older than data we already have. Skipping {0} update.'.format(dev.name))
except KeyError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.info(u'{0} cannot determine age of data. Skipping until next scheduled poll.'.format(dev.name))
good_time = False
if ((self.masterWeatherDict != {}) and good_time and (not ignore_estimated)):
if (dev.model in ['Almanac', 'WUnderground Almanac']):
self.parseAlmanacData(dev)
elif (dev.model in ['Astronomy', 'WUnderground Astronomy']):
self.parseAstronomyData(dev)
elif (dev.model in ['WUnderground Hourly Forecast', 'Hourly Forecast']):
self.parseHourlyData(dev)
elif (dev.model in ['Ten Day Forecast', 'WUnderground Ten Day Forecast']):
self.parseTenDayData(dev)
elif (dev.model in ['WUnderground Tides', 'Tides']):
self.parseTidesData(dev)
elif (dev.model in ['WUnderground Device', 'WUnderground Weather', 'WUnderground Weather Device', 'Weather Underground', 'Weather']):
self.parseWeatherData(dev)
self.parseAlertsData(dev)
self.parseForecastData(dev)
if self.pluginPrefs.get('updaterEmailsEnabled', False):
self.emailForecast(dev)
elif (dev.model in ['Satellite Image Downloader', 'WUnderground Satellite Image Downloader']):
self.getSatelliteImage(dev)
elif (dev.model in ['WUnderground Radar']):
self.getWUradar(dev)
self.logger.debug(u'{0} locations polled: {1}'.format(len(self.masterWeatherDict.keys()), self.masterWeatherDict.keys()))
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing Weather data. Dev: {0}'.format(dev.name)) | def refreshWeatherData(self):
'\n Refresh data for plugin devices\n\n This method refreshes weather data for all devices based on a WUnderground\n general cycle, Action Item or Plugin Menu call.\n\n -----\n '
api_key = self.pluginPrefs['apiKey']
daily_call_limit_reached = self.pluginPrefs.get('dailyCallLimitReached', False)
self.download_interval = dt.timedelta(seconds=int(self.pluginPrefs.get('downloadInterval', '900')))
self.wuOnline = True
try:
if daily_call_limit_reached:
self.callDay()
else:
self.callDay()
self.masterWeatherDict = {}
for dev in indigo.devices.itervalues('self'):
if (not self.wuOnline):
break
if (not dev):
self.logger.info(u"There aren't any devices to poll yet. Sleeping.")
elif (not dev.configured):
self.logger.info(u'A device has been created, but is not fully configured. Sleeping for a minute while you finish.')
if (api_key in [, 'API Key']):
self.logger.error(u'The plugin requires an API Key. See help for details.')
dev.updateStateOnServer('onOffState', value=False, uiValue=u'{0}'.format('No key.'))
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
elif (not dev.enabled):
self.logger.debug(u'{0}: device communication is disabled. Skipping.'.format(dev.name))
dev.updateStateOnServer('onOffState', value=False, uiValue=u'{0}'.format('Disabled'))
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
elif dev.enabled:
self.logger.debug(u'Processing device: {0}'.format(dev.name))
dev.updateStateOnServer('onOffState', value=True, uiValue=u' ')
if dev.pluginProps['isWeatherDevice']:
location = dev.pluginProps['location']
self.getWeatherData(dev)
try:
response = self.masterWeatherDict[location]['response']['error']['type']
if (response == 'querynotfound'):
self.logger.error(u'Location query for {0} not found. Please ensure that device location follows examples precisely.'.format(dev.name))
dev.updateStateOnServer('onOffState', value=False, uiValue=u'Bad Loc')
dev.updateStateImageOnServer(indigo.kStateImageSel.SensorOff)
except (KeyError, Exception) as error:
error = u'{0}'.format(error)
if (error == "'error'"):
pass
else:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
ignore_estimated = False
try:
estimated = self.masterWeatherDict[location]['current_observation']['estimated']['estimated']
if (estimated == 1):
self.logger.error(u'These are estimated conditions. There may be other functioning weather stations nearby. ({0})'.format(dev.name))
dev.updateStateOnServer('estimated', value='true', uiValue=u'True')
if self.pluginPrefs.get('ignoreEstimated', False):
ignore_estimated = True
except KeyError as error:
error = u'{0}'.format(error)
if (error == "'estimated'"):
dev.updateStateOnServer('estimated', value='false', uiValue=u'False')
ignore_estimated = False
else:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
ignore_estimated = False
try:
device_epoch = dev.states['currentObservationEpoch']
try:
device_epoch = int(device_epoch)
except ValueError:
device_epoch = 0
try:
weather_data_epoch = int(self.masterWeatherDict[location]['current_observation']['observation_epoch'])
except ValueError:
weather_data_epoch = 0
good_time = (device_epoch <= weather_data_epoch)
if (not good_time):
self.logger.info(u'Latest data are older than data we already have. Skipping {0} update.'.format(dev.name))
except KeyError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.info(u'{0} cannot determine age of data. Skipping until next scheduled poll.'.format(dev.name))
good_time = False
if ((self.masterWeatherDict != {}) and good_time and (not ignore_estimated)):
if (dev.model in ['Almanac', 'WUnderground Almanac']):
self.parseAlmanacData(dev)
elif (dev.model in ['Astronomy', 'WUnderground Astronomy']):
self.parseAstronomyData(dev)
elif (dev.model in ['WUnderground Hourly Forecast', 'Hourly Forecast']):
self.parseHourlyData(dev)
elif (dev.model in ['Ten Day Forecast', 'WUnderground Ten Day Forecast']):
self.parseTenDayData(dev)
elif (dev.model in ['WUnderground Tides', 'Tides']):
self.parseTidesData(dev)
elif (dev.model in ['WUnderground Device', 'WUnderground Weather', 'WUnderground Weather Device', 'Weather Underground', 'Weather']):
self.parseWeatherData(dev)
self.parseAlertsData(dev)
self.parseForecastData(dev)
if self.pluginPrefs.get('updaterEmailsEnabled', False):
self.emailForecast(dev)
elif (dev.model in ['Satellite Image Downloader', 'WUnderground Satellite Image Downloader']):
self.getSatelliteImage(dev)
elif (dev.model in ['WUnderground Radar']):
self.getWUradar(dev)
self.logger.debug(u'{0} locations polled: {1}'.format(len(self.masterWeatherDict.keys()), self.masterWeatherDict.keys()))
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.error(u'Problem parsing Weather data. Dev: {0}'.format(dev.name))<|docstring|>Refresh data for plugin devices
This method refreshes weather data for all devices based on a WUnderground
general cycle, Action Item or Plugin Menu call.
-----<|endoftext|> |
28598c228983d21f4528cd4aaeca7976dd3a6bf1c7918b0ff8d8b0088e61d72c | def triggerProcessing(self):
'\n Fire various triggers for plugin devices\n\n Weather Location Offline:\n The triggerProcessing method will examine the time of the last weather location\n update and, if the update exceeds the time delta specified in a WUnderground\n Plugin Weather Location Offline trigger, the trigger will be fired. The plugin\n examines the value of the latest "currentObservationEpoch" and *not* the Indigo\n Last Update value.\n\n An additional event that will cause a trigger to be fired is if the weather\n location temperature is less than -55 (Weather Underground will often set a\n value to a variation of -99 (-55 C) to indicate that a data value is invalid.\n\n Severe Weather Alerts:\n This trigger will fire if a weather location has at least one severe weather\n alert.\n\n Note that trigger processing will only occur during routine weather update\n cycles and will not be triggered when a data refresh is called from the Indigo\n Plugins menu.\n\n -----\n '
time_format = '%Y-%m-%d %H:%M:%S'
self.masterTriggerDict = {unicode(trigger.pluginProps['listOfDevices']): (trigger.pluginProps['offlineTimer'], trigger.id) for trigger in indigo.triggers.iter(filter='self.weatherSiteOffline')}
self.logger.debug(u'Rebuild Master Trigger Dict: {0}'.format(self.masterTriggerDict))
try:
for dev in indigo.devices.itervalues(filter='self'):
if (str(dev.id) in self.masterTriggerDict.keys()):
if dev.enabled:
trigger_id = self.masterTriggerDict[str(dev.id)][1]
if (indigo.triggers[trigger_id].pluginTypeId == 'weatherSiteOffline'):
offline_delta = dt.timedelta(minutes=int(self.masterTriggerDict.get(unicode(dev.id), ('60', ''))[0]))
self.logger.debug(u'Offline weather location delta: {0}'.format(offline_delta))
current_observation_epoch = float(dev.states['currentObservationEpoch'])
current_observation = time.strftime(time_format, time.localtime(current_observation_epoch))
current_observation = dt.datetime.strptime(current_observation, time_format)
diff = (indigo.server.getTime() - current_observation)
if (diff >= offline_delta):
total_seconds = int(diff.total_seconds())
(days, remainder) = divmod(total_seconds, ((60 * 60) * 24))
(hours, remainder) = divmod(remainder, (60 * 60))
(minutes, seconds) = divmod(remainder, 60)
diff_msg = u'{} days, {} hrs, {} mins'.format(days, hours, minutes)
dev.updateStateImageOnServer(indigo.kStateImageSel.TemperatureSensor)
dev.updateStateOnServer('onOffState', value='offline')
if indigo.triggers[trigger_id].enabled:
self.logger.warning(u'{0} location appears to be offline for {1}'.format(dev.name, diff_msg))
indigo.trigger.execute(trigger_id)
elif (dev.states['temp'] <= (- 55.0)):
dev.updateStateImageOnServer(indigo.kStateImageSel.TemperatureSensor)
dev.updateStateOnServer('onOffState', value='offline')
if indigo.triggers[trigger_id].enabled:
self.logger.warning(u'{0} location appears to be offline (ambient temperature lower than -55).'.format(dev.name))
indigo.trigger.execute(trigger_id)
for trigger in indigo.triggers.itervalues('self.weatherAlert'):
if ((int(trigger.pluginProps['listOfDevices']) == dev.id) and (dev.states['alertStatus'] == 'true') and trigger.enabled):
self.logger.warning(u'{0} location has at least one severe weather alert.'.format(dev.name))
indigo.trigger.execute(trigger.id)
except KeyError:
pass | Fire various triggers for plugin devices
Weather Location Offline:
The triggerProcessing method will examine the time of the last weather location
update and, if the update exceeds the time delta specified in a WUnderground
Plugin Weather Location Offline trigger, the trigger will be fired. The plugin
examines the value of the latest "currentObservationEpoch" and *not* the Indigo
Last Update value.
An additional event that will cause a trigger to be fired is if the weather
location temperature is less than -55 (Weather Underground will often set a
value to a variation of -99 (-55 C) to indicate that a data value is invalid.
Severe Weather Alerts:
This trigger will fire if a weather location has at least one severe weather
alert.
Note that trigger processing will only occur during routine weather update
cycles and will not be triggered when a data refresh is called from the Indigo
Plugins menu.
----- | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | triggerProcessing | DaveL17/WUnderground7 | 0 | python | def triggerProcessing(self):
'\n Fire various triggers for plugin devices\n\n Weather Location Offline:\n The triggerProcessing method will examine the time of the last weather location\n update and, if the update exceeds the time delta specified in a WUnderground\n Plugin Weather Location Offline trigger, the trigger will be fired. The plugin\n examines the value of the latest "currentObservationEpoch" and *not* the Indigo\n Last Update value.\n\n An additional event that will cause a trigger to be fired is if the weather\n location temperature is less than -55 (Weather Underground will often set a\n value to a variation of -99 (-55 C) to indicate that a data value is invalid.\n\n Severe Weather Alerts:\n This trigger will fire if a weather location has at least one severe weather\n alert.\n\n Note that trigger processing will only occur during routine weather update\n cycles and will not be triggered when a data refresh is called from the Indigo\n Plugins menu.\n\n -----\n '
time_format = '%Y-%m-%d %H:%M:%S'
self.masterTriggerDict = {unicode(trigger.pluginProps['listOfDevices']): (trigger.pluginProps['offlineTimer'], trigger.id) for trigger in indigo.triggers.iter(filter='self.weatherSiteOffline')}
self.logger.debug(u'Rebuild Master Trigger Dict: {0}'.format(self.masterTriggerDict))
try:
for dev in indigo.devices.itervalues(filter='self'):
if (str(dev.id) in self.masterTriggerDict.keys()):
if dev.enabled:
trigger_id = self.masterTriggerDict[str(dev.id)][1]
if (indigo.triggers[trigger_id].pluginTypeId == 'weatherSiteOffline'):
offline_delta = dt.timedelta(minutes=int(self.masterTriggerDict.get(unicode(dev.id), ('60', ))[0]))
self.logger.debug(u'Offline weather location delta: {0}'.format(offline_delta))
current_observation_epoch = float(dev.states['currentObservationEpoch'])
current_observation = time.strftime(time_format, time.localtime(current_observation_epoch))
current_observation = dt.datetime.strptime(current_observation, time_format)
diff = (indigo.server.getTime() - current_observation)
if (diff >= offline_delta):
total_seconds = int(diff.total_seconds())
(days, remainder) = divmod(total_seconds, ((60 * 60) * 24))
(hours, remainder) = divmod(remainder, (60 * 60))
(minutes, seconds) = divmod(remainder, 60)
diff_msg = u'{} days, {} hrs, {} mins'.format(days, hours, minutes)
dev.updateStateImageOnServer(indigo.kStateImageSel.TemperatureSensor)
dev.updateStateOnServer('onOffState', value='offline')
if indigo.triggers[trigger_id].enabled:
self.logger.warning(u'{0} location appears to be offline for {1}'.format(dev.name, diff_msg))
indigo.trigger.execute(trigger_id)
elif (dev.states['temp'] <= (- 55.0)):
dev.updateStateImageOnServer(indigo.kStateImageSel.TemperatureSensor)
dev.updateStateOnServer('onOffState', value='offline')
if indigo.triggers[trigger_id].enabled:
self.logger.warning(u'{0} location appears to be offline (ambient temperature lower than -55).'.format(dev.name))
indigo.trigger.execute(trigger_id)
for trigger in indigo.triggers.itervalues('self.weatherAlert'):
if ((int(trigger.pluginProps['listOfDevices']) == dev.id) and (dev.states['alertStatus'] == 'true') and trigger.enabled):
self.logger.warning(u'{0} location has at least one severe weather alert.'.format(dev.name))
indigo.trigger.execute(trigger.id)
except KeyError:
pass | def triggerProcessing(self):
'\n Fire various triggers for plugin devices\n\n Weather Location Offline:\n The triggerProcessing method will examine the time of the last weather location\n update and, if the update exceeds the time delta specified in a WUnderground\n Plugin Weather Location Offline trigger, the trigger will be fired. The plugin\n examines the value of the latest "currentObservationEpoch" and *not* the Indigo\n Last Update value.\n\n An additional event that will cause a trigger to be fired is if the weather\n location temperature is less than -55 (Weather Underground will often set a\n value to a variation of -99 (-55 C) to indicate that a data value is invalid.\n\n Severe Weather Alerts:\n This trigger will fire if a weather location has at least one severe weather\n alert.\n\n Note that trigger processing will only occur during routine weather update\n cycles and will not be triggered when a data refresh is called from the Indigo\n Plugins menu.\n\n -----\n '
time_format = '%Y-%m-%d %H:%M:%S'
self.masterTriggerDict = {unicode(trigger.pluginProps['listOfDevices']): (trigger.pluginProps['offlineTimer'], trigger.id) for trigger in indigo.triggers.iter(filter='self.weatherSiteOffline')}
self.logger.debug(u'Rebuild Master Trigger Dict: {0}'.format(self.masterTriggerDict))
try:
for dev in indigo.devices.itervalues(filter='self'):
if (str(dev.id) in self.masterTriggerDict.keys()):
if dev.enabled:
trigger_id = self.masterTriggerDict[str(dev.id)][1]
if (indigo.triggers[trigger_id].pluginTypeId == 'weatherSiteOffline'):
offline_delta = dt.timedelta(minutes=int(self.masterTriggerDict.get(unicode(dev.id), ('60', ))[0]))
self.logger.debug(u'Offline weather location delta: {0}'.format(offline_delta))
current_observation_epoch = float(dev.states['currentObservationEpoch'])
current_observation = time.strftime(time_format, time.localtime(current_observation_epoch))
current_observation = dt.datetime.strptime(current_observation, time_format)
diff = (indigo.server.getTime() - current_observation)
if (diff >= offline_delta):
total_seconds = int(diff.total_seconds())
(days, remainder) = divmod(total_seconds, ((60 * 60) * 24))
(hours, remainder) = divmod(remainder, (60 * 60))
(minutes, seconds) = divmod(remainder, 60)
diff_msg = u'{} days, {} hrs, {} mins'.format(days, hours, minutes)
dev.updateStateImageOnServer(indigo.kStateImageSel.TemperatureSensor)
dev.updateStateOnServer('onOffState', value='offline')
if indigo.triggers[trigger_id].enabled:
self.logger.warning(u'{0} location appears to be offline for {1}'.format(dev.name, diff_msg))
indigo.trigger.execute(trigger_id)
elif (dev.states['temp'] <= (- 55.0)):
dev.updateStateImageOnServer(indigo.kStateImageSel.TemperatureSensor)
dev.updateStateOnServer('onOffState', value='offline')
if indigo.triggers[trigger_id].enabled:
self.logger.warning(u'{0} location appears to be offline (ambient temperature lower than -55).'.format(dev.name))
indigo.trigger.execute(trigger_id)
for trigger in indigo.triggers.itervalues('self.weatherAlert'):
if ((int(trigger.pluginProps['listOfDevices']) == dev.id) and (dev.states['alertStatus'] == 'true') and trigger.enabled):
self.logger.warning(u'{0} location has at least one severe weather alert.'.format(dev.name))
indigo.trigger.execute(trigger.id)
except KeyError:
pass<|docstring|>Fire various triggers for plugin devices
Weather Location Offline:
The triggerProcessing method will examine the time of the last weather location
update and, if the update exceeds the time delta specified in a WUnderground
Plugin Weather Location Offline trigger, the trigger will be fired. The plugin
examines the value of the latest "currentObservationEpoch" and *not* the Indigo
Last Update value.
An additional event that will cause a trigger to be fired is if the weather
location temperature is less than -55 (Weather Underground will often set a
value to a variation of -99 (-55 C) to indicate that a data value is invalid.
Severe Weather Alerts:
This trigger will fire if a weather location has at least one severe weather
alert.
Note that trigger processing will only occur during routine weather update
cycles and will not be triggered when a data refresh is called from the Indigo
Plugins menu.
-----<|endoftext|> |
6a458cd1ca6db240455b8e84e8d640f20a96f2a29a5f9177c900bd3d80514a66 | def uiFormatItemListTemperature(self, val):
'\n Format temperature values for Indigo UI\n\n Adjusts the decimal precision of the temperature value for the Indigo Item\n List. Note: this method needs to return a string rather than a Unicode string\n (for now.)\n\n -----\n\n :param val:\n '
try:
if (int(self.pluginPrefs.get('itemListTempDecimal', '1')) == 0):
val = float(val)
return u'{0:0.0f}'.format(val)
else:
return u'{0}'.format(val)
except ValueError:
return u'{0}'.format(val) | Format temperature values for Indigo UI
Adjusts the decimal precision of the temperature value for the Indigo Item
List. Note: this method needs to return a string rather than a Unicode string
(for now.)
-----
:param val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | uiFormatItemListTemperature | DaveL17/WUnderground7 | 0 | python | def uiFormatItemListTemperature(self, val):
'\n Format temperature values for Indigo UI\n\n Adjusts the decimal precision of the temperature value for the Indigo Item\n List. Note: this method needs to return a string rather than a Unicode string\n (for now.)\n\n -----\n\n :param val:\n '
try:
if (int(self.pluginPrefs.get('itemListTempDecimal', '1')) == 0):
val = float(val)
return u'{0:0.0f}'.format(val)
else:
return u'{0}'.format(val)
except ValueError:
return u'{0}'.format(val) | def uiFormatItemListTemperature(self, val):
'\n Format temperature values for Indigo UI\n\n Adjusts the decimal precision of the temperature value for the Indigo Item\n List. Note: this method needs to return a string rather than a Unicode string\n (for now.)\n\n -----\n\n :param val:\n '
try:
if (int(self.pluginPrefs.get('itemListTempDecimal', '1')) == 0):
val = float(val)
return u'{0:0.0f}'.format(val)
else:
return u'{0}'.format(val)
except ValueError:
return u'{0}'.format(val)<|docstring|>Format temperature values for Indigo UI
Adjusts the decimal precision of the temperature value for the Indigo Item
List. Note: this method needs to return a string rather than a Unicode string
(for now.)
-----
:param val:<|endoftext|> |
07dbc9875b0cba994769f8a2e732e9fc75e22bb8f47de3d6094c15be54e35f72 | def uiFormatPercentage(self, dev, state_name, val):
'\n Format percentage data for Indigo UI\n\n Adjusts the decimal precision of percentage values for display in control\n pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param str val:\n '
humidity_decimal = int(self.pluginPrefs.get('uiHumidityDecimal', '1'))
percentage_units = unicode(dev.pluginProps.get('percentageUnits', ''))
try:
return u'{0:0.{precision}f}{1}'.format(float(val), percentage_units, precision=humidity_decimal)
except ValueError:
return u'{0}{1}'.format(val, percentage_units) | Format percentage data for Indigo UI
Adjusts the decimal precision of percentage values for display in control
pages, etc.
-----
:param indigo.Device dev:
:param str state_name:
:param str val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | uiFormatPercentage | DaveL17/WUnderground7 | 0 | python | def uiFormatPercentage(self, dev, state_name, val):
'\n Format percentage data for Indigo UI\n\n Adjusts the decimal precision of percentage values for display in control\n pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param str val:\n '
humidity_decimal = int(self.pluginPrefs.get('uiHumidityDecimal', '1'))
percentage_units = unicode(dev.pluginProps.get('percentageUnits', ))
try:
return u'{0:0.{precision}f}{1}'.format(float(val), percentage_units, precision=humidity_decimal)
except ValueError:
return u'{0}{1}'.format(val, percentage_units) | def uiFormatPercentage(self, dev, state_name, val):
'\n Format percentage data for Indigo UI\n\n Adjusts the decimal precision of percentage values for display in control\n pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param str val:\n '
humidity_decimal = int(self.pluginPrefs.get('uiHumidityDecimal', '1'))
percentage_units = unicode(dev.pluginProps.get('percentageUnits', ))
try:
return u'{0:0.{precision}f}{1}'.format(float(val), percentage_units, precision=humidity_decimal)
except ValueError:
return u'{0}{1}'.format(val, percentage_units)<|docstring|>Format percentage data for Indigo UI
Adjusts the decimal precision of percentage values for display in control
pages, etc.
-----
:param indigo.Device dev:
:param str state_name:
:param str val:<|endoftext|> |
17a30d9e3a7b4f43eaac72b1910780ca1d281064f7aad448c389f2689d5c3498 | def uiFormatPressureSymbol(self, state_name, val):
'\n Convert pressure trend symbol\n\n Converts the barometric pressure trend symbol to something more human friendly.\n\n -----\n\n :param str state_name:\n :param val:\n '
pref = self.pluginPrefs['uiPressureTrend']
translator = {'graphic': {'+': u'⬆'.encode('utf-8'), '-': u'⬇'.encode('utf-8'), '0': u'➡'.encode('utf-8')}, 'lower_letters': {'+': 'r', '-': 'f', '0': 's'}, 'lower_words': {'+': 'rising', '-': 'falling', '0': 'steady'}, 'native': {'+': '+', '-': '-', '0': '0'}, 'text': {'+': '^', '-': 'v', '0': '-'}, 'upper_letters': {'+': 'R', '-': 'F', '0': 'S'}, 'upper_words': {'+': 'Rising', '-': 'Falling', '0': 'Steady'}}
try:
return translator[pref][val]
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Error setting {0} pressure.')
return val | Convert pressure trend symbol
Converts the barometric pressure trend symbol to something more human friendly.
-----
:param str state_name:
:param val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | uiFormatPressureSymbol | DaveL17/WUnderground7 | 0 | python | def uiFormatPressureSymbol(self, state_name, val):
'\n Convert pressure trend symbol\n\n Converts the barometric pressure trend symbol to something more human friendly.\n\n -----\n\n :param str state_name:\n :param val:\n '
pref = self.pluginPrefs['uiPressureTrend']
translator = {'graphic': {'+': u'⬆'.encode('utf-8'), '-': u'⬇'.encode('utf-8'), '0': u'➡'.encode('utf-8')}, 'lower_letters': {'+': 'r', '-': 'f', '0': 's'}, 'lower_words': {'+': 'rising', '-': 'falling', '0': 'steady'}, 'native': {'+': '+', '-': '-', '0': '0'}, 'text': {'+': '^', '-': 'v', '0': '-'}, 'upper_letters': {'+': 'R', '-': 'F', '0': 'S'}, 'upper_words': {'+': 'Rising', '-': 'Falling', '0': 'Steady'}}
try:
return translator[pref][val]
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Error setting {0} pressure.')
return val | def uiFormatPressureSymbol(self, state_name, val):
'\n Convert pressure trend symbol\n\n Converts the barometric pressure trend symbol to something more human friendly.\n\n -----\n\n :param str state_name:\n :param val:\n '
pref = self.pluginPrefs['uiPressureTrend']
translator = {'graphic': {'+': u'⬆'.encode('utf-8'), '-': u'⬇'.encode('utf-8'), '0': u'➡'.encode('utf-8')}, 'lower_letters': {'+': 'r', '-': 'f', '0': 's'}, 'lower_words': {'+': 'rising', '-': 'falling', '0': 'steady'}, 'native': {'+': '+', '-': '-', '0': '0'}, 'text': {'+': '^', '-': 'v', '0': '-'}, 'upper_letters': {'+': 'R', '-': 'F', '0': 'S'}, 'upper_words': {'+': 'Rising', '-': 'Falling', '0': 'Steady'}}
try:
return translator[pref][val]
except Exception:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Error setting {0} pressure.')
return val<|docstring|>Convert pressure trend symbol
Converts the barometric pressure trend symbol to something more human friendly.
-----
:param str state_name:
:param val:<|endoftext|> |
2dc5d288d052b67543a727b0490ddfa61fbebef8ec253ba75bd08795d71f0b44 | def uiFormatRain(self, dev, state_name, val):
'\n Format rain data for Indigo UI\n\n Adds rain units to rain values for display in control pages, etc.\n\n -----\n\n :param indigo.Devices dev:\n :param str state_name:\n :param val:\n '
try:
rain_units = dev.pluginProps['rainUnits']
except KeyError:
rain_units = dev.pluginProps.get('rainAmountUnits', '')
if (val in ['NA', 'N/A', '--', '']):
return val
try:
return u'{0:0.2f}{1}'.format(float(val), rain_units)
except ValueError:
return u'{0}'.format(val) | Format rain data for Indigo UI
Adds rain units to rain values for display in control pages, etc.
-----
:param indigo.Devices dev:
:param str state_name:
:param val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | uiFormatRain | DaveL17/WUnderground7 | 0 | python | def uiFormatRain(self, dev, state_name, val):
'\n Format rain data for Indigo UI\n\n Adds rain units to rain values for display in control pages, etc.\n\n -----\n\n :param indigo.Devices dev:\n :param str state_name:\n :param val:\n '
try:
rain_units = dev.pluginProps['rainUnits']
except KeyError:
rain_units = dev.pluginProps.get('rainAmountUnits', )
if (val in ['NA', 'N/A', '--', ]):
return val
try:
return u'{0:0.2f}{1}'.format(float(val), rain_units)
except ValueError:
return u'{0}'.format(val) | def uiFormatRain(self, dev, state_name, val):
'\n Format rain data for Indigo UI\n\n Adds rain units to rain values for display in control pages, etc.\n\n -----\n\n :param indigo.Devices dev:\n :param str state_name:\n :param val:\n '
try:
rain_units = dev.pluginProps['rainUnits']
except KeyError:
rain_units = dev.pluginProps.get('rainAmountUnits', )
if (val in ['NA', 'N/A', '--', ]):
return val
try:
return u'{0:0.2f}{1}'.format(float(val), rain_units)
except ValueError:
return u'{0}'.format(val)<|docstring|>Format rain data for Indigo UI
Adds rain units to rain values for display in control pages, etc.
-----
:param indigo.Devices dev:
:param str state_name:
:param val:<|endoftext|> |
a9779bd4348b48575078c61b952e40a7b48427b704e2d6e5a6483573506ca6a8 | def uiFormatSnow(self, dev, state_name, val):
'\n Format snow data for Indigo UI\n\n Adjusts the display format of snow values for display in control pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param val:\n '
if (val in ['NA', 'N/A', '--', '']):
return val
try:
return u'{0}{1}'.format(val, dev.pluginProps.get('snowAmountUnits', ''))
except ValueError:
return u'{0}'.format(val) | Format snow data for Indigo UI
Adjusts the display format of snow values for display in control pages, etc.
-----
:param indigo.Device dev:
:param str state_name:
:param val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | uiFormatSnow | DaveL17/WUnderground7 | 0 | python | def uiFormatSnow(self, dev, state_name, val):
'\n Format snow data for Indigo UI\n\n Adjusts the display format of snow values for display in control pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param val:\n '
if (val in ['NA', 'N/A', '--', ]):
return val
try:
return u'{0}{1}'.format(val, dev.pluginProps.get('snowAmountUnits', ))
except ValueError:
return u'{0}'.format(val) | def uiFormatSnow(self, dev, state_name, val):
'\n Format snow data for Indigo UI\n\n Adjusts the display format of snow values for display in control pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param val:\n '
if (val in ['NA', 'N/A', '--', ]):
return val
try:
return u'{0}{1}'.format(val, dev.pluginProps.get('snowAmountUnits', ))
except ValueError:
return u'{0}'.format(val)<|docstring|>Format snow data for Indigo UI
Adjusts the display format of snow values for display in control pages, etc.
-----
:param indigo.Device dev:
:param str state_name:
:param val:<|endoftext|> |
7f788928ebff45ea65f56be98fa80201ddf11eaeda481d2259f924cb1906f04c | def uiFormatTemperature(self, dev, state_name, val):
'\n Format temperature data for Indigo UI\n\n Adjusts the decimal precision of certain temperature values and appends the\n desired units string for display in control pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param val:\n '
temp_decimal = int(self.pluginPrefs.get('uiTempDecimal', '1'))
temperature_units = unicode(dev.pluginProps.get('temperatureUnits', ''))
try:
return u'{0:0.{precision}f}{1}'.format(float(val), temperature_units, precision=temp_decimal)
except ValueError:
return u'--' | Format temperature data for Indigo UI
Adjusts the decimal precision of certain temperature values and appends the
desired units string for display in control pages, etc.
-----
:param indigo.Device dev:
:param str state_name:
:param val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | uiFormatTemperature | DaveL17/WUnderground7 | 0 | python | def uiFormatTemperature(self, dev, state_name, val):
'\n Format temperature data for Indigo UI\n\n Adjusts the decimal precision of certain temperature values and appends the\n desired units string for display in control pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param val:\n '
temp_decimal = int(self.pluginPrefs.get('uiTempDecimal', '1'))
temperature_units = unicode(dev.pluginProps.get('temperatureUnits', ))
try:
return u'{0:0.{precision}f}{1}'.format(float(val), temperature_units, precision=temp_decimal)
except ValueError:
return u'--' | def uiFormatTemperature(self, dev, state_name, val):
'\n Format temperature data for Indigo UI\n\n Adjusts the decimal precision of certain temperature values and appends the\n desired units string for display in control pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param val:\n '
temp_decimal = int(self.pluginPrefs.get('uiTempDecimal', '1'))
temperature_units = unicode(dev.pluginProps.get('temperatureUnits', ))
try:
return u'{0:0.{precision}f}{1}'.format(float(val), temperature_units, precision=temp_decimal)
except ValueError:
return u'--'<|docstring|>Format temperature data for Indigo UI
Adjusts the decimal precision of certain temperature values and appends the
desired units string for display in control pages, etc.
-----
:param indigo.Device dev:
:param str state_name:
:param val:<|endoftext|> |
5795f55f859e3b09f3f0d13101e8e57937cc26c9d1b4ef41f4c6a187187d2f07 | def uiFormatWind(self, dev, state_name, val):
'\n Format wind data for Indigo UI\n\n Adjusts the decimal precision of certain wind values for display in control\n pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param val:\n '
wind_decimal = int(self.pluginPrefs.get('uiWindDecimal', '1'))
wind_units = unicode(dev.pluginProps.get('windUnits', ''))
try:
return u'{0:0.{precision}f}{1}'.format(float(val), wind_units, precision=wind_decimal)
except ValueError:
return u'{0}'.format(val) | Format wind data for Indigo UI
Adjusts the decimal precision of certain wind values for display in control
pages, etc.
-----
:param indigo.Device dev:
:param str state_name:
:param val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | uiFormatWind | DaveL17/WUnderground7 | 0 | python | def uiFormatWind(self, dev, state_name, val):
'\n Format wind data for Indigo UI\n\n Adjusts the decimal precision of certain wind values for display in control\n pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param val:\n '
wind_decimal = int(self.pluginPrefs.get('uiWindDecimal', '1'))
wind_units = unicode(dev.pluginProps.get('windUnits', ))
try:
return u'{0:0.{precision}f}{1}'.format(float(val), wind_units, precision=wind_decimal)
except ValueError:
return u'{0}'.format(val) | def uiFormatWind(self, dev, state_name, val):
'\n Format wind data for Indigo UI\n\n Adjusts the decimal precision of certain wind values for display in control\n pages, etc.\n\n -----\n\n :param indigo.Device dev:\n :param str state_name:\n :param val:\n '
wind_decimal = int(self.pluginPrefs.get('uiWindDecimal', '1'))
wind_units = unicode(dev.pluginProps.get('windUnits', ))
try:
return u'{0:0.{precision}f}{1}'.format(float(val), wind_units, precision=wind_decimal)
except ValueError:
return u'{0}'.format(val)<|docstring|>Format wind data for Indigo UI
Adjusts the decimal precision of certain wind values for display in control
pages, etc.
-----
:param indigo.Device dev:
:param str state_name:
:param val:<|endoftext|> |
fda3c6b02256cdceb4faba21296c159245219b1699c1a5c52646c7e7431168f1 | def verboseWindNames(self, state_name, val):
'\n Format wind data for Indigo UI\n\n The verboseWindNames() method takes possible wind direction values and\n standardizes them across all device types and all reporting stations to ensure\n that we wind up with values that we can recognize.\n\n -----\n\n :param str state_name:\n :param val:\n '
wind_dict = {'N': 'north', 'North': 'north', 'NNE': 'north northeast', 'NE': 'northeast', 'ENE': 'east northeast', 'E': 'east', 'East': 'east', 'ESE': 'east southeast', 'SE': 'southeast', 'SSE': 'south southeast', 'S': 'south', 'South': 'south', 'SSW': 'south southwest', 'SW': 'southwest', 'WSW': 'west southwest', 'W': 'west', 'West': 'west', 'WNW': 'west northwest', 'NW': 'northwest', 'NNW': 'north northwest'}
try:
return wind_dict[val]
except KeyError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Error formatting {0} verbose wind names: {1}'.format(state_name, val))
return val | Format wind data for Indigo UI
The verboseWindNames() method takes possible wind direction values and
standardizes them across all device types and all reporting stations to ensure
that we wind up with values that we can recognize.
-----
:param str state_name:
:param val: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | verboseWindNames | DaveL17/WUnderground7 | 0 | python | def verboseWindNames(self, state_name, val):
'\n Format wind data for Indigo UI\n\n The verboseWindNames() method takes possible wind direction values and\n standardizes them across all device types and all reporting stations to ensure\n that we wind up with values that we can recognize.\n\n -----\n\n :param str state_name:\n :param val:\n '
wind_dict = {'N': 'north', 'North': 'north', 'NNE': 'north northeast', 'NE': 'northeast', 'ENE': 'east northeast', 'E': 'east', 'East': 'east', 'ESE': 'east southeast', 'SE': 'southeast', 'SSE': 'south southeast', 'S': 'south', 'South': 'south', 'SSW': 'south southwest', 'SW': 'southwest', 'WSW': 'west southwest', 'W': 'west', 'West': 'west', 'WNW': 'west northwest', 'NW': 'northwest', 'NNW': 'north northwest'}
try:
return wind_dict[val]
except KeyError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Error formatting {0} verbose wind names: {1}'.format(state_name, val))
return val | def verboseWindNames(self, state_name, val):
'\n Format wind data for Indigo UI\n\n The verboseWindNames() method takes possible wind direction values and\n standardizes them across all device types and all reporting stations to ensure\n that we wind up with values that we can recognize.\n\n -----\n\n :param str state_name:\n :param val:\n '
wind_dict = {'N': 'north', 'North': 'north', 'NNE': 'north northeast', 'NE': 'northeast', 'ENE': 'east northeast', 'E': 'east', 'East': 'east', 'ESE': 'east southeast', 'SE': 'southeast', 'SSE': 'south southeast', 'S': 'south', 'South': 'south', 'SSW': 'south southwest', 'SW': 'southwest', 'WSW': 'west southwest', 'W': 'west', 'West': 'west', 'WNW': 'west northwest', 'NW': 'northwest', 'NNW': 'north northwest'}
try:
return wind_dict[val]
except KeyError:
self.Fogbert.pluginErrorHandler(traceback.format_exc())
self.logger.debug(u'Error formatting {0} verbose wind names: {1}'.format(state_name, val))
return val<|docstring|>Format wind data for Indigo UI
The verboseWindNames() method takes possible wind direction values and
standardizes them across all device types and all reporting stations to ensure
that we wind up with values that we can recognize.
-----
:param str state_name:
:param val:<|endoftext|> |
de0cd890d77d9c1c3aa990497ee40bdd23dbe87ecd25aa1cf9963b831596ab11 | def wundergroundSite(self, values_dict):
'\n Launch a web browser to register for API\n\n Launch a web browser session with the values_dict parm containing the target\n URL.\n\n -----\n\n :param indigo.Dict values_dict:\n '
self.Fogbert.launchWebPage(values_dict['launchWUparameters']) | Launch a web browser to register for API
Launch a web browser session with the values_dict parm containing the target
URL.
-----
:param indigo.Dict values_dict: | Wunderground.indigoPlugin/Contents/Server Plugin/plugin.py | wundergroundSite | DaveL17/WUnderground7 | 0 | python | def wundergroundSite(self, values_dict):
'\n Launch a web browser to register for API\n\n Launch a web browser session with the values_dict parm containing the target\n URL.\n\n -----\n\n :param indigo.Dict values_dict:\n '
self.Fogbert.launchWebPage(values_dict['launchWUparameters']) | def wundergroundSite(self, values_dict):
'\n Launch a web browser to register for API\n\n Launch a web browser session with the values_dict parm containing the target\n URL.\n\n -----\n\n :param indigo.Dict values_dict:\n '
self.Fogbert.launchWebPage(values_dict['launchWUparameters'])<|docstring|>Launch a web browser to register for API
Launch a web browser session with the values_dict parm containing the target
URL.
-----
:param indigo.Dict values_dict:<|endoftext|> |
638f38d57813dd2fc023b0d854a028c6bce521fd5c7d3c5a99693aea8852a9fd | def main():
"\n\tinput each day's temperature and output maximum, minimum, average and how many cold days\n\t"
print('stanCode "Weather Master 4.0"!')
first_temperature = int(input((('Next temperature: (or ' + str(QUIT)) + ' to quit)? ')))
if (first_temperature == QUIT):
print('No temperatures were entered.')
if (first_temperature != QUIT):
if (first_temperature < 16):
cold_day = 1
else:
cold_day = 0
count = 1
total = first_temperature
maximum = first_temperature
minimum = first_temperature
while True:
temperature = int(input((('Next temperature: (or ' + str(QUIT)) + ' to quit)? ')))
if (temperature == QUIT):
break
if (temperature != QUIT):
if (temperature < 16):
cold_day += 1
if (temperature > maximum):
maximum = temperature
if (temperature < minimum):
minimum = temperature
count += 1
total += temperature
print(('Highest temperature = ' + str(maximum)))
print(('Lowest temperature = ' + str(minimum)))
print(('Average = ' + str(float((total / count)))))
print((str(cold_day) + ' cold day(s)')) | input each day's temperature and output maximum, minimum, average and how many cold days | stanCode-project/Weather_Master/weather_master.py | main | summerororo/sc-project | 0 | python | def main():
"\n\t\n\t"
print('stanCode "Weather Master 4.0"!')
first_temperature = int(input((('Next temperature: (or ' + str(QUIT)) + ' to quit)? ')))
if (first_temperature == QUIT):
print('No temperatures were entered.')
if (first_temperature != QUIT):
if (first_temperature < 16):
cold_day = 1
else:
cold_day = 0
count = 1
total = first_temperature
maximum = first_temperature
minimum = first_temperature
while True:
temperature = int(input((('Next temperature: (or ' + str(QUIT)) + ' to quit)? ')))
if (temperature == QUIT):
break
if (temperature != QUIT):
if (temperature < 16):
cold_day += 1
if (temperature > maximum):
maximum = temperature
if (temperature < minimum):
minimum = temperature
count += 1
total += temperature
print(('Highest temperature = ' + str(maximum)))
print(('Lowest temperature = ' + str(minimum)))
print(('Average = ' + str(float((total / count)))))
print((str(cold_day) + ' cold day(s)')) | def main():
"\n\t\n\t"
print('stanCode "Weather Master 4.0"!')
first_temperature = int(input((('Next temperature: (or ' + str(QUIT)) + ' to quit)? ')))
if (first_temperature == QUIT):
print('No temperatures were entered.')
if (first_temperature != QUIT):
if (first_temperature < 16):
cold_day = 1
else:
cold_day = 0
count = 1
total = first_temperature
maximum = first_temperature
minimum = first_temperature
while True:
temperature = int(input((('Next temperature: (or ' + str(QUIT)) + ' to quit)? ')))
if (temperature == QUIT):
break
if (temperature != QUIT):
if (temperature < 16):
cold_day += 1
if (temperature > maximum):
maximum = temperature
if (temperature < minimum):
minimum = temperature
count += 1
total += temperature
print(('Highest temperature = ' + str(maximum)))
print(('Lowest temperature = ' + str(minimum)))
print(('Average = ' + str(float((total / count)))))
print((str(cold_day) + ' cold day(s)'))<|docstring|>input each day's temperature and output maximum, minimum, average and how many cold days<|endoftext|> |
d24eab749e3a9ed3b4081886d5686423b2f3f3cbb64328f2ade7f09f5e28a54c | def get_graphs():
'\n Returns instances of defined graphs.\n '
g1 = NxGraph()
g1.name = 'Graph 1'
g1.add_node('A', id='A', name='Node A', category=['biolink:NamedThing'])
g1.add_node('B', id='B', name='Node B', category=['biolink:NamedThing'])
g1.add_node('C', id='C', name='Node C', category=['biolink:NamedThing'])
g1.add_edge('C', 'B', edge_key='C-biolink:subclass_of-B', edge_label='biolink:sub_class_of', relation='rdfs:subClassOf')
g1.add_edge('B', 'A', edge_key='B-biolink:subclass_of-A', edge_label='biolink:sub_class_of', relation='rdfs:subClassOf', provided_by='Graph 1')
g2 = NxGraph()
g2.name = 'Graph 2'
g2.add_node('A', id='A', name='Node A', description='Node A in Graph 2', category=['biolink:NamedThing'])
g2.add_node('B', id='B', name='Node B', description='Node B in Graph 2', category=['biolink:NamedThing'])
g2.add_node('C', id='C', name='Node C', description='Node C in Graph 2', category=['biolink:NamedThing'])
g2.add_node('D', id='D', name='Node D', description='Node D in Graph 2', category=['biolink:NamedThing'])
g2.add_node('E', id='E', name='Node E', description='Node E in Graph 2', category=['biolink:NamedThing'])
g2.add_edge('B', 'A', edge_key='B-biolink:subclass_of-A', edge_label='biolink:subclass_of', relation='rdfs:subClassOf', provided_by='Graph 2')
g2.add_edge('B', 'A', edge_key='B-biolink:related_to-A', edge_label='biolink:related_to', relation='biolink:related_to')
g2.add_edge('D', 'A', edge_key='D-biolink:related_to-A', edge_label='biolink:related_to', relation='biolink:related_to')
g2.add_edge('E', 'A', edge_key='E-biolink:related_to-A', edge_label='biolink:related_to', relation='biolink:related_to')
g3 = NxGraph()
g3.name = 'Graph 3'
g3.add_edge('F', 'E', edge_key='F-biolink:same_as-E', edge_label='biolink:same_as', relation='OWL:same_as')
return [g1, g2, g3] | Returns instances of defined graphs. | tests/unit/test_graph_merge.py | get_graphs | EvanDietzMorris/kgx | 32 | python | def get_graphs():
'\n \n '
g1 = NxGraph()
g1.name = 'Graph 1'
g1.add_node('A', id='A', name='Node A', category=['biolink:NamedThing'])
g1.add_node('B', id='B', name='Node B', category=['biolink:NamedThing'])
g1.add_node('C', id='C', name='Node C', category=['biolink:NamedThing'])
g1.add_edge('C', 'B', edge_key='C-biolink:subclass_of-B', edge_label='biolink:sub_class_of', relation='rdfs:subClassOf')
g1.add_edge('B', 'A', edge_key='B-biolink:subclass_of-A', edge_label='biolink:sub_class_of', relation='rdfs:subClassOf', provided_by='Graph 1')
g2 = NxGraph()
g2.name = 'Graph 2'
g2.add_node('A', id='A', name='Node A', description='Node A in Graph 2', category=['biolink:NamedThing'])
g2.add_node('B', id='B', name='Node B', description='Node B in Graph 2', category=['biolink:NamedThing'])
g2.add_node('C', id='C', name='Node C', description='Node C in Graph 2', category=['biolink:NamedThing'])
g2.add_node('D', id='D', name='Node D', description='Node D in Graph 2', category=['biolink:NamedThing'])
g2.add_node('E', id='E', name='Node E', description='Node E in Graph 2', category=['biolink:NamedThing'])
g2.add_edge('B', 'A', edge_key='B-biolink:subclass_of-A', edge_label='biolink:subclass_of', relation='rdfs:subClassOf', provided_by='Graph 2')
g2.add_edge('B', 'A', edge_key='B-biolink:related_to-A', edge_label='biolink:related_to', relation='biolink:related_to')
g2.add_edge('D', 'A', edge_key='D-biolink:related_to-A', edge_label='biolink:related_to', relation='biolink:related_to')
g2.add_edge('E', 'A', edge_key='E-biolink:related_to-A', edge_label='biolink:related_to', relation='biolink:related_to')
g3 = NxGraph()
g3.name = 'Graph 3'
g3.add_edge('F', 'E', edge_key='F-biolink:same_as-E', edge_label='biolink:same_as', relation='OWL:same_as')
return [g1, g2, g3] | def get_graphs():
'\n \n '
g1 = NxGraph()
g1.name = 'Graph 1'
g1.add_node('A', id='A', name='Node A', category=['biolink:NamedThing'])
g1.add_node('B', id='B', name='Node B', category=['biolink:NamedThing'])
g1.add_node('C', id='C', name='Node C', category=['biolink:NamedThing'])
g1.add_edge('C', 'B', edge_key='C-biolink:subclass_of-B', edge_label='biolink:sub_class_of', relation='rdfs:subClassOf')
g1.add_edge('B', 'A', edge_key='B-biolink:subclass_of-A', edge_label='biolink:sub_class_of', relation='rdfs:subClassOf', provided_by='Graph 1')
g2 = NxGraph()
g2.name = 'Graph 2'
g2.add_node('A', id='A', name='Node A', description='Node A in Graph 2', category=['biolink:NamedThing'])
g2.add_node('B', id='B', name='Node B', description='Node B in Graph 2', category=['biolink:NamedThing'])
g2.add_node('C', id='C', name='Node C', description='Node C in Graph 2', category=['biolink:NamedThing'])
g2.add_node('D', id='D', name='Node D', description='Node D in Graph 2', category=['biolink:NamedThing'])
g2.add_node('E', id='E', name='Node E', description='Node E in Graph 2', category=['biolink:NamedThing'])
g2.add_edge('B', 'A', edge_key='B-biolink:subclass_of-A', edge_label='biolink:subclass_of', relation='rdfs:subClassOf', provided_by='Graph 2')
g2.add_edge('B', 'A', edge_key='B-biolink:related_to-A', edge_label='biolink:related_to', relation='biolink:related_to')
g2.add_edge('D', 'A', edge_key='D-biolink:related_to-A', edge_label='biolink:related_to', relation='biolink:related_to')
g2.add_edge('E', 'A', edge_key='E-biolink:related_to-A', edge_label='biolink:related_to', relation='biolink:related_to')
g3 = NxGraph()
g3.name = 'Graph 3'
g3.add_edge('F', 'E', edge_key='F-biolink:same_as-E', edge_label='biolink:same_as', relation='OWL:same_as')
return [g1, g2, g3]<|docstring|>Returns instances of defined graphs.<|endoftext|> |
e90d14bfc90f9f17f9c788c3043b9bd4e4c23ac52c0175272abf65a86626336c | def test_merge_all_graphs():
'\n Test for merging three graphs into one,\n while preserving conflicting node and edge properties.\n '
graphs = get_graphs()
merged_graph = merge_all_graphs(graphs, preserve=True)
assert (merged_graph.number_of_nodes() == 6)
assert (merged_graph.number_of_edges() == 6)
assert (merged_graph.name == 'Graph 2')
data = merged_graph.nodes()['A']
assert (data['name'] == 'Node A')
assert (data['description'] == 'Node A in Graph 2')
edges = merged_graph.get_edge('B', 'A')
assert (len(edges) == 2)
data = list(edges.values())[0]
assert (len(data['provided_by']) == 2)
assert (data['provided_by'] == ['Graph 2', 'Graph 1'])
graphs = get_graphs()
merged_graph = merge_all_graphs(graphs, preserve=False)
assert (merged_graph.number_of_nodes() == 6)
assert (merged_graph.number_of_edges() == 6)
assert (merged_graph.name == 'Graph 2')
data = merged_graph.nodes()['A']
assert (data['name'] == 'Node A')
assert (data['description'] == 'Node A in Graph 2')
edges = merged_graph.get_edge('B', 'A')
assert (len(edges) == 2)
data = list(edges.values())[0]
assert isinstance(data['provided_by'], list)
assert ('Graph 1' in data['provided_by'])
assert ('Graph 2' in data['provided_by']) | Test for merging three graphs into one,
while preserving conflicting node and edge properties. | tests/unit/test_graph_merge.py | test_merge_all_graphs | EvanDietzMorris/kgx | 32 | python | def test_merge_all_graphs():
'\n Test for merging three graphs into one,\n while preserving conflicting node and edge properties.\n '
graphs = get_graphs()
merged_graph = merge_all_graphs(graphs, preserve=True)
assert (merged_graph.number_of_nodes() == 6)
assert (merged_graph.number_of_edges() == 6)
assert (merged_graph.name == 'Graph 2')
data = merged_graph.nodes()['A']
assert (data['name'] == 'Node A')
assert (data['description'] == 'Node A in Graph 2')
edges = merged_graph.get_edge('B', 'A')
assert (len(edges) == 2)
data = list(edges.values())[0]
assert (len(data['provided_by']) == 2)
assert (data['provided_by'] == ['Graph 2', 'Graph 1'])
graphs = get_graphs()
merged_graph = merge_all_graphs(graphs, preserve=False)
assert (merged_graph.number_of_nodes() == 6)
assert (merged_graph.number_of_edges() == 6)
assert (merged_graph.name == 'Graph 2')
data = merged_graph.nodes()['A']
assert (data['name'] == 'Node A')
assert (data['description'] == 'Node A in Graph 2')
edges = merged_graph.get_edge('B', 'A')
assert (len(edges) == 2)
data = list(edges.values())[0]
assert isinstance(data['provided_by'], list)
assert ('Graph 1' in data['provided_by'])
assert ('Graph 2' in data['provided_by']) | def test_merge_all_graphs():
'\n Test for merging three graphs into one,\n while preserving conflicting node and edge properties.\n '
graphs = get_graphs()
merged_graph = merge_all_graphs(graphs, preserve=True)
assert (merged_graph.number_of_nodes() == 6)
assert (merged_graph.number_of_edges() == 6)
assert (merged_graph.name == 'Graph 2')
data = merged_graph.nodes()['A']
assert (data['name'] == 'Node A')
assert (data['description'] == 'Node A in Graph 2')
edges = merged_graph.get_edge('B', 'A')
assert (len(edges) == 2)
data = list(edges.values())[0]
assert (len(data['provided_by']) == 2)
assert (data['provided_by'] == ['Graph 2', 'Graph 1'])
graphs = get_graphs()
merged_graph = merge_all_graphs(graphs, preserve=False)
assert (merged_graph.number_of_nodes() == 6)
assert (merged_graph.number_of_edges() == 6)
assert (merged_graph.name == 'Graph 2')
data = merged_graph.nodes()['A']
assert (data['name'] == 'Node A')
assert (data['description'] == 'Node A in Graph 2')
edges = merged_graph.get_edge('B', 'A')
assert (len(edges) == 2)
data = list(edges.values())[0]
assert isinstance(data['provided_by'], list)
assert ('Graph 1' in data['provided_by'])
assert ('Graph 2' in data['provided_by'])<|docstring|>Test for merging three graphs into one,
while preserving conflicting node and edge properties.<|endoftext|> |
7846a76d3e900828601e94e6b3b171ea7c9e490747680911cca9e337f350d5d1 | def test_merge_graphs():
'\n Test for merging 3 graphs into one,\n while not preserving conflicting node and edge properties.\n '
graphs = get_graphs()
merged_graph = merge_graphs(NxGraph(), graphs)
assert (merged_graph.number_of_nodes() == 6)
assert (merged_graph.number_of_edges() == 6)
assert (merged_graph.name not in [x.name for x in graphs]) | Test for merging 3 graphs into one,
while not preserving conflicting node and edge properties. | tests/unit/test_graph_merge.py | test_merge_graphs | EvanDietzMorris/kgx | 32 | python | def test_merge_graphs():
'\n Test for merging 3 graphs into one,\n while not preserving conflicting node and edge properties.\n '
graphs = get_graphs()
merged_graph = merge_graphs(NxGraph(), graphs)
assert (merged_graph.number_of_nodes() == 6)
assert (merged_graph.number_of_edges() == 6)
assert (merged_graph.name not in [x.name for x in graphs]) | def test_merge_graphs():
'\n Test for merging 3 graphs into one,\n while not preserving conflicting node and edge properties.\n '
graphs = get_graphs()
merged_graph = merge_graphs(NxGraph(), graphs)
assert (merged_graph.number_of_nodes() == 6)
assert (merged_graph.number_of_edges() == 6)
assert (merged_graph.name not in [x.name for x in graphs])<|docstring|>Test for merging 3 graphs into one,
while not preserving conflicting node and edge properties.<|endoftext|> |
3230935f94a7718845ce56514ce8590877f8152e8e0fe863756c7fed3500f070 | def test_merge_node():
'\n Test merging of a node into a graph.\n '
graphs = get_graphs()
g = graphs[0]
node = g.nodes()['A']
new_data = node.copy()
new_data['subset'] = 'test'
new_data['source'] = 'KGX'
new_data['category'] = ['biolink:InformationContentEntity']
new_data['description'] = 'Node A modified by merge operation'
node = merge_node(g, node['id'], new_data, preserve=True)
assert (node['id'] == 'A')
assert (node['name'] == 'Node A')
assert (node['description'] == 'Node A modified by merge operation')
assert (('subset' in node) and (node['subset'] == 'test'))
assert (('source' in node) and (node['source'] == 'KGX')) | Test merging of a node into a graph. | tests/unit/test_graph_merge.py | test_merge_node | EvanDietzMorris/kgx | 32 | python | def test_merge_node():
'\n \n '
graphs = get_graphs()
g = graphs[0]
node = g.nodes()['A']
new_data = node.copy()
new_data['subset'] = 'test'
new_data['source'] = 'KGX'
new_data['category'] = ['biolink:InformationContentEntity']
new_data['description'] = 'Node A modified by merge operation'
node = merge_node(g, node['id'], new_data, preserve=True)
assert (node['id'] == 'A')
assert (node['name'] == 'Node A')
assert (node['description'] == 'Node A modified by merge operation')
assert (('subset' in node) and (node['subset'] == 'test'))
assert (('source' in node) and (node['source'] == 'KGX')) | def test_merge_node():
'\n \n '
graphs = get_graphs()
g = graphs[0]
node = g.nodes()['A']
new_data = node.copy()
new_data['subset'] = 'test'
new_data['source'] = 'KGX'
new_data['category'] = ['biolink:InformationContentEntity']
new_data['description'] = 'Node A modified by merge operation'
node = merge_node(g, node['id'], new_data, preserve=True)
assert (node['id'] == 'A')
assert (node['name'] == 'Node A')
assert (node['description'] == 'Node A modified by merge operation')
assert (('subset' in node) and (node['subset'] == 'test'))
assert (('source' in node) and (node['source'] == 'KGX'))<|docstring|>Test merging of a node into a graph.<|endoftext|> |
e6c6789af78e0f70f21175a44ccb634d84c216dc27417dfff8d0a308461776cc | def test_merge_edge():
'\n Test merging of an edge into a graph.\n '
graphs = get_graphs()
g = graphs[1]
edge = g.get_edge('E', 'A')
new_data = edge.copy()
new_data['provided_by'] = 'KGX'
new_data['evidence'] = 'PMID:123456'
edge = merge_edge(g, 'E', 'A', 'E-biolink:related_to-A', new_data, preserve=True)
assert (edge['edge_label'] == 'biolink:related_to')
assert (edge['relation'] == 'biolink:related_to')
assert ('KGX' in edge['provided_by'])
assert (edge['evidence'] == 'PMID:123456') | Test merging of an edge into a graph. | tests/unit/test_graph_merge.py | test_merge_edge | EvanDietzMorris/kgx | 32 | python | def test_merge_edge():
'\n \n '
graphs = get_graphs()
g = graphs[1]
edge = g.get_edge('E', 'A')
new_data = edge.copy()
new_data['provided_by'] = 'KGX'
new_data['evidence'] = 'PMID:123456'
edge = merge_edge(g, 'E', 'A', 'E-biolink:related_to-A', new_data, preserve=True)
assert (edge['edge_label'] == 'biolink:related_to')
assert (edge['relation'] == 'biolink:related_to')
assert ('KGX' in edge['provided_by'])
assert (edge['evidence'] == 'PMID:123456') | def test_merge_edge():
'\n \n '
graphs = get_graphs()
g = graphs[1]
edge = g.get_edge('E', 'A')
new_data = edge.copy()
new_data['provided_by'] = 'KGX'
new_data['evidence'] = 'PMID:123456'
edge = merge_edge(g, 'E', 'A', 'E-biolink:related_to-A', new_data, preserve=True)
assert (edge['edge_label'] == 'biolink:related_to')
assert (edge['relation'] == 'biolink:related_to')
assert ('KGX' in edge['provided_by'])
assert (edge['evidence'] == 'PMID:123456')<|docstring|>Test merging of an edge into a graph.<|endoftext|> |
33751879aafc502e709bab1fd09f5b021317733b1d7d0fe8c780f809eb9218e4 | def recursive_list_dir(root_dir):
'Yields all files of a root directory tree.'
for (dirname, _, filenames) in tf.io.gfile.walk(root_dir):
for filename in filenames:
(yield os.path.join(dirname, filename)) | Yields all files of a root directory tree. | tools/filesystem_utils.py | recursive_list_dir | edrone/tfhub.dev | 2 | python | def recursive_list_dir(root_dir):
for (dirname, _, filenames) in tf.io.gfile.walk(root_dir):
for filename in filenames:
(yield os.path.join(dirname, filename)) | def recursive_list_dir(root_dir):
for (dirname, _, filenames) in tf.io.gfile.walk(root_dir):
for filename in filenames:
(yield os.path.join(dirname, filename))<|docstring|>Yields all files of a root directory tree.<|endoftext|> |
d1957181004ad689858d11f42ae139573dc426b5401cc52f4ee864ba85a3664f | def get_content(file_path):
"Returns a file's content."
with tf.io.gfile.GFile(file_path, 'r') as f:
return f.read() | Returns a file's content. | tools/filesystem_utils.py | get_content | edrone/tfhub.dev | 2 | python | def get_content(file_path):
with tf.io.gfile.GFile(file_path, 'r') as f:
return f.read() | def get_content(file_path):
with tf.io.gfile.GFile(file_path, 'r') as f:
return f.read()<|docstring|>Returns a file's content.<|endoftext|> |
b0799e9f988125f6903eac6944f191b398799f9e917763073e1f27509471bf76 | def test_controls(self, elevator=0, aileron=0, tla=0) -> None:
'\n Directly control the aircraft using control surfaces for the purpose of testing the model\n\n :param elevator: elevator angle [-30 to +30]\n :param aileron: aileron angle [-30 to +30]\n :param tla: Thrust Lever Angle [0 to 1]\n :return: None\n '
self.sim[prp.elevator_cmd] = elevator
self.sim[prp.aileron_cmd] = aileron
self.sim[prp.throttle_cmd] = tla | Directly control the aircraft using control surfaces for the purpose of testing the model
:param elevator: elevator angle [-30 to +30]
:param aileron: aileron angle [-30 to +30]
:param tla: Thrust Lever Angle [0 to 1]
:return: None | src/autopilot.py | test_controls | nkbeebe/FW-Airsim | 16 | python | def test_controls(self, elevator=0, aileron=0, tla=0) -> None:
'\n Directly control the aircraft using control surfaces for the purpose of testing the model\n\n :param elevator: elevator angle [-30 to +30]\n :param aileron: aileron angle [-30 to +30]\n :param tla: Thrust Lever Angle [0 to 1]\n :return: None\n '
self.sim[prp.elevator_cmd] = elevator
self.sim[prp.aileron_cmd] = aileron
self.sim[prp.throttle_cmd] = tla | def test_controls(self, elevator=0, aileron=0, tla=0) -> None:
'\n Directly control the aircraft using control surfaces for the purpose of testing the model\n\n :param elevator: elevator angle [-30 to +30]\n :param aileron: aileron angle [-30 to +30]\n :param tla: Thrust Lever Angle [0 to 1]\n :return: None\n '
self.sim[prp.elevator_cmd] = elevator
self.sim[prp.aileron_cmd] = aileron
self.sim[prp.throttle_cmd] = tla<|docstring|>Directly control the aircraft using control surfaces for the purpose of testing the model
:param elevator: elevator angle [-30 to +30]
:param aileron: aileron angle [-30 to +30]
:param tla: Thrust Lever Angle [0 to 1]
:return: None<|endoftext|> |
2e4395e4ac0d28aa393b7d9b0451c7144e56bf677146e31fb0e704baa75d5719 | def pitch_hold(self, pitch_comm: float) -> None:
'\n Maintains a commanded pitch attitude [radians] using a PI controller with a rate component\n\n :param pitch_comm: commanded pitch attitude [radians]\n :return: None\n '
error = (pitch_comm - self.sim[prp.pitch_rad])
kp = 1.0
ki = 0.0
kd = 0.03
controller = PID(kp, ki, 0.0)
output = controller(error)
rate = self.sim[prp.q_radps]
rate_controller = PID(kd, 0.0, 0.0)
rate_output = rate_controller(rate)
output = (output + rate_output)
self.sim[prp.elevator_cmd] = output | Maintains a commanded pitch attitude [radians] using a PI controller with a rate component
:param pitch_comm: commanded pitch attitude [radians]
:return: None | src/autopilot.py | pitch_hold | nkbeebe/FW-Airsim | 16 | python | def pitch_hold(self, pitch_comm: float) -> None:
'\n Maintains a commanded pitch attitude [radians] using a PI controller with a rate component\n\n :param pitch_comm: commanded pitch attitude [radians]\n :return: None\n '
error = (pitch_comm - self.sim[prp.pitch_rad])
kp = 1.0
ki = 0.0
kd = 0.03
controller = PID(kp, ki, 0.0)
output = controller(error)
rate = self.sim[prp.q_radps]
rate_controller = PID(kd, 0.0, 0.0)
rate_output = rate_controller(rate)
output = (output + rate_output)
self.sim[prp.elevator_cmd] = output | def pitch_hold(self, pitch_comm: float) -> None:
'\n Maintains a commanded pitch attitude [radians] using a PI controller with a rate component\n\n :param pitch_comm: commanded pitch attitude [radians]\n :return: None\n '
error = (pitch_comm - self.sim[prp.pitch_rad])
kp = 1.0
ki = 0.0
kd = 0.03
controller = PID(kp, ki, 0.0)
output = controller(error)
rate = self.sim[prp.q_radps]
rate_controller = PID(kd, 0.0, 0.0)
rate_output = rate_controller(rate)
output = (output + rate_output)
self.sim[prp.elevator_cmd] = output<|docstring|>Maintains a commanded pitch attitude [radians] using a PI controller with a rate component
:param pitch_comm: commanded pitch attitude [radians]
:return: None<|endoftext|> |
95d295acc294276ef86a09f49052f5f7485d3b2162c0d1dc5db01111b6504b8e | def roll_hold(self, roll_comm: float) -> None:
'\n Maintains a commanded roll attitude [radians] using a PID controller\n\n :param roll_comm: commanded roll attitude [radians]\n :return: None\n '
error = (roll_comm - self.sim[prp.roll_rad])
kp = 0.2
ki = (kp * 0.0)
kd = 0.089
controller = PID(kp, ki, 0.0)
output = controller(error)
rate = self.sim[prp.p_radps]
rate_controller = PID(kd, 0.0, 0.0)
rate_output = rate_controller(rate)
output = ((- output) + rate_output)
self.sim[prp.aileron_cmd] = output | Maintains a commanded roll attitude [radians] using a PID controller
:param roll_comm: commanded roll attitude [radians]
:return: None | src/autopilot.py | roll_hold | nkbeebe/FW-Airsim | 16 | python | def roll_hold(self, roll_comm: float) -> None:
'\n Maintains a commanded roll attitude [radians] using a PID controller\n\n :param roll_comm: commanded roll attitude [radians]\n :return: None\n '
error = (roll_comm - self.sim[prp.roll_rad])
kp = 0.2
ki = (kp * 0.0)
kd = 0.089
controller = PID(kp, ki, 0.0)
output = controller(error)
rate = self.sim[prp.p_radps]
rate_controller = PID(kd, 0.0, 0.0)
rate_output = rate_controller(rate)
output = ((- output) + rate_output)
self.sim[prp.aileron_cmd] = output | def roll_hold(self, roll_comm: float) -> None:
'\n Maintains a commanded roll attitude [radians] using a PID controller\n\n :param roll_comm: commanded roll attitude [radians]\n :return: None\n '
error = (roll_comm - self.sim[prp.roll_rad])
kp = 0.2
ki = (kp * 0.0)
kd = 0.089
controller = PID(kp, ki, 0.0)
output = controller(error)
rate = self.sim[prp.p_radps]
rate_controller = PID(kd, 0.0, 0.0)
rate_output = rate_controller(rate)
output = ((- output) + rate_output)
self.sim[prp.aileron_cmd] = output<|docstring|>Maintains a commanded roll attitude [radians] using a PID controller
:param roll_comm: commanded roll attitude [radians]
:return: None<|endoftext|> |
e8433a3a1ed4b01af6a3e3bdc86938363c29276911c41379143847248b3a5686 | def heading_hold(self, heading_comm: float) -> None:
'\n Maintains a commanded heading [degrees] using a PI controller\n\n :param heading_comm: commanded heading [degrees]\n :return: None\n '
error = (heading_comm - self.sim[prp.heading_deg])
if (error < (- 180)):
error = (error + 360)
if (error > 180):
error = (error - 360)
kp = ((- 2.0023) * 0.005)
ki = ((- 0.6382) * 0.005)
heading_controller = PID(kp, ki, 0.0)
output = heading_controller(error)
if (output < ((- 30) * (math.pi / 180))):
output = ((- 30) * (math.pi / 180))
if (output > (30 * (math.pi / 180))):
output = (30 * (math.pi / 180))
self.roll_hold(output) | Maintains a commanded heading [degrees] using a PI controller
:param heading_comm: commanded heading [degrees]
:return: None | src/autopilot.py | heading_hold | nkbeebe/FW-Airsim | 16 | python | def heading_hold(self, heading_comm: float) -> None:
'\n Maintains a commanded heading [degrees] using a PI controller\n\n :param heading_comm: commanded heading [degrees]\n :return: None\n '
error = (heading_comm - self.sim[prp.heading_deg])
if (error < (- 180)):
error = (error + 360)
if (error > 180):
error = (error - 360)
kp = ((- 2.0023) * 0.005)
ki = ((- 0.6382) * 0.005)
heading_controller = PID(kp, ki, 0.0)
output = heading_controller(error)
if (output < ((- 30) * (math.pi / 180))):
output = ((- 30) * (math.pi / 180))
if (output > (30 * (math.pi / 180))):
output = (30 * (math.pi / 180))
self.roll_hold(output) | def heading_hold(self, heading_comm: float) -> None:
'\n Maintains a commanded heading [degrees] using a PI controller\n\n :param heading_comm: commanded heading [degrees]\n :return: None\n '
error = (heading_comm - self.sim[prp.heading_deg])
if (error < (- 180)):
error = (error + 360)
if (error > 180):
error = (error - 360)
kp = ((- 2.0023) * 0.005)
ki = ((- 0.6382) * 0.005)
heading_controller = PID(kp, ki, 0.0)
output = heading_controller(error)
if (output < ((- 30) * (math.pi / 180))):
output = ((- 30) * (math.pi / 180))
if (output > (30 * (math.pi / 180))):
output = (30 * (math.pi / 180))
self.roll_hold(output)<|docstring|>Maintains a commanded heading [degrees] using a PI controller
:param heading_comm: commanded heading [degrees]
:return: None<|endoftext|> |
0a08674e6c06d563ad9ca317ce10c8c7ea652fb3561b962a365abf2054c54f09 | def airspeed_hold_w_throttle(self, airspeed_comm: float) -> None:
'\n Maintains a commanded airspeed [KTAS] using throttle_cmd and a PI controller\n\n :param airspeed_comm: commanded airspeed [KTAS]\n :return: None\n '
error = (airspeed_comm - (self.sim[prp.airspeed] * 0.5925))
kp = 1.0
ki = 0.035
airspeed_controller = PID(kp, ki, 0.0)
output = airspeed_controller((- error))
if (output > 1):
output = 1
if (output < 0):
output = 0
self.sim[prp.throttle_cmd] = output | Maintains a commanded airspeed [KTAS] using throttle_cmd and a PI controller
:param airspeed_comm: commanded airspeed [KTAS]
:return: None | src/autopilot.py | airspeed_hold_w_throttle | nkbeebe/FW-Airsim | 16 | python | def airspeed_hold_w_throttle(self, airspeed_comm: float) -> None:
'\n Maintains a commanded airspeed [KTAS] using throttle_cmd and a PI controller\n\n :param airspeed_comm: commanded airspeed [KTAS]\n :return: None\n '
error = (airspeed_comm - (self.sim[prp.airspeed] * 0.5925))
kp = 1.0
ki = 0.035
airspeed_controller = PID(kp, ki, 0.0)
output = airspeed_controller((- error))
if (output > 1):
output = 1
if (output < 0):
output = 0
self.sim[prp.throttle_cmd] = output | def airspeed_hold_w_throttle(self, airspeed_comm: float) -> None:
'\n Maintains a commanded airspeed [KTAS] using throttle_cmd and a PI controller\n\n :param airspeed_comm: commanded airspeed [KTAS]\n :return: None\n '
error = (airspeed_comm - (self.sim[prp.airspeed] * 0.5925))
kp = 1.0
ki = 0.035
airspeed_controller = PID(kp, ki, 0.0)
output = airspeed_controller((- error))
if (output > 1):
output = 1
if (output < 0):
output = 0
self.sim[prp.throttle_cmd] = output<|docstring|>Maintains a commanded airspeed [KTAS] using throttle_cmd and a PI controller
:param airspeed_comm: commanded airspeed [KTAS]
:return: None<|endoftext|> |
9de472f5bbfa0fc9b286c812d05a3b0a4455055e6d55240875b8d64dba58eddf | def altitude_hold(self, altitude_comm) -> None:
'\n Maintains a demanded altitude [feet] using pitch attitude\n\n :param altitude_comm: demanded altitude [feet]\n :return: None\n '
error = (altitude_comm - self.sim[prp.altitude_sl_ft])
kp = 0.1
ki = 0.6
altitude_controller = PID(kp, ki, 0)
output = altitude_controller((- error))
if (output < ((- 10) * (math.pi / 180))):
output = ((- 10) * (math.pi / 180))
if (output > (15 * (math.pi / 180))):
output = (15 * (math.pi / 180))
self.pitch_hold(output) | Maintains a demanded altitude [feet] using pitch attitude
:param altitude_comm: demanded altitude [feet]
:return: None | src/autopilot.py | altitude_hold | nkbeebe/FW-Airsim | 16 | python | def altitude_hold(self, altitude_comm) -> None:
'\n Maintains a demanded altitude [feet] using pitch attitude\n\n :param altitude_comm: demanded altitude [feet]\n :return: None\n '
error = (altitude_comm - self.sim[prp.altitude_sl_ft])
kp = 0.1
ki = 0.6
altitude_controller = PID(kp, ki, 0)
output = altitude_controller((- error))
if (output < ((- 10) * (math.pi / 180))):
output = ((- 10) * (math.pi / 180))
if (output > (15 * (math.pi / 180))):
output = (15 * (math.pi / 180))
self.pitch_hold(output) | def altitude_hold(self, altitude_comm) -> None:
'\n Maintains a demanded altitude [feet] using pitch attitude\n\n :param altitude_comm: demanded altitude [feet]\n :return: None\n '
error = (altitude_comm - self.sim[prp.altitude_sl_ft])
kp = 0.1
ki = 0.6
altitude_controller = PID(kp, ki, 0)
output = altitude_controller((- error))
if (output < ((- 10) * (math.pi / 180))):
output = ((- 10) * (math.pi / 180))
if (output > (15 * (math.pi / 180))):
output = (15 * (math.pi / 180))
self.pitch_hold(output)<|docstring|>Maintains a demanded altitude [feet] using pitch attitude
:param altitude_comm: demanded altitude [feet]
:return: None<|endoftext|> |
ff352ce535db160e1be3c8bebdf8ab9f08467498758a13158b95b31c5c81608d | def home_to_target(self, target_northing: float, target_easting: float, target_alt: float) -> bool:
'\n Homes towards a 2D (lat, long) point in space and uses altitude_hold to maintain an altitude\n\n :param target_northing: latitude of target relative to current position [m]\n :param target_easting: longitude of target relative to current position [m]\n :param target_alt: demanded altitude for this path segment [feet]\n :return: flag==True if the simulation has reached a target in space\n '
if (self.nav is None):
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target(target_northing, target_easting)
self.flag = False
if (self.nav is not None):
if (not self.flag):
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
if (distance < 100):
self.flag = True
self.nav = None
return self.flag
self.heading_hold(bearing)
self.altitude_hold(target_alt) | Homes towards a 2D (lat, long) point in space and uses altitude_hold to maintain an altitude
:param target_northing: latitude of target relative to current position [m]
:param target_easting: longitude of target relative to current position [m]
:param target_alt: demanded altitude for this path segment [feet]
:return: flag==True if the simulation has reached a target in space | src/autopilot.py | home_to_target | nkbeebe/FW-Airsim | 16 | python | def home_to_target(self, target_northing: float, target_easting: float, target_alt: float) -> bool:
'\n Homes towards a 2D (lat, long) point in space and uses altitude_hold to maintain an altitude\n\n :param target_northing: latitude of target relative to current position [m]\n :param target_easting: longitude of target relative to current position [m]\n :param target_alt: demanded altitude for this path segment [feet]\n :return: flag==True if the simulation has reached a target in space\n '
if (self.nav is None):
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target(target_northing, target_easting)
self.flag = False
if (self.nav is not None):
if (not self.flag):
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
if (distance < 100):
self.flag = True
self.nav = None
return self.flag
self.heading_hold(bearing)
self.altitude_hold(target_alt) | def home_to_target(self, target_northing: float, target_easting: float, target_alt: float) -> bool:
'\n Homes towards a 2D (lat, long) point in space and uses altitude_hold to maintain an altitude\n\n :param target_northing: latitude of target relative to current position [m]\n :param target_easting: longitude of target relative to current position [m]\n :param target_alt: demanded altitude for this path segment [feet]\n :return: flag==True if the simulation has reached a target in space\n '
if (self.nav is None):
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target(target_northing, target_easting)
self.flag = False
if (self.nav is not None):
if (not self.flag):
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
if (distance < 100):
self.flag = True
self.nav = None
return self.flag
self.heading_hold(bearing)
self.altitude_hold(target_alt)<|docstring|>Homes towards a 2D (lat, long) point in space and uses altitude_hold to maintain an altitude
:param target_northing: latitude of target relative to current position [m]
:param target_easting: longitude of target relative to current position [m]
:param target_alt: demanded altitude for this path segment [feet]
:return: flag==True if the simulation has reached a target in space<|endoftext|> |
9ea8f6beb643fdf8efb5a63b171e6b9e122aed0e6a8def69cb434d6fe96d62d4 | def track_to_target(self, target_northing: float, target_easting: float, target_alt: float) -> bool:
'\n Maintains a track from the point the simulation started at to the target point\n\n ...\n\n This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to\n re-establish the track to the pre-defined target point in space. The method terminates when the aircraft arrives\n at a point within 200m of the target point.\n :param target_northing: latitude of target relative to current position [m]\n :param target_easting: longitude of target relative to current position [m]\n :param target_alt: demanded altitude for this path segment [feet]\n :return: flag==True if the simulation has reached the target\n '
if (self.nav is None):
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target(target_northing, target_easting)
self.track_bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing < 0):
self.track_bearing = (self.track_bearing + 360.0)
self.track_distance = self.nav.distance()
self.flag = False
if (self.nav is not None):
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
off_tk_angle = (self.track_bearing - bearing)
distance_to_go = self.nav.distance_to_go(distance, off_tk_angle)
error = (off_tk_angle * distance_to_go)
kp = 0.01
ki = 0.0
kd = 0.0
closure_controller = PID(kp, ki, kd)
heading = (closure_controller((- error)) + bearing)
if (distance < 200):
self.flag = True
self.nav = None
return self.flag
self.heading_hold(heading)
self.altitude_hold(target_alt) | Maintains a track from the point the simulation started at to the target point
...
This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to
re-establish the track to the pre-defined target point in space. The method terminates when the aircraft arrives
at a point within 200m of the target point.
:param target_northing: latitude of target relative to current position [m]
:param target_easting: longitude of target relative to current position [m]
:param target_alt: demanded altitude for this path segment [feet]
:return: flag==True if the simulation has reached the target | src/autopilot.py | track_to_target | nkbeebe/FW-Airsim | 16 | python | def track_to_target(self, target_northing: float, target_easting: float, target_alt: float) -> bool:
'\n Maintains a track from the point the simulation started at to the target point\n\n ...\n\n This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to\n re-establish the track to the pre-defined target point in space. The method terminates when the aircraft arrives\n at a point within 200m of the target point.\n :param target_northing: latitude of target relative to current position [m]\n :param target_easting: longitude of target relative to current position [m]\n :param target_alt: demanded altitude for this path segment [feet]\n :return: flag==True if the simulation has reached the target\n '
if (self.nav is None):
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target(target_northing, target_easting)
self.track_bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing < 0):
self.track_bearing = (self.track_bearing + 360.0)
self.track_distance = self.nav.distance()
self.flag = False
if (self.nav is not None):
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
off_tk_angle = (self.track_bearing - bearing)
distance_to_go = self.nav.distance_to_go(distance, off_tk_angle)
error = (off_tk_angle * distance_to_go)
kp = 0.01
ki = 0.0
kd = 0.0
closure_controller = PID(kp, ki, kd)
heading = (closure_controller((- error)) + bearing)
if (distance < 200):
self.flag = True
self.nav = None
return self.flag
self.heading_hold(heading)
self.altitude_hold(target_alt) | def track_to_target(self, target_northing: float, target_easting: float, target_alt: float) -> bool:
'\n Maintains a track from the point the simulation started at to the target point\n\n ...\n\n This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to\n re-establish the track to the pre-defined target point in space. The method terminates when the aircraft arrives\n at a point within 200m of the target point.\n :param target_northing: latitude of target relative to current position [m]\n :param target_easting: longitude of target relative to current position [m]\n :param target_alt: demanded altitude for this path segment [feet]\n :return: flag==True if the simulation has reached the target\n '
if (self.nav is None):
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target(target_northing, target_easting)
self.track_bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing < 0):
self.track_bearing = (self.track_bearing + 360.0)
self.track_distance = self.nav.distance()
self.flag = False
if (self.nav is not None):
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
off_tk_angle = (self.track_bearing - bearing)
distance_to_go = self.nav.distance_to_go(distance, off_tk_angle)
error = (off_tk_angle * distance_to_go)
kp = 0.01
ki = 0.0
kd = 0.0
closure_controller = PID(kp, ki, kd)
heading = (closure_controller((- error)) + bearing)
if (distance < 200):
self.flag = True
self.nav = None
return self.flag
self.heading_hold(heading)
self.altitude_hold(target_alt)<|docstring|>Maintains a track from the point the simulation started at to the target point
...
This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to
re-establish the track to the pre-defined target point in space. The method terminates when the aircraft arrives
at a point within 200m of the target point.
:param target_northing: latitude of target relative to current position [m]
:param target_easting: longitude of target relative to current position [m]
:param target_alt: demanded altitude for this path segment [feet]
:return: flag==True if the simulation has reached the target<|endoftext|> |
fa3c18cbed56e7f68c433a86b19c9eb818b8ff55573ebf65c42a9a9e44ab737f | def track_to_profile(self, profile: list) -> bool:
'\n Maintains a track along a series of points in the simulation and the defined altitude along each path segment\n\n ...\n\n This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to\n re-establish the track to the pre-defined target point in space. The method switches to the next target point\n when the aircraft arrives at a point within 300m of the current target point. The method terminates when the\n final point(:tuple) in the profile(:list) is reached.\n :param profile: series of points used to define a path formatted with a tuple at each index of the list\n [latitude, longitude, altitude]\n :return: flag==True if the simulation has reached the final target\n '
if (self.nav is None):
self.track_id = (self.track_id + 1)
if (self.track_id == (len(profile) - 1)):
print('hit flag')
self.flag = True
return self.flag
point_a = profile[self.track_id]
point_b = profile[(self.track_id + 1)]
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target((point_b[0] - point_a[0]), (point_b[1] - point_a[1]))
self.track_bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing < 0):
self.track_bearing = (self.track_bearing + 360.0)
self.track_distance = self.nav.distance()
self.flag = False
if (self.nav is not None):
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
off_tk_angle = (bearing - self.track_bearing)
if (off_tk_angle > 180):
off_tk_angle = (off_tk_angle - 360.0)
distance_to_go = self.nav.distance_to_go(distance, off_tk_angle)
if (distance_to_go > 3000):
distance_to_go = 3000
heading = ((((8 * 0.00033) * distance_to_go) * off_tk_angle) + self.track_bearing)
radius = 300
self.heading_hold(heading)
self.altitude_hold(self.track_id[2])
if (distance < radius):
self.nav = None | Maintains a track along a series of points in the simulation and the defined altitude along each path segment
...
This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to
re-establish the track to the pre-defined target point in space. The method switches to the next target point
when the aircraft arrives at a point within 300m of the current target point. The method terminates when the
final point(:tuple) in the profile(:list) is reached.
:param profile: series of points used to define a path formatted with a tuple at each index of the list
[latitude, longitude, altitude]
:return: flag==True if the simulation has reached the final target | src/autopilot.py | track_to_profile | nkbeebe/FW-Airsim | 16 | python | def track_to_profile(self, profile: list) -> bool:
'\n Maintains a track along a series of points in the simulation and the defined altitude along each path segment\n\n ...\n\n This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to\n re-establish the track to the pre-defined target point in space. The method switches to the next target point\n when the aircraft arrives at a point within 300m of the current target point. The method terminates when the\n final point(:tuple) in the profile(:list) is reached.\n :param profile: series of points used to define a path formatted with a tuple at each index of the list\n [latitude, longitude, altitude]\n :return: flag==True if the simulation has reached the final target\n '
if (self.nav is None):
self.track_id = (self.track_id + 1)
if (self.track_id == (len(profile) - 1)):
print('hit flag')
self.flag = True
return self.flag
point_a = profile[self.track_id]
point_b = profile[(self.track_id + 1)]
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target((point_b[0] - point_a[0]), (point_b[1] - point_a[1]))
self.track_bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing < 0):
self.track_bearing = (self.track_bearing + 360.0)
self.track_distance = self.nav.distance()
self.flag = False
if (self.nav is not None):
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
off_tk_angle = (bearing - self.track_bearing)
if (off_tk_angle > 180):
off_tk_angle = (off_tk_angle - 360.0)
distance_to_go = self.nav.distance_to_go(distance, off_tk_angle)
if (distance_to_go > 3000):
distance_to_go = 3000
heading = ((((8 * 0.00033) * distance_to_go) * off_tk_angle) + self.track_bearing)
radius = 300
self.heading_hold(heading)
self.altitude_hold(self.track_id[2])
if (distance < radius):
self.nav = None | def track_to_profile(self, profile: list) -> bool:
'\n Maintains a track along a series of points in the simulation and the defined altitude along each path segment\n\n ...\n\n This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to\n re-establish the track to the pre-defined target point in space. The method switches to the next target point\n when the aircraft arrives at a point within 300m of the current target point. The method terminates when the\n final point(:tuple) in the profile(:list) is reached.\n :param profile: series of points used to define a path formatted with a tuple at each index of the list\n [latitude, longitude, altitude]\n :return: flag==True if the simulation has reached the final target\n '
if (self.nav is None):
self.track_id = (self.track_id + 1)
if (self.track_id == (len(profile) - 1)):
print('hit flag')
self.flag = True
return self.flag
point_a = profile[self.track_id]
point_b = profile[(self.track_id + 1)]
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target((point_b[0] - point_a[0]), (point_b[1] - point_a[1]))
self.track_bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing < 0):
self.track_bearing = (self.track_bearing + 360.0)
self.track_distance = self.nav.distance()
self.flag = False
if (self.nav is not None):
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
off_tk_angle = (bearing - self.track_bearing)
if (off_tk_angle > 180):
off_tk_angle = (off_tk_angle - 360.0)
distance_to_go = self.nav.distance_to_go(distance, off_tk_angle)
if (distance_to_go > 3000):
distance_to_go = 3000
heading = ((((8 * 0.00033) * distance_to_go) * off_tk_angle) + self.track_bearing)
radius = 300
self.heading_hold(heading)
self.altitude_hold(self.track_id[2])
if (distance < radius):
self.nav = None<|docstring|>Maintains a track along a series of points in the simulation and the defined altitude along each path segment
...
This ensures the aircraft does not fly a curved homing path if displaced from track but instead aims to
re-establish the track to the pre-defined target point in space. The method switches to the next target point
when the aircraft arrives at a point within 300m of the current target point. The method terminates when the
final point(:tuple) in the profile(:list) is reached.
:param profile: series of points used to define a path formatted with a tuple at each index of the list
[latitude, longitude, altitude]
:return: flag==True if the simulation has reached the final target<|endoftext|> |
968f9f5b550bca636b16eedbd7c0bb66fbc732ab79043bfd01fd749caf601292 | def arc_path(self, profile, radius) -> bool:
"\n Maintains a track along a series of points in the simulation and the defined altitude along each path segment,\n ensures a smooth turn by flying an arc/filet with radius=radius at each point\n\n ...\n\n The aircraft maintains a track based on the bearing from the location the target was instantiated to the target.\n When within a radius or crossing a plane perpendicular to track the aircraft goes from straight track mode to\n flying a curved path of radius r around a point perpendicular to the point created by the confluence of the two\n tracks. The method switches to the next point when it reaches a point equidistant from the beginning of the arc.\n The method terminates when there is no further 'b' or 'c' points available i.e. 2 points before the final track.\n The method is based off the algorithm defined in Beard & McLain chapter 11, path planning:\n http://uavbook.byu.edu/doku.php\n :param profile: series of points used to define a path formatted with a tuple at each index of the list\n [latitude, longitude, altitude]\n :param radius: fillet radial distance [m], used to calculate z point\n :return: flag==True if the simulation has reached the termination condition\n "
if (self.nav is None):
print('Changing points !!!')
self.track_id = (self.track_id + 1)
print(self.track_id)
if (self.track_id == (len(profile) - 2)):
print('hit flag')
self.flag = True
return self.flag
point_a = profile[self.track_id]
point_b = profile[(self.track_id + 1)]
point_c = profile[(self.track_id + 2)]
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target((point_c[0] - point_b[0]), (point_c[1] - point_b[1]))
self.track_bearing_out = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing_out < 0):
self.track_bearing_out = (self.track_bearing_out + 360.0)
self.nav.local_target_set = False
self.nav.set_local_target((point_b[0] - point_a[0]), (point_b[1] - point_a[1]))
self.track_bearing_in = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing_in < 0):
self.track_bearing_in = (self.track_bearing_in + 360.0)
self.flag = False
if (self.nav is not None):
filet_angle = (self.track_bearing_out - self.track_bearing_in)
if (filet_angle < 0):
filet_angle = (filet_angle + 360)
if (self.state == 0):
q = self.nav.unit_dir_vector(profile[self.track_id], profile[(self.track_id + 1)])
w = profile[(self.track_id + 1)]
try:
z_point = ((w[0] - ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q[0])), (w[1] - ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q[1])))
cur = self.nav.get_local_pos()
h_point = ((cur[0] - z_point[0]), (cur[1] - z_point[1]))
h_val = ((h_point[0] * q[0]) + (h_point[1] * q[1]))
if (h_val > 0):
self.state = 1
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
off_tk_angle = (bearing - self.track_bearing_in)
if (off_tk_angle > 180):
off_tk_angle = (off_tk_angle - 360.0)
distance_to_go = self.nav.distance_to_go(distance, off_tk_angle)
if (distance_to_go > 3000):
distance_to_go = 3000
heading = ((((8 * 0.00033) * distance_to_go) * off_tk_angle) + self.track_bearing_in)
except ZeroDivisionError:
heading = self.track_bearing_in
print("You have straight lines don't do this!")
self.heading_hold(heading)
self.altitude_hold(altitude_comm=w[2])
if (self.state == 1):
q0 = self.nav.unit_dir_vector(profile[self.track_id], profile[(self.track_id + 1)])
q1 = self.nav.unit_dir_vector(profile[(self.track_id + 1)], profile[(self.track_id + 2)])
q_grad = self.nav.unit_dir_vector(q1, q0)
w = profile[(self.track_id + 1)]
center_point = ((w[0] - ((radius / math.sin(((filet_angle / 2) * (math.pi / 180.0)))) * q_grad[0])), (w[1] - ((radius / math.sin(((filet_angle / 2) * (math.pi / 180.0)))) * q_grad[1])))
z_point = ((w[0] + ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q1[0])), (w[1] + ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q1[1])))
turning_direction = math.copysign(1, ((q0[0] * q1[1]) - (q0[1] * q1[0])))
cur = self.nav.get_local_pos()
h_point = ((cur[0] - z_point[0]), (cur[1] - z_point[1]))
h_val = ((h_point[0] * q1[0]) + (h_point[1] * q1[1]))
if (h_val > 0):
self.nav = None
self.state = 0
return
distance_from_center = math.sqrt((math.pow((cur[0] - center_point[0]), 2) + math.pow((cur[1] - center_point[1]), 2)))
circ_x = (cur[1] - center_point[1])
circ_y = (cur[0] - center_point[0])
circle_angle = math.atan2(circ_x, circ_y)
if (circle_angle < 0):
circle_angle = (circle_angle + (2 * math.pi))
tangent_track = (circle_angle + (turning_direction * (math.pi / 2)))
if (tangent_track < 0):
tangent_track = (tangent_track + (2 * math.pi))
if (tangent_track > (2 * math.pi)):
tangent_track = (tangent_track - (2 * math.pi))
tangent_track = (tangent_track * (180.0 / math.pi))
error = ((distance_from_center - radius) / radius)
k_orbit = 4.0
heading = (tangent_track + (math.atan((k_orbit * error)) * (180.0 / math.pi)))
self.heading_hold(heading)
self.altitude_hold(altitude_comm=w[2]) | Maintains a track along a series of points in the simulation and the defined altitude along each path segment,
ensures a smooth turn by flying an arc/filet with radius=radius at each point
...
The aircraft maintains a track based on the bearing from the location the target was instantiated to the target.
When within a radius or crossing a plane perpendicular to track the aircraft goes from straight track mode to
flying a curved path of radius r around a point perpendicular to the point created by the confluence of the two
tracks. The method switches to the next point when it reaches a point equidistant from the beginning of the arc.
The method terminates when there is no further 'b' or 'c' points available i.e. 2 points before the final track.
The method is based off the algorithm defined in Beard & McLain chapter 11, path planning:
http://uavbook.byu.edu/doku.php
:param profile: series of points used to define a path formatted with a tuple at each index of the list
[latitude, longitude, altitude]
:param radius: fillet radial distance [m], used to calculate z point
:return: flag==True if the simulation has reached the termination condition | src/autopilot.py | arc_path | nkbeebe/FW-Airsim | 16 | python | def arc_path(self, profile, radius) -> bool:
"\n Maintains a track along a series of points in the simulation and the defined altitude along each path segment,\n ensures a smooth turn by flying an arc/filet with radius=radius at each point\n\n ...\n\n The aircraft maintains a track based on the bearing from the location the target was instantiated to the target.\n When within a radius or crossing a plane perpendicular to track the aircraft goes from straight track mode to\n flying a curved path of radius r around a point perpendicular to the point created by the confluence of the two\n tracks. The method switches to the next point when it reaches a point equidistant from the beginning of the arc.\n The method terminates when there is no further 'b' or 'c' points available i.e. 2 points before the final track.\n The method is based off the algorithm defined in Beard & McLain chapter 11, path planning:\n http://uavbook.byu.edu/doku.php\n :param profile: series of points used to define a path formatted with a tuple at each index of the list\n [latitude, longitude, altitude]\n :param radius: fillet radial distance [m], used to calculate z point\n :return: flag==True if the simulation has reached the termination condition\n "
if (self.nav is None):
print('Changing points !!!')
self.track_id = (self.track_id + 1)
print(self.track_id)
if (self.track_id == (len(profile) - 2)):
print('hit flag')
self.flag = True
return self.flag
point_a = profile[self.track_id]
point_b = profile[(self.track_id + 1)]
point_c = profile[(self.track_id + 2)]
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target((point_c[0] - point_b[0]), (point_c[1] - point_b[1]))
self.track_bearing_out = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing_out < 0):
self.track_bearing_out = (self.track_bearing_out + 360.0)
self.nav.local_target_set = False
self.nav.set_local_target((point_b[0] - point_a[0]), (point_b[1] - point_a[1]))
self.track_bearing_in = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing_in < 0):
self.track_bearing_in = (self.track_bearing_in + 360.0)
self.flag = False
if (self.nav is not None):
filet_angle = (self.track_bearing_out - self.track_bearing_in)
if (filet_angle < 0):
filet_angle = (filet_angle + 360)
if (self.state == 0):
q = self.nav.unit_dir_vector(profile[self.track_id], profile[(self.track_id + 1)])
w = profile[(self.track_id + 1)]
try:
z_point = ((w[0] - ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q[0])), (w[1] - ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q[1])))
cur = self.nav.get_local_pos()
h_point = ((cur[0] - z_point[0]), (cur[1] - z_point[1]))
h_val = ((h_point[0] * q[0]) + (h_point[1] * q[1]))
if (h_val > 0):
self.state = 1
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
off_tk_angle = (bearing - self.track_bearing_in)
if (off_tk_angle > 180):
off_tk_angle = (off_tk_angle - 360.0)
distance_to_go = self.nav.distance_to_go(distance, off_tk_angle)
if (distance_to_go > 3000):
distance_to_go = 3000
heading = ((((8 * 0.00033) * distance_to_go) * off_tk_angle) + self.track_bearing_in)
except ZeroDivisionError:
heading = self.track_bearing_in
print("You have straight lines don't do this!")
self.heading_hold(heading)
self.altitude_hold(altitude_comm=w[2])
if (self.state == 1):
q0 = self.nav.unit_dir_vector(profile[self.track_id], profile[(self.track_id + 1)])
q1 = self.nav.unit_dir_vector(profile[(self.track_id + 1)], profile[(self.track_id + 2)])
q_grad = self.nav.unit_dir_vector(q1, q0)
w = profile[(self.track_id + 1)]
center_point = ((w[0] - ((radius / math.sin(((filet_angle / 2) * (math.pi / 180.0)))) * q_grad[0])), (w[1] - ((radius / math.sin(((filet_angle / 2) * (math.pi / 180.0)))) * q_grad[1])))
z_point = ((w[0] + ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q1[0])), (w[1] + ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q1[1])))
turning_direction = math.copysign(1, ((q0[0] * q1[1]) - (q0[1] * q1[0])))
cur = self.nav.get_local_pos()
h_point = ((cur[0] - z_point[0]), (cur[1] - z_point[1]))
h_val = ((h_point[0] * q1[0]) + (h_point[1] * q1[1]))
if (h_val > 0):
self.nav = None
self.state = 0
return
distance_from_center = math.sqrt((math.pow((cur[0] - center_point[0]), 2) + math.pow((cur[1] - center_point[1]), 2)))
circ_x = (cur[1] - center_point[1])
circ_y = (cur[0] - center_point[0])
circle_angle = math.atan2(circ_x, circ_y)
if (circle_angle < 0):
circle_angle = (circle_angle + (2 * math.pi))
tangent_track = (circle_angle + (turning_direction * (math.pi / 2)))
if (tangent_track < 0):
tangent_track = (tangent_track + (2 * math.pi))
if (tangent_track > (2 * math.pi)):
tangent_track = (tangent_track - (2 * math.pi))
tangent_track = (tangent_track * (180.0 / math.pi))
error = ((distance_from_center - radius) / radius)
k_orbit = 4.0
heading = (tangent_track + (math.atan((k_orbit * error)) * (180.0 / math.pi)))
self.heading_hold(heading)
self.altitude_hold(altitude_comm=w[2]) | def arc_path(self, profile, radius) -> bool:
"\n Maintains a track along a series of points in the simulation and the defined altitude along each path segment,\n ensures a smooth turn by flying an arc/filet with radius=radius at each point\n\n ...\n\n The aircraft maintains a track based on the bearing from the location the target was instantiated to the target.\n When within a radius or crossing a plane perpendicular to track the aircraft goes from straight track mode to\n flying a curved path of radius r around a point perpendicular to the point created by the confluence of the two\n tracks. The method switches to the next point when it reaches a point equidistant from the beginning of the arc.\n The method terminates when there is no further 'b' or 'c' points available i.e. 2 points before the final track.\n The method is based off the algorithm defined in Beard & McLain chapter 11, path planning:\n http://uavbook.byu.edu/doku.php\n :param profile: series of points used to define a path formatted with a tuple at each index of the list\n [latitude, longitude, altitude]\n :param radius: fillet radial distance [m], used to calculate z point\n :return: flag==True if the simulation has reached the termination condition\n "
if (self.nav is None):
print('Changing points !!!')
self.track_id = (self.track_id + 1)
print(self.track_id)
if (self.track_id == (len(profile) - 2)):
print('hit flag')
self.flag = True
return self.flag
point_a = profile[self.track_id]
point_b = profile[(self.track_id + 1)]
point_c = profile[(self.track_id + 2)]
self.nav = LocalNavigation(self.sim)
self.nav.set_local_target((point_c[0] - point_b[0]), (point_c[1] - point_b[1]))
self.track_bearing_out = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing_out < 0):
self.track_bearing_out = (self.track_bearing_out + 360.0)
self.nav.local_target_set = False
self.nav.set_local_target((point_b[0] - point_a[0]), (point_b[1] - point_a[1]))
self.track_bearing_in = ((self.nav.bearing() * 180.0) / math.pi)
if (self.track_bearing_in < 0):
self.track_bearing_in = (self.track_bearing_in + 360.0)
self.flag = False
if (self.nav is not None):
filet_angle = (self.track_bearing_out - self.track_bearing_in)
if (filet_angle < 0):
filet_angle = (filet_angle + 360)
if (self.state == 0):
q = self.nav.unit_dir_vector(profile[self.track_id], profile[(self.track_id + 1)])
w = profile[(self.track_id + 1)]
try:
z_point = ((w[0] - ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q[0])), (w[1] - ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q[1])))
cur = self.nav.get_local_pos()
h_point = ((cur[0] - z_point[0]), (cur[1] - z_point[1]))
h_val = ((h_point[0] * q[0]) + (h_point[1] * q[1]))
if (h_val > 0):
self.state = 1
bearing = ((self.nav.bearing() * 180.0) / math.pi)
if (bearing < 0):
bearing = (bearing + 360)
distance = self.nav.distance()
off_tk_angle = (bearing - self.track_bearing_in)
if (off_tk_angle > 180):
off_tk_angle = (off_tk_angle - 360.0)
distance_to_go = self.nav.distance_to_go(distance, off_tk_angle)
if (distance_to_go > 3000):
distance_to_go = 3000
heading = ((((8 * 0.00033) * distance_to_go) * off_tk_angle) + self.track_bearing_in)
except ZeroDivisionError:
heading = self.track_bearing_in
print("You have straight lines don't do this!")
self.heading_hold(heading)
self.altitude_hold(altitude_comm=w[2])
if (self.state == 1):
q0 = self.nav.unit_dir_vector(profile[self.track_id], profile[(self.track_id + 1)])
q1 = self.nav.unit_dir_vector(profile[(self.track_id + 1)], profile[(self.track_id + 2)])
q_grad = self.nav.unit_dir_vector(q1, q0)
w = profile[(self.track_id + 1)]
center_point = ((w[0] - ((radius / math.sin(((filet_angle / 2) * (math.pi / 180.0)))) * q_grad[0])), (w[1] - ((radius / math.sin(((filet_angle / 2) * (math.pi / 180.0)))) * q_grad[1])))
z_point = ((w[0] + ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q1[0])), (w[1] + ((radius / math.tan(((filet_angle / 2) * (math.pi / 180.0)))) * q1[1])))
turning_direction = math.copysign(1, ((q0[0] * q1[1]) - (q0[1] * q1[0])))
cur = self.nav.get_local_pos()
h_point = ((cur[0] - z_point[0]), (cur[1] - z_point[1]))
h_val = ((h_point[0] * q1[0]) + (h_point[1] * q1[1]))
if (h_val > 0):
self.nav = None
self.state = 0
return
distance_from_center = math.sqrt((math.pow((cur[0] - center_point[0]), 2) + math.pow((cur[1] - center_point[1]), 2)))
circ_x = (cur[1] - center_point[1])
circ_y = (cur[0] - center_point[0])
circle_angle = math.atan2(circ_x, circ_y)
if (circle_angle < 0):
circle_angle = (circle_angle + (2 * math.pi))
tangent_track = (circle_angle + (turning_direction * (math.pi / 2)))
if (tangent_track < 0):
tangent_track = (tangent_track + (2 * math.pi))
if (tangent_track > (2 * math.pi)):
tangent_track = (tangent_track - (2 * math.pi))
tangent_track = (tangent_track * (180.0 / math.pi))
error = ((distance_from_center - radius) / radius)
k_orbit = 4.0
heading = (tangent_track + (math.atan((k_orbit * error)) * (180.0 / math.pi)))
self.heading_hold(heading)
self.altitude_hold(altitude_comm=w[2])<|docstring|>Maintains a track along a series of points in the simulation and the defined altitude along each path segment,
ensures a smooth turn by flying an arc/filet with radius=radius at each point
...
The aircraft maintains a track based on the bearing from the location the target was instantiated to the target.
When within a radius or crossing a plane perpendicular to track the aircraft goes from straight track mode to
flying a curved path of radius r around a point perpendicular to the point created by the confluence of the two
tracks. The method switches to the next point when it reaches a point equidistant from the beginning of the arc.
The method terminates when there is no further 'b' or 'c' points available i.e. 2 points before the final track.
The method is based off the algorithm defined in Beard & McLain chapter 11, path planning:
http://uavbook.byu.edu/doku.php
:param profile: series of points used to define a path formatted with a tuple at each index of the list
[latitude, longitude, altitude]
:param radius: fillet radial distance [m], used to calculate z point
:return: flag==True if the simulation has reached the termination condition<|endoftext|> |
0f629bb9e992183f2bb7bcaad229e71218086d6d3f60d9c3d03e043bb5f3368d | @app.cli.command()
def test() -> None:
'Run the unittests.'
os.system('pytest -v') | Run the unittests. | flog/commands.py | test | rice0208/Flog | 14 | python | @app.cli.command()
def test() -> None:
os.system('pytest -v') | @app.cli.command()
def test() -> None:
os.system('pytest -v')<|docstring|>Run the unittests.<|endoftext|> |
c47d91eb378c62e64859eaa4be2213c6cc752ee1865badbe0a564e1c32e0d120 | @app.cli.command()
def create_admin():
'Create administrator account'
from .models import Role, User
admin_role = Role.query.filter_by(name='Administrator').first()
username = app.config['FLOG_ADMIN']
email = app.config['FLOG_ADMIN_EMAIL']
password = app.config['FLOG_ADMIN_PASSWORD']
if (User.query.filter_by(email=email).count() == 0):
admin = User(username=username, email=email, name=username, confirmed=True)
admin.set_password(password)
admin.role = admin_role
db.session.add(admin)
db.session.commit()
else:
click.echo('Either exceeded the max number of admins: 1 or the role is invalid') | Create administrator account | flog/commands.py | create_admin | rice0208/Flog | 14 | python | @app.cli.command()
def create_admin():
from .models import Role, User
admin_role = Role.query.filter_by(name='Administrator').first()
username = app.config['FLOG_ADMIN']
email = app.config['FLOG_ADMIN_EMAIL']
password = app.config['FLOG_ADMIN_PASSWORD']
if (User.query.filter_by(email=email).count() == 0):
admin = User(username=username, email=email, name=username, confirmed=True)
admin.set_password(password)
admin.role = admin_role
db.session.add(admin)
db.session.commit()
else:
click.echo('Either exceeded the max number of admins: 1 or the role is invalid') | @app.cli.command()
def create_admin():
from .models import Role, User
admin_role = Role.query.filter_by(name='Administrator').first()
username = app.config['FLOG_ADMIN']
email = app.config['FLOG_ADMIN_EMAIL']
password = app.config['FLOG_ADMIN_PASSWORD']
if (User.query.filter_by(email=email).count() == 0):
admin = User(username=username, email=email, name=username, confirmed=True)
admin.set_password(password)
admin.role = admin_role
db.session.add(admin)
db.session.commit()
else:
click.echo('Either exceeded the max number of admins: 1 or the role is invalid')<|docstring|>Create administrator account<|endoftext|> |
a6edc8d54f7e74e02e29811bc7e693f36f735393995fc30d4f7011b31f36fad3 | @app.cli.command()
@click.option('--users', default=20, help='Generates fake users')
@click.option('--posts', default=20, help='Generates fake posts')
@click.option('--feedbacks', default=20, help='Generates fake feedbacks')
@click.option('--follows', default=20, help='Generates fake follows')
@click.option('--comments', default=20, help='Generates fake comments')
@click.option('--notifications', default=5, help='Generates fake notifications')
@click.option('--groups', default=20, help='Generates fake groups')
@click.option('--columns', default=20, help='Generate fake columns')
@click.option('--messages', default=20, help='Generate fake messages')
def forge(users, posts, feedbacks, follows, comments, notifications, groups, columns, messages):
'Generates fake data'
from . import fakes as fake
from .models import Role
Role.insert_roles()
fake.users(users)
fake.posts(posts)
fake.comments(comments)
fake.feedbacks(feedbacks)
fake.follows(follows)
fake.notifications(notifications)
fake.groups(groups)
fake.columns(columns)
fake.messages(messages) | Generates fake data | flog/commands.py | forge | rice0208/Flog | 14 | python | @app.cli.command()
@click.option('--users', default=20, help='Generates fake users')
@click.option('--posts', default=20, help='Generates fake posts')
@click.option('--feedbacks', default=20, help='Generates fake feedbacks')
@click.option('--follows', default=20, help='Generates fake follows')
@click.option('--comments', default=20, help='Generates fake comments')
@click.option('--notifications', default=5, help='Generates fake notifications')
@click.option('--groups', default=20, help='Generates fake groups')
@click.option('--columns', default=20, help='Generate fake columns')
@click.option('--messages', default=20, help='Generate fake messages')
def forge(users, posts, feedbacks, follows, comments, notifications, groups, columns, messages):
from . import fakes as fake
from .models import Role
Role.insert_roles()
fake.users(users)
fake.posts(posts)
fake.comments(comments)
fake.feedbacks(feedbacks)
fake.follows(follows)
fake.notifications(notifications)
fake.groups(groups)
fake.columns(columns)
fake.messages(messages) | @app.cli.command()
@click.option('--users', default=20, help='Generates fake users')
@click.option('--posts', default=20, help='Generates fake posts')
@click.option('--feedbacks', default=20, help='Generates fake feedbacks')
@click.option('--follows', default=20, help='Generates fake follows')
@click.option('--comments', default=20, help='Generates fake comments')
@click.option('--notifications', default=5, help='Generates fake notifications')
@click.option('--groups', default=20, help='Generates fake groups')
@click.option('--columns', default=20, help='Generate fake columns')
@click.option('--messages', default=20, help='Generate fake messages')
def forge(users, posts, feedbacks, follows, comments, notifications, groups, columns, messages):
from . import fakes as fake
from .models import Role
Role.insert_roles()
fake.users(users)
fake.posts(posts)
fake.comments(comments)
fake.feedbacks(feedbacks)
fake.follows(follows)
fake.notifications(notifications)
fake.groups(groups)
fake.columns(columns)
fake.messages(messages)<|docstring|>Generates fake data<|endoftext|> |
f655b39f6a45c66fb47a08a71c1e44935046cb3c3d8c32134ba5de11e2b8c094 | @app.cli.command()
@click.option('--drop/--no-drop', help='Drop database or not')
def init_db(drop: bool=False) -> None:
'Initialize database on a new machine.'
if drop:
db.drop_all(app=app)
db.create_all(app=app) | Initialize database on a new machine. | flog/commands.py | init_db | rice0208/Flog | 14 | python | @app.cli.command()
@click.option('--drop/--no-drop', help='Drop database or not')
def init_db(drop: bool=False) -> None:
if drop:
db.drop_all(app=app)
db.create_all(app=app) | @app.cli.command()
@click.option('--drop/--no-drop', help='Drop database or not')
def init_db(drop: bool=False) -> None:
if drop:
db.drop_all(app=app)
db.create_all(app=app)<|docstring|>Initialize database on a new machine.<|endoftext|> |
ac8ea8e756ce113df693f46e45a71f83a5d621390190991fcf69d33b9b57b8a7 | @app.cli.command()
def deploy():
'Run deployment tasks'
from flask_migrate import upgrade, stamp
try:
upgrade()
except:
db.create_all()
stamp()
from .models import User, Role
Role.insert_roles()
for user in User.query.all():
user.follow(user)
if os.system('pybabel compile -d flog/translations'):
raise RuntimeError('Error: Compiling failed.') | Run deployment tasks | flog/commands.py | deploy | rice0208/Flog | 14 | python | @app.cli.command()
def deploy():
from flask_migrate import upgrade, stamp
try:
upgrade()
except:
db.create_all()
stamp()
from .models import User, Role
Role.insert_roles()
for user in User.query.all():
user.follow(user)
if os.system('pybabel compile -d flog/translations'):
raise RuntimeError('Error: Compiling failed.') | @app.cli.command()
def deploy():
from flask_migrate import upgrade, stamp
try:
upgrade()
except:
db.create_all()
stamp()
from .models import User, Role
Role.insert_roles()
for user in User.query.all():
user.follow(user)
if os.system('pybabel compile -d flog/translations'):
raise RuntimeError('Error: Compiling failed.')<|docstring|>Run deployment tasks<|endoftext|> |
9a6562e98406e426969ec33ced4f77016db1be56a2690bc40e5a2745b8b028fb | @app.cli.group()
def translate():
'Translation and localization commands.'
pass | Translation and localization commands. | flog/commands.py | translate | rice0208/Flog | 14 | python | @app.cli.group()
def translate():
pass | @app.cli.group()
def translate():
pass<|docstring|>Translation and localization commands.<|endoftext|> |
5ef8d2fb0dd4c95f6a6758cf997db7898ec2858ea0c1e333210288f90f37a183 | @translate.command()
@click.argument('locale')
def init(locale):
'Initialize a new language.'
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('Error: Extracting the config file failed.')
if os.system(('pybabel init -i messages.pot -d flog`/translations -l ' + locale)):
raise RuntimeError(f'Error: Initing the new language {locale} failed.')
os.remove('messages.pot') | Initialize a new language. | flog/commands.py | init | rice0208/Flog | 14 | python | @translate.command()
@click.argument('locale')
def init(locale):
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('Error: Extracting the config file failed.')
if os.system(('pybabel init -i messages.pot -d flog`/translations -l ' + locale)):
raise RuntimeError(f'Error: Initing the new language {locale} failed.')
os.remove('messages.pot') | @translate.command()
@click.argument('locale')
def init(locale):
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('Error: Extracting the config file failed.')
if os.system(('pybabel init -i messages.pot -d flog`/translations -l ' + locale)):
raise RuntimeError(f'Error: Initing the new language {locale} failed.')
os.remove('messages.pot')<|docstring|>Initialize a new language.<|endoftext|> |
d33c40bc4c392f1db6353e0dc3e4bf289a3e32948a75d5d6f422388be58311ab | @translate.command()
def update():
'Update all languages.'
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('Error: Extracting the config file failed.')
if os.system('pybabel update -i messages.pot -d flog/translations'):
raise RuntimeError('Error: Updating the .po file failed.')
os.remove('messages.pot') | Update all languages. | flog/commands.py | update | rice0208/Flog | 14 | python | @translate.command()
def update():
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('Error: Extracting the config file failed.')
if os.system('pybabel update -i messages.pot -d flog/translations'):
raise RuntimeError('Error: Updating the .po file failed.')
os.remove('messages.pot') | @translate.command()
def update():
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('Error: Extracting the config file failed.')
if os.system('pybabel update -i messages.pot -d flog/translations'):
raise RuntimeError('Error: Updating the .po file failed.')
os.remove('messages.pot')<|docstring|>Update all languages.<|endoftext|> |
d17cf7bdbaa1c0a172dc3c8f418fc2c44a0b7a2d07f5d42d7cb21f2c300d0128 | @translate.command()
def compile():
'Compile all languages to .mo file.'
if os.system('pybabel compile -d flog/translations'):
raise RuntimeError('Error: Compiling failed.') | Compile all languages to .mo file. | flog/commands.py | compile | rice0208/Flog | 14 | python | @translate.command()
def compile():
if os.system('pybabel compile -d flog/translations'):
raise RuntimeError('Error: Compiling failed.') | @translate.command()
def compile():
if os.system('pybabel compile -d flog/translations'):
raise RuntimeError('Error: Compiling failed.')<|docstring|>Compile all languages to .mo file.<|endoftext|> |
f958dcd7aa605404050f42e95cd3e59ed919fe91dc4bf86218cc82abc99e1f1e | @property
def DceNodeIpv4Groups(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv4groups_45c069e4f39be165e2266b91bc876a78.DceNodeIpv4Groups): An instance of the DceNodeIpv4Groups class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv4groups_45c069e4f39be165e2266b91bc876a78 import DceNodeIpv4Groups
if (self._properties.get('DceNodeIpv4Groups', None) is not None):
return self._properties.get('DceNodeIpv4Groups')
else:
return DceNodeIpv4Groups(self) | Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv4groups_45c069e4f39be165e2266b91bc876a78.DceNodeIpv4Groups): An instance of the DceNodeIpv4Groups class
Raises
------
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | DceNodeIpv4Groups | OpenIxia/ixnetwork_restpy | 20 | python | @property
def DceNodeIpv4Groups(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv4groups_45c069e4f39be165e2266b91bc876a78.DceNodeIpv4Groups): An instance of the DceNodeIpv4Groups class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv4groups_45c069e4f39be165e2266b91bc876a78 import DceNodeIpv4Groups
if (self._properties.get('DceNodeIpv4Groups', None) is not None):
return self._properties.get('DceNodeIpv4Groups')
else:
return DceNodeIpv4Groups(self) | @property
def DceNodeIpv4Groups(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv4groups_45c069e4f39be165e2266b91bc876a78.DceNodeIpv4Groups): An instance of the DceNodeIpv4Groups class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv4groups_45c069e4f39be165e2266b91bc876a78 import DceNodeIpv4Groups
if (self._properties.get('DceNodeIpv4Groups', None) is not None):
return self._properties.get('DceNodeIpv4Groups')
else:
return DceNodeIpv4Groups(self)<|docstring|>Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv4groups_45c069e4f39be165e2266b91bc876a78.DceNodeIpv4Groups): An instance of the DceNodeIpv4Groups class
Raises
------
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
21fe83275d1ae309a4199b1d1c879a9e31b8808b460df1517f2dfcd3cb3e3f0a | @property
def DceNodeIpv6Groups(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv6groups_b1c5a6a36b8a89171fe4ff9773ebcf11.DceNodeIpv6Groups): An instance of the DceNodeIpv6Groups class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv6groups_b1c5a6a36b8a89171fe4ff9773ebcf11 import DceNodeIpv6Groups
if (self._properties.get('DceNodeIpv6Groups', None) is not None):
return self._properties.get('DceNodeIpv6Groups')
else:
return DceNodeIpv6Groups(self) | Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv6groups_b1c5a6a36b8a89171fe4ff9773ebcf11.DceNodeIpv6Groups): An instance of the DceNodeIpv6Groups class
Raises
------
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | DceNodeIpv6Groups | OpenIxia/ixnetwork_restpy | 20 | python | @property
def DceNodeIpv6Groups(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv6groups_b1c5a6a36b8a89171fe4ff9773ebcf11.DceNodeIpv6Groups): An instance of the DceNodeIpv6Groups class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv6groups_b1c5a6a36b8a89171fe4ff9773ebcf11 import DceNodeIpv6Groups
if (self._properties.get('DceNodeIpv6Groups', None) is not None):
return self._properties.get('DceNodeIpv6Groups')
else:
return DceNodeIpv6Groups(self) | @property
def DceNodeIpv6Groups(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv6groups_b1c5a6a36b8a89171fe4ff9773ebcf11.DceNodeIpv6Groups): An instance of the DceNodeIpv6Groups class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv6groups_b1c5a6a36b8a89171fe4ff9773ebcf11 import DceNodeIpv6Groups
if (self._properties.get('DceNodeIpv6Groups', None) is not None):
return self._properties.get('DceNodeIpv6Groups')
else:
return DceNodeIpv6Groups(self)<|docstring|>Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodeipv6groups_b1c5a6a36b8a89171fe4ff9773ebcf11.DceNodeIpv6Groups): An instance of the DceNodeIpv6Groups class
Raises
------
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
718a7b4ee815e8dac9164815938cb973a2e74646474dbfcb187f929024587f04 | @property
def DceNodeMacGroups(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodemacgroups_1bea0f65691a805b1d1d4bad054594d3.DceNodeMacGroups): An instance of the DceNodeMacGroups class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodemacgroups_1bea0f65691a805b1d1d4bad054594d3 import DceNodeMacGroups
if (self._properties.get('DceNodeMacGroups', None) is not None):
return self._properties.get('DceNodeMacGroups')
else:
return DceNodeMacGroups(self) | Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodemacgroups_1bea0f65691a805b1d1d4bad054594d3.DceNodeMacGroups): An instance of the DceNodeMacGroups class
Raises
------
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | DceNodeMacGroups | OpenIxia/ixnetwork_restpy | 20 | python | @property
def DceNodeMacGroups(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodemacgroups_1bea0f65691a805b1d1d4bad054594d3.DceNodeMacGroups): An instance of the DceNodeMacGroups class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodemacgroups_1bea0f65691a805b1d1d4bad054594d3 import DceNodeMacGroups
if (self._properties.get('DceNodeMacGroups', None) is not None):
return self._properties.get('DceNodeMacGroups')
else:
return DceNodeMacGroups(self) | @property
def DceNodeMacGroups(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodemacgroups_1bea0f65691a805b1d1d4bad054594d3.DceNodeMacGroups): An instance of the DceNodeMacGroups class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodemacgroups_1bea0f65691a805b1d1d4bad054594d3 import DceNodeMacGroups
if (self._properties.get('DceNodeMacGroups', None) is not None):
return self._properties.get('DceNodeMacGroups')
else:
return DceNodeMacGroups(self)<|docstring|>Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodemacgroups_1bea0f65691a805b1d1d4bad054594d3.DceNodeMacGroups): An instance of the DceNodeMacGroups class
Raises
------
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
7f7964452dc0f1b992aff91fd7faedda93a01f4b6bdf3e2339fd87cdf13e731e | @property
def DceNodeTopologyRange(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodetopologyrange_34374b8565456318538178dbf3a92ccb.DceNodeTopologyRange): An instance of the DceNodeTopologyRange class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodetopologyrange_34374b8565456318538178dbf3a92ccb import DceNodeTopologyRange
if (self._properties.get('DceNodeTopologyRange', None) is not None):
return self._properties.get('DceNodeTopologyRange')
else:
return DceNodeTopologyRange(self) | Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodetopologyrange_34374b8565456318538178dbf3a92ccb.DceNodeTopologyRange): An instance of the DceNodeTopologyRange class
Raises
------
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | DceNodeTopologyRange | OpenIxia/ixnetwork_restpy | 20 | python | @property
def DceNodeTopologyRange(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodetopologyrange_34374b8565456318538178dbf3a92ccb.DceNodeTopologyRange): An instance of the DceNodeTopologyRange class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodetopologyrange_34374b8565456318538178dbf3a92ccb import DceNodeTopologyRange
if (self._properties.get('DceNodeTopologyRange', None) is not None):
return self._properties.get('DceNodeTopologyRange')
else:
return DceNodeTopologyRange(self) | @property
def DceNodeTopologyRange(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodetopologyrange_34374b8565456318538178dbf3a92ccb.DceNodeTopologyRange): An instance of the DceNodeTopologyRange class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodetopologyrange_34374b8565456318538178dbf3a92ccb import DceNodeTopologyRange
if (self._properties.get('DceNodeTopologyRange', None) is not None):
return self._properties.get('DceNodeTopologyRange')
else:
return DceNodeTopologyRange(self)<|docstring|>Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dcenodetopologyrange_34374b8565456318538178dbf3a92ccb.DceNodeTopologyRange): An instance of the DceNodeTopologyRange class
Raises
------
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
32b505c706d120ade9cc505a1d0c1f4b9f63dc51c77e895af0c9c52998aedb4e | @property
def DceOutsideLinks(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dceoutsidelinks_c8ff484de41176eecca6e12142cde237.DceOutsideLinks): An instance of the DceOutsideLinks class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dceoutsidelinks_c8ff484de41176eecca6e12142cde237 import DceOutsideLinks
if (self._properties.get('DceOutsideLinks', None) is not None):
return self._properties.get('DceOutsideLinks')
else:
return DceOutsideLinks(self) | Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dceoutsidelinks_c8ff484de41176eecca6e12142cde237.DceOutsideLinks): An instance of the DceOutsideLinks class
Raises
------
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | DceOutsideLinks | OpenIxia/ixnetwork_restpy | 20 | python | @property
def DceOutsideLinks(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dceoutsidelinks_c8ff484de41176eecca6e12142cde237.DceOutsideLinks): An instance of the DceOutsideLinks class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dceoutsidelinks_c8ff484de41176eecca6e12142cde237 import DceOutsideLinks
if (self._properties.get('DceOutsideLinks', None) is not None):
return self._properties.get('DceOutsideLinks')
else:
return DceOutsideLinks(self) | @property
def DceOutsideLinks(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dceoutsidelinks_c8ff484de41176eecca6e12142cde237.DceOutsideLinks): An instance of the DceOutsideLinks class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dceoutsidelinks_c8ff484de41176eecca6e12142cde237 import DceOutsideLinks
if (self._properties.get('DceOutsideLinks', None) is not None):
return self._properties.get('DceOutsideLinks')
else:
return DceOutsideLinks(self)<|docstring|>Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.dceoutsidelinks_c8ff484de41176eecca6e12142cde237.DceOutsideLinks): An instance of the DceOutsideLinks class
Raises
------
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
4ffe44883e3f871819071be0f16d4577d3ffb0e07ccae962480bb3a5bcd9d978 | @property
def TrillNodeMacRanges(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.trillnodemacranges_4f6b90623cca463478f04a7f774acbab.TrillNodeMacRanges): An instance of the TrillNodeMacRanges class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.trillnodemacranges_4f6b90623cca463478f04a7f774acbab import TrillNodeMacRanges
if (self._properties.get('TrillNodeMacRanges', None) is not None):
return self._properties.get('TrillNodeMacRanges')
else:
return TrillNodeMacRanges(self) | Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.trillnodemacranges_4f6b90623cca463478f04a7f774acbab.TrillNodeMacRanges): An instance of the TrillNodeMacRanges class
Raises
------
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | TrillNodeMacRanges | OpenIxia/ixnetwork_restpy | 20 | python | @property
def TrillNodeMacRanges(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.trillnodemacranges_4f6b90623cca463478f04a7f774acbab.TrillNodeMacRanges): An instance of the TrillNodeMacRanges class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.trillnodemacranges_4f6b90623cca463478f04a7f774acbab import TrillNodeMacRanges
if (self._properties.get('TrillNodeMacRanges', None) is not None):
return self._properties.get('TrillNodeMacRanges')
else:
return TrillNodeMacRanges(self) | @property
def TrillNodeMacRanges(self):
'\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.trillnodemacranges_4f6b90623cca463478f04a7f774acbab.TrillNodeMacRanges): An instance of the TrillNodeMacRanges class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n '
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.trillnodemacranges_4f6b90623cca463478f04a7f774acbab import TrillNodeMacRanges
if (self._properties.get('TrillNodeMacRanges', None) is not None):
return self._properties.get('TrillNodeMacRanges')
else:
return TrillNodeMacRanges(self)<|docstring|>Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.trillnodemacranges_4f6b90623cca463478f04a7f774acbab.TrillNodeMacRanges): An instance of the TrillNodeMacRanges class
Raises
------
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
fb83e64b1793c9022e9fc1b287a2745d1741828f26add541edaa1ad88c03d562 | @property
def AdvertiseNetworkRange(self):
'\n Returns\n -------\n - bool: If true, this DCE ISIS Network Range is advertised.\n '
return self._get_attribute(self._SDM_ATT_MAP['AdvertiseNetworkRange']) | Returns
-------
- bool: If true, this DCE ISIS Network Range is advertised. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | AdvertiseNetworkRange | OpenIxia/ixnetwork_restpy | 20 | python | @property
def AdvertiseNetworkRange(self):
'\n Returns\n -------\n - bool: If true, this DCE ISIS Network Range is advertised.\n '
return self._get_attribute(self._SDM_ATT_MAP['AdvertiseNetworkRange']) | @property
def AdvertiseNetworkRange(self):
'\n Returns\n -------\n - bool: If true, this DCE ISIS Network Range is advertised.\n '
return self._get_attribute(self._SDM_ATT_MAP['AdvertiseNetworkRange'])<|docstring|>Returns
-------
- bool: If true, this DCE ISIS Network Range is advertised.<|endoftext|> |
2add1bc191346c5e91a9cd2c616e5daaf103e238e6a87c3b9be5a64971463f69 | @property
def BroadcastRootPriorityStep(self):
'DEPRECATED \n Returns\n -------\n - number: The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['BroadcastRootPriorityStep']) | DEPRECATED
Returns
-------
- number: The increment step of the Broadcast Root Priority of this emulated DCE ISIS router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | BroadcastRootPriorityStep | OpenIxia/ixnetwork_restpy | 20 | python | @property
def BroadcastRootPriorityStep(self):
'DEPRECATED \n Returns\n -------\n - number: The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['BroadcastRootPriorityStep']) | @property
def BroadcastRootPriorityStep(self):
'DEPRECATED \n Returns\n -------\n - number: The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['BroadcastRootPriorityStep'])<|docstring|>DEPRECATED
Returns
-------
- number: The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.<|endoftext|> |
e48aef3a55448cc44bbfbd97b2bf144b861b9c74705baca973c52fd38a2eb894 | @property
def CapabilityRouterId(self):
'\n Returns\n -------\n - str: The IP address format of Capability Router.\n '
return self._get_attribute(self._SDM_ATT_MAP['CapabilityRouterId']) | Returns
-------
- str: The IP address format of Capability Router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | CapabilityRouterId | OpenIxia/ixnetwork_restpy | 20 | python | @property
def CapabilityRouterId(self):
'\n Returns\n -------\n - str: The IP address format of Capability Router.\n '
return self._get_attribute(self._SDM_ATT_MAP['CapabilityRouterId']) | @property
def CapabilityRouterId(self):
'\n Returns\n -------\n - str: The IP address format of Capability Router.\n '
return self._get_attribute(self._SDM_ATT_MAP['CapabilityRouterId'])<|docstring|>Returns
-------
- str: The IP address format of Capability Router.<|endoftext|> |
aedc88e9f89cf5dfbff7c4e14feb884ac4283233e6a11efd89f19fd5d8fd7c46 | @property
def EnableHostName(self):
'\n Returns\n -------\n - bool: If true, the given dynamic host name is transmitted in all the packets sent from this router.\n '
return self._get_attribute(self._SDM_ATT_MAP['EnableHostName']) | Returns
-------
- bool: If true, the given dynamic host name is transmitted in all the packets sent from this router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | EnableHostName | OpenIxia/ixnetwork_restpy | 20 | python | @property
def EnableHostName(self):
'\n Returns\n -------\n - bool: If true, the given dynamic host name is transmitted in all the packets sent from this router.\n '
return self._get_attribute(self._SDM_ATT_MAP['EnableHostName']) | @property
def EnableHostName(self):
'\n Returns\n -------\n - bool: If true, the given dynamic host name is transmitted in all the packets sent from this router.\n '
return self._get_attribute(self._SDM_ATT_MAP['EnableHostName'])<|docstring|>Returns
-------
- bool: If true, the given dynamic host name is transmitted in all the packets sent from this router.<|endoftext|> |
f9a6d18d70e8036c6a66c9f4f7ee218eb6b93a041b34481bdec8c4c2acf17ce9 | @property
def EnableMultiTopology(self):
'\n Returns\n -------\n - bool: Enables more than one topology (distribution tree) corresponding to the given R bridge.\n '
return self._get_attribute(self._SDM_ATT_MAP['EnableMultiTopology']) | Returns
-------
- bool: Enables more than one topology (distribution tree) corresponding to the given R bridge. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | EnableMultiTopology | OpenIxia/ixnetwork_restpy | 20 | python | @property
def EnableMultiTopology(self):
'\n Returns\n -------\n - bool: Enables more than one topology (distribution tree) corresponding to the given R bridge.\n '
return self._get_attribute(self._SDM_ATT_MAP['EnableMultiTopology']) | @property
def EnableMultiTopology(self):
'\n Returns\n -------\n - bool: Enables more than one topology (distribution tree) corresponding to the given R bridge.\n '
return self._get_attribute(self._SDM_ATT_MAP['EnableMultiTopology'])<|docstring|>Returns
-------
- bool: Enables more than one topology (distribution tree) corresponding to the given R bridge.<|endoftext|> |
97b6bbe900451b6bbf01b0e1585317895228fab0657ca832deb99bc26443679d | @property
def EntryCol(self):
"\n Returns\n -------\n - number: The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n "
return self._get_attribute(self._SDM_ATT_MAP['EntryCol']) | Returns
-------
- number: The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | EntryCol | OpenIxia/ixnetwork_restpy | 20 | python | @property
def EntryCol(self):
"\n Returns\n -------\n - number: The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n "
return self._get_attribute(self._SDM_ATT_MAP['EntryCol']) | @property
def EntryCol(self):
"\n Returns\n -------\n - number: The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n "
return self._get_attribute(self._SDM_ATT_MAP['EntryCol'])<|docstring|>Returns
-------
- number: The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.<|endoftext|> |
558c6b53e75779e0ffcfcede308597c5f22a1e1306d14d9d4228ffac98e8fa4a | @property
def EntryRow(self):
"\n Returns\n -------\n - number: The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n "
return self._get_attribute(self._SDM_ATT_MAP['EntryRow']) | Returns
-------
- number: The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | EntryRow | OpenIxia/ixnetwork_restpy | 20 | python | @property
def EntryRow(self):
"\n Returns\n -------\n - number: The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n "
return self._get_attribute(self._SDM_ATT_MAP['EntryRow']) | @property
def EntryRow(self):
"\n Returns\n -------\n - number: The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n "
return self._get_attribute(self._SDM_ATT_MAP['EntryRow'])<|docstring|>Returns
-------
- number: The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.<|endoftext|> |
eae6355ea631e0b09e948be82850c441d9ee3dd0ca1e36a8833daa866cd640d4 | @property
def HostNamePrefix(self):
'\n Returns\n -------\n - str: Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n '
return self._get_attribute(self._SDM_ATT_MAP['HostNamePrefix']) | Returns
-------
- str: Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | HostNamePrefix | OpenIxia/ixnetwork_restpy | 20 | python | @property
def HostNamePrefix(self):
'\n Returns\n -------\n - str: Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n '
return self._get_attribute(self._SDM_ATT_MAP['HostNamePrefix']) | @property
def HostNamePrefix(self):
'\n Returns\n -------\n - str: Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n '
return self._get_attribute(self._SDM_ATT_MAP['HostNamePrefix'])<|docstring|>Returns
-------
- str: Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.<|endoftext|> |
4070fce53c7065e083f385236f6cfd9fc99127669505cd1c9a6ece6931e8d75b | @property
def InterfaceMetric(self):
'\n Returns\n -------\n - number: The metric cost associated with this emulated DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['InterfaceMetric']) | Returns
-------
- number: The metric cost associated with this emulated DCE ISIS router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | InterfaceMetric | OpenIxia/ixnetwork_restpy | 20 | python | @property
def InterfaceMetric(self):
'\n Returns\n -------\n - number: The metric cost associated with this emulated DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['InterfaceMetric']) | @property
def InterfaceMetric(self):
'\n Returns\n -------\n - number: The metric cost associated with this emulated DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['InterfaceMetric'])<|docstring|>Returns
-------
- number: The metric cost associated with this emulated DCE ISIS router.<|endoftext|> |
5069c637ee94f3849791fc961a13d86699635004175b853d250cda9667526d69 | @property
def LinkType(self):
'\n Returns\n -------\n - str(pointToPoint | broadcast): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only.\n '
return self._get_attribute(self._SDM_ATT_MAP['LinkType']) | Returns
-------
- str(pointToPoint | broadcast): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | LinkType | OpenIxia/ixnetwork_restpy | 20 | python | @property
def LinkType(self):
'\n Returns\n -------\n - str(pointToPoint | broadcast): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only.\n '
return self._get_attribute(self._SDM_ATT_MAP['LinkType']) | @property
def LinkType(self):
'\n Returns\n -------\n - str(pointToPoint | broadcast): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only.\n '
return self._get_attribute(self._SDM_ATT_MAP['LinkType'])<|docstring|>Returns
-------
- str(pointToPoint | broadcast): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only.<|endoftext|> |
4b71f3f5de588b76d21cadce8d3f78fa1583c18b121a3eb8febea21397644d1c | @property
def NoOfCols(self):
'\n Returns\n -------\n - number: The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['NoOfCols']) | Returns
-------
- number: The value in this field is used in combination with number of rows to create a matrix (grid) for a network range. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | NoOfCols | OpenIxia/ixnetwork_restpy | 20 | python | @property
def NoOfCols(self):
'\n Returns\n -------\n - number: The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['NoOfCols']) | @property
def NoOfCols(self):
'\n Returns\n -------\n - number: The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['NoOfCols'])<|docstring|>Returns
-------
- number: The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.<|endoftext|> |
2e659dd06fac2a90ff60a31366ca7294e2fac49a174f2f0c9e01264cf688cccc | @property
def NoOfRows(self):
'\n Returns\n -------\n - number: The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['NoOfRows']) | Returns
-------
- number: The value in this field is used in combination with number of columns to create a matrix (grid) for a network range. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | NoOfRows | OpenIxia/ixnetwork_restpy | 20 | python | @property
def NoOfRows(self):
'\n Returns\n -------\n - number: The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['NoOfRows']) | @property
def NoOfRows(self):
'\n Returns\n -------\n - number: The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['NoOfRows'])<|docstring|>Returns
-------
- number: The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.<|endoftext|> |
2b88ab5a8e6f77ff4d189445d4c5c39a6e2ddcbcc399494df09023b1a909c40e | @property
def NumberOfMultiDestinationTrees(self):
'DEPRECATED \n Returns\n -------\n - number: The number of Multi-Destination Trees for the DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['NumberOfMultiDestinationTrees']) | DEPRECATED
Returns
-------
- number: The number of Multi-Destination Trees for the DCE ISIS router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | NumberOfMultiDestinationTrees | OpenIxia/ixnetwork_restpy | 20 | python | @property
def NumberOfMultiDestinationTrees(self):
'DEPRECATED \n Returns\n -------\n - number: The number of Multi-Destination Trees for the DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['NumberOfMultiDestinationTrees']) | @property
def NumberOfMultiDestinationTrees(self):
'DEPRECATED \n Returns\n -------\n - number: The number of Multi-Destination Trees for the DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['NumberOfMultiDestinationTrees'])<|docstring|>DEPRECATED
Returns
-------
- number: The number of Multi-Destination Trees for the DCE ISIS router.<|endoftext|> |
d622e440cc9dbe6a450cbeb9bd165d6757560060fd38236988951ac52778efc3 | @property
def StartBroadcastRootPriority(self):
'DEPRECATED \n Returns\n -------\n - number: The starting value of the Broadcast Root Priority of this DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['StartBroadcastRootPriority']) | DEPRECATED
Returns
-------
- number: The starting value of the Broadcast Root Priority of this DCE ISIS router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | StartBroadcastRootPriority | OpenIxia/ixnetwork_restpy | 20 | python | @property
def StartBroadcastRootPriority(self):
'DEPRECATED \n Returns\n -------\n - number: The starting value of the Broadcast Root Priority of this DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['StartBroadcastRootPriority']) | @property
def StartBroadcastRootPriority(self):
'DEPRECATED \n Returns\n -------\n - number: The starting value of the Broadcast Root Priority of this DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['StartBroadcastRootPriority'])<|docstring|>DEPRECATED
Returns
-------
- number: The starting value of the Broadcast Root Priority of this DCE ISIS router.<|endoftext|> |
29e224da4f13ab2f8a60fb483bce7dd5966b4576fbb9788f737344516b287e1e | @property
def StartSwitchId(self):
'DEPRECATED \n Returns\n -------\n - number: The Switch ID of this emulated DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['StartSwitchId']) | DEPRECATED
Returns
-------
- number: The Switch ID of this emulated DCE ISIS router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | StartSwitchId | OpenIxia/ixnetwork_restpy | 20 | python | @property
def StartSwitchId(self):
'DEPRECATED \n Returns\n -------\n - number: The Switch ID of this emulated DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['StartSwitchId']) | @property
def StartSwitchId(self):
'DEPRECATED \n Returns\n -------\n - number: The Switch ID of this emulated DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['StartSwitchId'])<|docstring|>DEPRECATED
Returns
-------
- number: The Switch ID of this emulated DCE ISIS router.<|endoftext|> |
505a373eb4d72ed0a2c9aa80fa707d946d0f1e236980b9123115f505fee0a25c | @property
def StartSystemId(self):
'\n Returns\n -------\n - str: The System ID assigned to the starting DCE ISIS router in this network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['StartSystemId']) | Returns
-------
- str: The System ID assigned to the starting DCE ISIS router in this network range. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | StartSystemId | OpenIxia/ixnetwork_restpy | 20 | python | @property
def StartSystemId(self):
'\n Returns\n -------\n - str: The System ID assigned to the starting DCE ISIS router in this network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['StartSystemId']) | @property
def StartSystemId(self):
'\n Returns\n -------\n - str: The System ID assigned to the starting DCE ISIS router in this network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['StartSystemId'])<|docstring|>Returns
-------
- str: The System ID assigned to the starting DCE ISIS router in this network range.<|endoftext|> |
20a82cf4fe6c56ac83725e07835d1fd46d327d92395192ca7751d10fcc302664 | @property
def SwitchIdPriority(self):
'DEPRECATED \n Returns\n -------\n - number: The Switch ID priority of this DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['SwitchIdPriority']) | DEPRECATED
Returns
-------
- number: The Switch ID priority of this DCE ISIS router. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | SwitchIdPriority | OpenIxia/ixnetwork_restpy | 20 | python | @property
def SwitchIdPriority(self):
'DEPRECATED \n Returns\n -------\n - number: The Switch ID priority of this DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['SwitchIdPriority']) | @property
def SwitchIdPriority(self):
'DEPRECATED \n Returns\n -------\n - number: The Switch ID priority of this DCE ISIS router.\n '
return self._get_attribute(self._SDM_ATT_MAP['SwitchIdPriority'])<|docstring|>DEPRECATED
Returns
-------
- number: The Switch ID priority of this DCE ISIS router.<|endoftext|> |
1466a7f3b9f3b789fb0c89dbb00510d5c429410114a49adf360e05d26ebd2106 | @property
def SwitchIdStep(self):
'DEPRECATED \n Returns\n -------\n - number: The increment value by which the Switch ID of the DCE ISIS router increases.\n '
return self._get_attribute(self._SDM_ATT_MAP['SwitchIdStep']) | DEPRECATED
Returns
-------
- number: The increment value by which the Switch ID of the DCE ISIS router increases. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | SwitchIdStep | OpenIxia/ixnetwork_restpy | 20 | python | @property
def SwitchIdStep(self):
'DEPRECATED \n Returns\n -------\n - number: The increment value by which the Switch ID of the DCE ISIS router increases.\n '
return self._get_attribute(self._SDM_ATT_MAP['SwitchIdStep']) | @property
def SwitchIdStep(self):
'DEPRECATED \n Returns\n -------\n - number: The increment value by which the Switch ID of the DCE ISIS router increases.\n '
return self._get_attribute(self._SDM_ATT_MAP['SwitchIdStep'])<|docstring|>DEPRECATED
Returns
-------
- number: The increment value by which the Switch ID of the DCE ISIS router increases.<|endoftext|> |
dc3a134fdd524a4ea95f6ec0fadaed10927ee50daa63b9d99b488f89b850ede8 | @property
def SystemIdIncrementBy(self):
'\n Returns\n -------\n - str: The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['SystemIdIncrementBy']) | Returns
-------
- str: The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range. | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | SystemIdIncrementBy | OpenIxia/ixnetwork_restpy | 20 | python | @property
def SystemIdIncrementBy(self):
'\n Returns\n -------\n - str: The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['SystemIdIncrementBy']) | @property
def SystemIdIncrementBy(self):
'\n Returns\n -------\n - str: The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n '
return self._get_attribute(self._SDM_ATT_MAP['SystemIdIncrementBy'])<|docstring|>Returns
-------
- str: The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.<|endoftext|> |
41c0ab0fc1a1feb48b6dad9e36f023d5b8042a2a6872c8d765a4cd73468972a5 | def update(self, AdvertiseNetworkRange=None, BroadcastRootPriorityStep=None, CapabilityRouterId=None, EnableHostName=None, EnableMultiTopology=None, EntryCol=None, EntryRow=None, HostNamePrefix=None, InterfaceMetric=None, NoOfCols=None, NoOfRows=None, NumberOfMultiDestinationTrees=None, StartBroadcastRootPriority=None, StartSwitchId=None, StartSystemId=None, SwitchIdPriority=None, SwitchIdStep=None, SystemIdIncrementBy=None):
"Updates dceNetworkRange resource on the server.\n\n Args\n ----\n - AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.\n - BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n - CapabilityRouterId (str): The IP address format of Capability Router.\n - EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.\n - EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.\n - EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n - InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.\n - NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n - NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n - NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.\n - StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.\n - StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.\n - StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.\n - SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.\n - SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.\n - SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n "
return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) | Updates dceNetworkRange resource on the server.
Args
----
- AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.
- BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.
- CapabilityRouterId (str): The IP address format of Capability Router.
- EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.
- EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.
- EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.
- InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.
- NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.
- NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.
- NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.
- StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.
- StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.
- StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.
- SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.
- SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.
- SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.
Raises
------
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | update | OpenIxia/ixnetwork_restpy | 20 | python | def update(self, AdvertiseNetworkRange=None, BroadcastRootPriorityStep=None, CapabilityRouterId=None, EnableHostName=None, EnableMultiTopology=None, EntryCol=None, EntryRow=None, HostNamePrefix=None, InterfaceMetric=None, NoOfCols=None, NoOfRows=None, NumberOfMultiDestinationTrees=None, StartBroadcastRootPriority=None, StartSwitchId=None, StartSystemId=None, SwitchIdPriority=None, SwitchIdStep=None, SystemIdIncrementBy=None):
"Updates dceNetworkRange resource on the server.\n\n Args\n ----\n - AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.\n - BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n - CapabilityRouterId (str): The IP address format of Capability Router.\n - EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.\n - EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.\n - EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n - InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.\n - NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n - NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n - NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.\n - StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.\n - StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.\n - StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.\n - SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.\n - SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.\n - SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n "
return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) | def update(self, AdvertiseNetworkRange=None, BroadcastRootPriorityStep=None, CapabilityRouterId=None, EnableHostName=None, EnableMultiTopology=None, EntryCol=None, EntryRow=None, HostNamePrefix=None, InterfaceMetric=None, NoOfCols=None, NoOfRows=None, NumberOfMultiDestinationTrees=None, StartBroadcastRootPriority=None, StartSwitchId=None, StartSystemId=None, SwitchIdPriority=None, SwitchIdStep=None, SystemIdIncrementBy=None):
"Updates dceNetworkRange resource on the server.\n\n Args\n ----\n - AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.\n - BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n - CapabilityRouterId (str): The IP address format of Capability Router.\n - EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.\n - EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.\n - EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n - InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.\n - NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n - NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n - NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.\n - StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.\n - StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.\n - StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.\n - SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.\n - SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.\n - SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n "
return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))<|docstring|>Updates dceNetworkRange resource on the server.
Args
----
- AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.
- BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.
- CapabilityRouterId (str): The IP address format of Capability Router.
- EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.
- EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.
- EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.
- InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.
- NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.
- NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.
- NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.
- StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.
- StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.
- StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.
- SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.
- SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.
- SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.
Raises
------
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
78eef01f31f89b3ee5d521315d83d5a317993aa1a3ef604e45c999be5d0e6dd6 | def add(self, AdvertiseNetworkRange=None, BroadcastRootPriorityStep=None, CapabilityRouterId=None, EnableHostName=None, EnableMultiTopology=None, EntryCol=None, EntryRow=None, HostNamePrefix=None, InterfaceMetric=None, NoOfCols=None, NoOfRows=None, NumberOfMultiDestinationTrees=None, StartBroadcastRootPriority=None, StartSwitchId=None, StartSystemId=None, SwitchIdPriority=None, SwitchIdStep=None, SystemIdIncrementBy=None):
"Adds a new dceNetworkRange resource on the server and adds it to the container.\n\n Args\n ----\n - AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.\n - BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n - CapabilityRouterId (str): The IP address format of Capability Router.\n - EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.\n - EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.\n - EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n - InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.\n - NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n - NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n - NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.\n - StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.\n - StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.\n - StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.\n - SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.\n - SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.\n - SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n\n Returns\n -------\n - self: This instance with all currently retrieved dceNetworkRange resources using find and the newly added dceNetworkRange resources available through an iterator or index\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n "
return self._create(self._map_locals(self._SDM_ATT_MAP, locals())) | Adds a new dceNetworkRange resource on the server and adds it to the container.
Args
----
- AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.
- BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.
- CapabilityRouterId (str): The IP address format of Capability Router.
- EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.
- EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.
- EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.
- InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.
- NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.
- NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.
- NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.
- StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.
- StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.
- StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.
- SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.
- SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.
- SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.
Returns
-------
- self: This instance with all currently retrieved dceNetworkRange resources using find and the newly added dceNetworkRange resources available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | add | OpenIxia/ixnetwork_restpy | 20 | python | def add(self, AdvertiseNetworkRange=None, BroadcastRootPriorityStep=None, CapabilityRouterId=None, EnableHostName=None, EnableMultiTopology=None, EntryCol=None, EntryRow=None, HostNamePrefix=None, InterfaceMetric=None, NoOfCols=None, NoOfRows=None, NumberOfMultiDestinationTrees=None, StartBroadcastRootPriority=None, StartSwitchId=None, StartSystemId=None, SwitchIdPriority=None, SwitchIdStep=None, SystemIdIncrementBy=None):
"Adds a new dceNetworkRange resource on the server and adds it to the container.\n\n Args\n ----\n - AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.\n - BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n - CapabilityRouterId (str): The IP address format of Capability Router.\n - EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.\n - EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.\n - EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n - InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.\n - NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n - NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n - NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.\n - StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.\n - StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.\n - StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.\n - SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.\n - SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.\n - SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n\n Returns\n -------\n - self: This instance with all currently retrieved dceNetworkRange resources using find and the newly added dceNetworkRange resources available through an iterator or index\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n "
return self._create(self._map_locals(self._SDM_ATT_MAP, locals())) | def add(self, AdvertiseNetworkRange=None, BroadcastRootPriorityStep=None, CapabilityRouterId=None, EnableHostName=None, EnableMultiTopology=None, EntryCol=None, EntryRow=None, HostNamePrefix=None, InterfaceMetric=None, NoOfCols=None, NoOfRows=None, NumberOfMultiDestinationTrees=None, StartBroadcastRootPriority=None, StartSwitchId=None, StartSystemId=None, SwitchIdPriority=None, SwitchIdStep=None, SystemIdIncrementBy=None):
"Adds a new dceNetworkRange resource on the server and adds it to the container.\n\n Args\n ----\n - AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.\n - BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n - CapabilityRouterId (str): The IP address format of Capability Router.\n - EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.\n - EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.\n - EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n - InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.\n - NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n - NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n - NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.\n - StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.\n - StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.\n - StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.\n - SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.\n - SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.\n - SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n\n Returns\n -------\n - self: This instance with all currently retrieved dceNetworkRange resources using find and the newly added dceNetworkRange resources available through an iterator or index\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n "
return self._create(self._map_locals(self._SDM_ATT_MAP, locals()))<|docstring|>Adds a new dceNetworkRange resource on the server and adds it to the container.
Args
----
- AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.
- BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.
- CapabilityRouterId (str): The IP address format of Capability Router.
- EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.
- EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.
- EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.
- InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.
- NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.
- NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.
- NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.
- StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.
- StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.
- StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.
- SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.
- SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.
- SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.
Returns
-------
- self: This instance with all currently retrieved dceNetworkRange resources using find and the newly added dceNetworkRange resources available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
d4829426e4b066ed6a8c1598b99ec6dee746d6f74c6c6ff61338752aceb6c0db | def remove(self):
'Deletes all the contained dceNetworkRange resources in this instance from the server.\n\n Raises\n ------\n - NotFoundError: The requested resource does not exist on the server\n - ServerError: The server has encountered an uncategorized error condition\n '
self._delete() | Deletes all the contained dceNetworkRange resources in this instance from the server.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | remove | OpenIxia/ixnetwork_restpy | 20 | python | def remove(self):
'Deletes all the contained dceNetworkRange resources in this instance from the server.\n\n Raises\n ------\n - NotFoundError: The requested resource does not exist on the server\n - ServerError: The server has encountered an uncategorized error condition\n '
self._delete() | def remove(self):
'Deletes all the contained dceNetworkRange resources in this instance from the server.\n\n Raises\n ------\n - NotFoundError: The requested resource does not exist on the server\n - ServerError: The server has encountered an uncategorized error condition\n '
self._delete()<|docstring|>Deletes all the contained dceNetworkRange resources in this instance from the server.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
3a050f74399f80b3e45461bf3b756aff8dd10f52d35f98abb33faf1093e325e4 | def find(self, AdvertiseNetworkRange=None, BroadcastRootPriorityStep=None, CapabilityRouterId=None, EnableHostName=None, EnableMultiTopology=None, EntryCol=None, EntryRow=None, HostNamePrefix=None, InterfaceMetric=None, LinkType=None, NoOfCols=None, NoOfRows=None, NumberOfMultiDestinationTrees=None, StartBroadcastRootPriority=None, StartSwitchId=None, StartSystemId=None, SwitchIdPriority=None, SwitchIdStep=None, SystemIdIncrementBy=None):
"Finds and retrieves dceNetworkRange resources from the server.\n\n All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve dceNetworkRange resources from the server.\n To retrieve an exact match ensure the parameter value starts with ^ and ends with $\n By default the find method takes no parameters and will retrieve all dceNetworkRange resources from the server.\n\n Args\n ----\n - AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.\n - BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n - CapabilityRouterId (str): The IP address format of Capability Router.\n - EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.\n - EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.\n - EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n - InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.\n - LinkType (str(pointToPoint | broadcast)): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only.\n - NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n - NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n - NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.\n - StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.\n - StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.\n - StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.\n - SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.\n - SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.\n - SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n\n Returns\n -------\n - self: This instance with matching dceNetworkRange resources retrieved from the server available through an iterator or index\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n "
return self._select(self._map_locals(self._SDM_ATT_MAP, locals())) | Finds and retrieves dceNetworkRange resources from the server.
All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve dceNetworkRange resources from the server.
To retrieve an exact match ensure the parameter value starts with ^ and ends with $
By default the find method takes no parameters and will retrieve all dceNetworkRange resources from the server.
Args
----
- AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.
- BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.
- CapabilityRouterId (str): The IP address format of Capability Router.
- EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.
- EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.
- EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.
- InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.
- LinkType (str(pointToPoint | broadcast)): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only.
- NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.
- NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.
- NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.
- StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.
- StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.
- StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.
- SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.
- SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.
- SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.
Returns
-------
- self: This instance with matching dceNetworkRange resources retrieved from the server available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | find | OpenIxia/ixnetwork_restpy | 20 | python | def find(self, AdvertiseNetworkRange=None, BroadcastRootPriorityStep=None, CapabilityRouterId=None, EnableHostName=None, EnableMultiTopology=None, EntryCol=None, EntryRow=None, HostNamePrefix=None, InterfaceMetric=None, LinkType=None, NoOfCols=None, NoOfRows=None, NumberOfMultiDestinationTrees=None, StartBroadcastRootPriority=None, StartSwitchId=None, StartSystemId=None, SwitchIdPriority=None, SwitchIdStep=None, SystemIdIncrementBy=None):
"Finds and retrieves dceNetworkRange resources from the server.\n\n All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve dceNetworkRange resources from the server.\n To retrieve an exact match ensure the parameter value starts with ^ and ends with $\n By default the find method takes no parameters and will retrieve all dceNetworkRange resources from the server.\n\n Args\n ----\n - AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.\n - BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n - CapabilityRouterId (str): The IP address format of Capability Router.\n - EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.\n - EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.\n - EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n - InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.\n - LinkType (str(pointToPoint | broadcast)): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only.\n - NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n - NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n - NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.\n - StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.\n - StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.\n - StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.\n - SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.\n - SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.\n - SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n\n Returns\n -------\n - self: This instance with matching dceNetworkRange resources retrieved from the server available through an iterator or index\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n "
return self._select(self._map_locals(self._SDM_ATT_MAP, locals())) | def find(self, AdvertiseNetworkRange=None, BroadcastRootPriorityStep=None, CapabilityRouterId=None, EnableHostName=None, EnableMultiTopology=None, EntryCol=None, EntryRow=None, HostNamePrefix=None, InterfaceMetric=None, LinkType=None, NoOfCols=None, NoOfRows=None, NumberOfMultiDestinationTrees=None, StartBroadcastRootPriority=None, StartSwitchId=None, StartSystemId=None, SwitchIdPriority=None, SwitchIdStep=None, SystemIdIncrementBy=None):
"Finds and retrieves dceNetworkRange resources from the server.\n\n All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve dceNetworkRange resources from the server.\n To retrieve an exact match ensure the parameter value starts with ^ and ends with $\n By default the find method takes no parameters and will retrieve all dceNetworkRange resources from the server.\n\n Args\n ----\n - AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.\n - BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.\n - CapabilityRouterId (str): The IP address format of Capability Router.\n - EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.\n - EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.\n - EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.\n - HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.\n - InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.\n - LinkType (str(pointToPoint | broadcast)): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only.\n - NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.\n - NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.\n - NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.\n - StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.\n - StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.\n - StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.\n - SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.\n - SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.\n - SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.\n\n Returns\n -------\n - self: This instance with matching dceNetworkRange resources retrieved from the server available through an iterator or index\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n "
return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))<|docstring|>Finds and retrieves dceNetworkRange resources from the server.
All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve dceNetworkRange resources from the server.
To retrieve an exact match ensure the parameter value starts with ^ and ends with $
By default the find method takes no parameters and will retrieve all dceNetworkRange resources from the server.
Args
----
- AdvertiseNetworkRange (bool): If true, this DCE ISIS Network Range is advertised.
- BroadcastRootPriorityStep (number): The increment step of the Broadcast Root Priority of this emulated DCE ISIS router.
- CapabilityRouterId (str): The IP address format of Capability Router.
- EnableHostName (bool): If true, the given dynamic host name is transmitted in all the packets sent from this router.
- EnableMultiTopology (bool): Enables more than one topology (distribution tree) corresponding to the given R bridge.
- EntryCol (number): The value in this field is used in combination with entry row to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- EntryRow (number): The value in this field is used in combination with entry column to specify which 'virtual' router in the Network Range is connected to the current ISIS L2/L3 Router.
- HostNamePrefix (str): Allows to add a prefix to the generated host name of this router. When host name prefix is provided, the generated host name is appended by -1 for the first router and subsequently increased by 1 for each router.
- InterfaceMetric (number): The metric cost associated with this emulated DCE ISIS router.
- LinkType (str(pointToPoint | broadcast)): For DCE ISIS emulation type, the type of network link is set to Point-Point and made read-only.
- NoOfCols (number): The value in this field is used in combination with number of rows to create a matrix (grid) for a network range.
- NoOfRows (number): The value in this field is used in combination with number of columns to create a matrix (grid) for a network range.
- NumberOfMultiDestinationTrees (number): The number of Multi-Destination Trees for the DCE ISIS router.
- StartBroadcastRootPriority (number): The starting value of the Broadcast Root Priority of this DCE ISIS router.
- StartSwitchId (number): The Switch ID of this emulated DCE ISIS router.
- StartSystemId (str): The System ID assigned to the starting DCE ISIS router in this network range.
- SwitchIdPriority (number): The Switch ID priority of this DCE ISIS router.
- SwitchIdStep (number): The increment value by which the Switch ID of the DCE ISIS router increases.
- SystemIdIncrementBy (str): The incremented System ID used when more than one router is emulated. The increment value is added to the previous System ID for each additional emulated router in this network range.
Returns
-------
- self: This instance with matching dceNetworkRange resources retrieved from the server available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
c0bb1063636b99ce46a78bfbf68bd4c0a9c2e21da1934e1af959723875e168e2 | def read(self, href):
'Retrieves a single instance of dceNetworkRange data from the server.\n\n Args\n ----\n - href (str): An href to the instance to be retrieved\n\n Returns\n -------\n - self: This instance with the dceNetworkRange resources from the server available through an iterator or index\n\n Raises\n ------\n - NotFoundError: The requested resource does not exist on the server\n - ServerError: The server has encountered an uncategorized error condition\n '
return self._read(href) | Retrieves a single instance of dceNetworkRange data from the server.
Args
----
- href (str): An href to the instance to be retrieved
Returns
-------
- self: This instance with the dceNetworkRange resources from the server available through an iterator or index
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenetworkrange_de592cf3e2529092f28b2f14e5282a24.py | read | OpenIxia/ixnetwork_restpy | 20 | python | def read(self, href):
'Retrieves a single instance of dceNetworkRange data from the server.\n\n Args\n ----\n - href (str): An href to the instance to be retrieved\n\n Returns\n -------\n - self: This instance with the dceNetworkRange resources from the server available through an iterator or index\n\n Raises\n ------\n - NotFoundError: The requested resource does not exist on the server\n - ServerError: The server has encountered an uncategorized error condition\n '
return self._read(href) | def read(self, href):
'Retrieves a single instance of dceNetworkRange data from the server.\n\n Args\n ----\n - href (str): An href to the instance to be retrieved\n\n Returns\n -------\n - self: This instance with the dceNetworkRange resources from the server available through an iterator or index\n\n Raises\n ------\n - NotFoundError: The requested resource does not exist on the server\n - ServerError: The server has encountered an uncategorized error condition\n '
return self._read(href)<|docstring|>Retrieves a single instance of dceNetworkRange data from the server.
Args
----
- href (str): An href to the instance to be retrieved
Returns
-------
- self: This instance with the dceNetworkRange resources from the server available through an iterator or index
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition<|endoftext|> |
c9f25d6cd75e830cebcfd456cca66f8bc42c29acd20d640822f133ad59505866 | def add_classpaths(self, *args):
'\n Add additional entries to the classpath when starting the JVM\n '
self.class_path += args | Add additional entries to the classpath when starting the JVM | pyhidra/launcher.py | add_classpaths | Defense-Cyber-Crime-Center/pyhidra | 10 | python | def add_classpaths(self, *args):
'\n \n '
self.class_path += args | def add_classpaths(self, *args):
'\n \n '
self.class_path += args<|docstring|>Add additional entries to the classpath when starting the JVM<|endoftext|> |
619330008a174bfb5695e8ecbd1f78d8ddd25d4fc681d905499a521fb46956e9 | def add_vmargs(self, *args):
'\n Add additional vmargs for launching the JVM\n '
self.vm_args += args | Add additional vmargs for launching the JVM | pyhidra/launcher.py | add_vmargs | Defense-Cyber-Crime-Center/pyhidra | 10 | python | def add_vmargs(self, *args):
'\n \n '
self.vm_args += args | def add_vmargs(self, *args):
'\n \n '
self.vm_args += args<|docstring|>Add additional vmargs for launching the JVM<|endoftext|> |
0a345e9c63d06da8650215bb2c9e3b560af2419b03fed1aac2bacc560445d7e7 | @classmethod
def check_ghidra_version(cls):
'\n Checks if the currently installed Ghidra version is supported.\n The launcher will report the problem and terminate if it is not supported.\n '
if (CURRENT_GHIDRA_VERSION < MINIMUM_GHIDRA_VERSION):
cls._report_fatal_error('Unsupported Version', textwrap.dedent(f''' Ghidra version {CURRENT_GHIDRA_VERSION} is not supported
The minimum required version is {MINIMUM_GHIDRA_VERSION}
''').rstrip()) | Checks if the currently installed Ghidra version is supported.
The launcher will report the problem and terminate if it is not supported. | pyhidra/launcher.py | check_ghidra_version | Defense-Cyber-Crime-Center/pyhidra | 10 | python | @classmethod
def check_ghidra_version(cls):
'\n Checks if the currently installed Ghidra version is supported.\n The launcher will report the problem and terminate if it is not supported.\n '
if (CURRENT_GHIDRA_VERSION < MINIMUM_GHIDRA_VERSION):
cls._report_fatal_error('Unsupported Version', textwrap.dedent(f' Ghidra version {CURRENT_GHIDRA_VERSION} is not supported
The minimum required version is {MINIMUM_GHIDRA_VERSION}
').rstrip()) | @classmethod
def check_ghidra_version(cls):
'\n Checks if the currently installed Ghidra version is supported.\n The launcher will report the problem and terminate if it is not supported.\n '
if (CURRENT_GHIDRA_VERSION < MINIMUM_GHIDRA_VERSION):
cls._report_fatal_error('Unsupported Version', textwrap.dedent(f' Ghidra version {CURRENT_GHIDRA_VERSION} is not supported
The minimum required version is {MINIMUM_GHIDRA_VERSION}
').rstrip())<|docstring|>Checks if the currently installed Ghidra version is supported.
The launcher will report the problem and terminate if it is not supported.<|endoftext|> |
0edf7fc7e38e8c41e7e816cc45e00b35782c2da8cf04ae1faebf8c74f32d7568 | def start(self):
'\n Starts Jpype connection to Ghidra (if not already started).\n '
if (not jpype.isJVMStarted()):
self.check_ghidra_version()
if (self.java_home is None):
java_home = subprocess.check_output(_GET_JAVA_HOME, encoding='utf-8', shell=True)
self.java_home = Path(java_home.rstrip())
jvm = _get_libjvm_path(self.java_home)
jpype.startJVM(str(jvm), *self.vm_args, ignoreUnrecognized=True, convertStrings=True, classpath=self.class_path)
imports.registerDomain('ghidra')
from ghidra import GhidraLauncher
self._update()
self.layout = GhidraLauncher.initializeGhidraEnvironment()
from pyhidra.java.plugin import install
install()
from . import properties as _
self._launch() | Starts Jpype connection to Ghidra (if not already started). | pyhidra/launcher.py | start | Defense-Cyber-Crime-Center/pyhidra | 10 | python | def start(self):
'\n \n '
if (not jpype.isJVMStarted()):
self.check_ghidra_version()
if (self.java_home is None):
java_home = subprocess.check_output(_GET_JAVA_HOME, encoding='utf-8', shell=True)
self.java_home = Path(java_home.rstrip())
jvm = _get_libjvm_path(self.java_home)
jpype.startJVM(str(jvm), *self.vm_args, ignoreUnrecognized=True, convertStrings=True, classpath=self.class_path)
imports.registerDomain('ghidra')
from ghidra import GhidraLauncher
self._update()
self.layout = GhidraLauncher.initializeGhidraEnvironment()
from pyhidra.java.plugin import install
install()
from . import properties as _
self._launch() | def start(self):
'\n \n '
if (not jpype.isJVMStarted()):
self.check_ghidra_version()
if (self.java_home is None):
java_home = subprocess.check_output(_GET_JAVA_HOME, encoding='utf-8', shell=True)
self.java_home = Path(java_home.rstrip())
jvm = _get_libjvm_path(self.java_home)
jpype.startJVM(str(jvm), *self.vm_args, ignoreUnrecognized=True, convertStrings=True, classpath=self.class_path)
imports.registerDomain('ghidra')
from ghidra import GhidraLauncher
self._update()
self.layout = GhidraLauncher.initializeGhidraEnvironment()
from pyhidra.java.plugin import install
install()
from . import properties as _
self._launch()<|docstring|>Starts Jpype connection to Ghidra (if not already started).<|endoftext|> |
6fe8bd2f910ae57516a780f574c800f2efd816e4dd3f1c5fc1d504a9b581d1fc | @staticmethod
def has_launched() -> bool:
'\n Checks if jpype has started and if Ghidra has been fully initialized.\n '
if (not jpype.isJVMStarted()):
return False
from ghidra.framework import Application
return Application.isInitialized() | Checks if jpype has started and if Ghidra has been fully initialized. | pyhidra/launcher.py | has_launched | Defense-Cyber-Crime-Center/pyhidra | 10 | python | @staticmethod
def has_launched() -> bool:
'\n \n '
if (not jpype.isJVMStarted()):
return False
from ghidra.framework import Application
return Application.isInitialized() | @staticmethod
def has_launched() -> bool:
'\n \n '
if (not jpype.isJVMStarted()):
return False
from ghidra.framework import Application
return Application.isInitialized()<|docstring|>Checks if jpype has started and if Ghidra has been fully initialized.<|endoftext|> |
448896cecf032606eee9d06546798fb52900936a897fba5ccd78a8b44a55c69e | def initialize_ghidra(self, headless=True):
'\n Finished Ghidra initialization\n\n :param headless: whether or not to initialize Ghidra in headless mode.\n (Defaults to True)\n '
from ghidra import GhidraRun
from ghidra.framework import Application, HeadlessGhidraApplicationConfiguration
with _silence_java_output((not self.verbose), (not self.verbose)):
if headless:
config = HeadlessGhidraApplicationConfiguration()
Application.initializeApplication(self.layout, config)
else:
GhidraRun().launch(self.layout, self.args) | Finished Ghidra initialization
:param headless: whether or not to initialize Ghidra in headless mode.
(Defaults to True) | pyhidra/launcher.py | initialize_ghidra | Defense-Cyber-Crime-Center/pyhidra | 10 | python | def initialize_ghidra(self, headless=True):
'\n Finished Ghidra initialization\n\n :param headless: whether or not to initialize Ghidra in headless mode.\n (Defaults to True)\n '
from ghidra import GhidraRun
from ghidra.framework import Application, HeadlessGhidraApplicationConfiguration
with _silence_java_output((not self.verbose), (not self.verbose)):
if headless:
config = HeadlessGhidraApplicationConfiguration()
Application.initializeApplication(self.layout, config)
else:
GhidraRun().launch(self.layout, self.args) | def initialize_ghidra(self, headless=True):
'\n Finished Ghidra initialization\n\n :param headless: whether or not to initialize Ghidra in headless mode.\n (Defaults to True)\n '
from ghidra import GhidraRun
from ghidra.framework import Application, HeadlessGhidraApplicationConfiguration
with _silence_java_output((not self.verbose), (not self.verbose)):
if headless:
config = HeadlessGhidraApplicationConfiguration()
Application.initializeApplication(self.layout, config)
else:
GhidraRun().launch(self.layout, self.args)<|docstring|>Finished Ghidra initialization
:param headless: whether or not to initialize Ghidra in headless mode.
(Defaults to True)<|endoftext|> |
4c7ed2d170e81945b53f5bc801976beaeb7933916e9f73037d931fe90d59d2d0 | def arrows(xstart, ystart, xend, yend, *args, ax=None, vertical=False, **kwargs):
" Utility wrapper around matplotlib.axes.Axes.quiver.\n Quiver uses locations and direction vectors usually.\n Here these are instead calculated automatically\n from the start and endpoints of the arrow.\n The function also automatically flips the x and y coordinates if the pitch is vertical.\n\n Plot a 2D field of arrows.\n See: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.quiver.html\n\n Parameters\n ----------\n xstart, ystart, xend, yend: array-like or scalar.\n Commonly, these parameters are 1D arrays.\n These should be the start and end coordinates of the lines.\n C: 1D or 2D array-like, optional\n Numeric data that defines the arrow colors by colormapping via norm and cmap.\n This does not support explicit colors.\n If you want to set colors directly, use color instead.\n The size of C must match the number of arrow locations.\n ax : matplotlib.axes.Axes, default None\n The axis to plot on.\n vertical : bool, default False\n If the orientation is vertical (True), then the code switches the x and y coordinates.\n width : float, default 4\n Arrow shaft width in points.\n headwidth : float, default 3\n Head width as a multiple of the arrow shaft width.\n headlength : float, default 5\n Head length as a multiple of the arrow shaft width.\n headaxislength : float, default: 4.5\n Head length at the shaft intersection.\n If this is equal to the headlength then the arrow will be a triangular shape.\n If greater than the headlength then the arrow will be wedge shaped.\n If less than the headlength the arrow will be swept back.\n color : color or color sequence, optional\n Explicit color(s) for the arrows. If C has been set, color has no effect.\n linewidth or linewidths or lw : float or sequence of floats\n Edgewidth of arrow.\n edgecolor or ec or edgecolors : color or sequence of colors or 'face'\n alpha : float or None\n Transparency of arrows.\n **kwargs : All other keyword arguments are passed on to matplotlib.axes.Axes.quiver.\n\n Returns\n -------\n PolyCollection : matplotlib.quiver.Quiver\n\n Examples\n --------\n >>> from mplsoccer import Pitch\n >>> pitch = Pitch()\n >>> fig, ax = pitch.draw()\n >>> pitch.arrows(20, 20, 45, 80, ax=ax)\n\n >>> from mplsoccer.quiver import arrows\n >>> import matplotlib.pyplot as plt\n >>> fig, ax = plt.subplots()\n >>> arrows([0.1, 0.4], [0.1, 0.5], [0.9, 0.4], [0.8, 0.8], ax=ax)\n >>> ax.set_xlim(0, 1)\n >>> ax.set_ylim(0, 1)\n "
validate_ax(ax)
units = kwargs.pop('units', 'inches')
scale_units = kwargs.pop('scale_units', 'xy')
angles = kwargs.pop('angles', 'xy')
scale = kwargs.pop('scale', 1)
width = kwargs.pop('width', 4)
width = (width / 72.0)
xstart = np.ravel(xstart)
ystart = np.ravel(ystart)
xend = np.ravel(xend)
yend = np.ravel(yend)
if (xstart.size != ystart.size):
raise ValueError('xstart and ystart must be the same size')
if (xstart.size != xend.size):
raise ValueError('xstart and xend must be the same size')
if (ystart.size != yend.size):
raise ValueError('ystart and yend must be the same size')
u = (xend - xstart)
v = (yend - ystart)
if vertical:
(ystart, xstart) = (xstart, ystart)
(v, u) = (u, v)
q = ax.quiver(xstart, ystart, u, v, *args, units=units, scale_units=scale_units, angles=angles, scale=scale, width=width, **kwargs)
quiver_handler = HandlerQuiver()
Legend.update_default_handler_map({q: quiver_handler})
return q | Utility wrapper around matplotlib.axes.Axes.quiver.
Quiver uses locations and direction vectors usually.
Here these are instead calculated automatically
from the start and endpoints of the arrow.
The function also automatically flips the x and y coordinates if the pitch is vertical.
Plot a 2D field of arrows.
See: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.quiver.html
Parameters
----------
xstart, ystart, xend, yend: array-like or scalar.
Commonly, these parameters are 1D arrays.
These should be the start and end coordinates of the lines.
C: 1D or 2D array-like, optional
Numeric data that defines the arrow colors by colormapping via norm and cmap.
This does not support explicit colors.
If you want to set colors directly, use color instead.
The size of C must match the number of arrow locations.
ax : matplotlib.axes.Axes, default None
The axis to plot on.
vertical : bool, default False
If the orientation is vertical (True), then the code switches the x and y coordinates.
width : float, default 4
Arrow shaft width in points.
headwidth : float, default 3
Head width as a multiple of the arrow shaft width.
headlength : float, default 5
Head length as a multiple of the arrow shaft width.
headaxislength : float, default: 4.5
Head length at the shaft intersection.
If this is equal to the headlength then the arrow will be a triangular shape.
If greater than the headlength then the arrow will be wedge shaped.
If less than the headlength the arrow will be swept back.
color : color or color sequence, optional
Explicit color(s) for the arrows. If C has been set, color has no effect.
linewidth or linewidths or lw : float or sequence of floats
Edgewidth of arrow.
edgecolor or ec or edgecolors : color or sequence of colors or 'face'
alpha : float or None
Transparency of arrows.
**kwargs : All other keyword arguments are passed on to matplotlib.axes.Axes.quiver.
Returns
-------
PolyCollection : matplotlib.quiver.Quiver
Examples
--------
>>> from mplsoccer import Pitch
>>> pitch = Pitch()
>>> fig, ax = pitch.draw()
>>> pitch.arrows(20, 20, 45, 80, ax=ax)
>>> from mplsoccer.quiver import arrows
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> arrows([0.1, 0.4], [0.1, 0.5], [0.9, 0.4], [0.8, 0.8], ax=ax)
>>> ax.set_xlim(0, 1)
>>> ax.set_ylim(0, 1) | mplsoccer/quiver.py | arrows | MalreddyNitin/mplsoccer | 157 | python | def arrows(xstart, ystart, xend, yend, *args, ax=None, vertical=False, **kwargs):
" Utility wrapper around matplotlib.axes.Axes.quiver.\n Quiver uses locations and direction vectors usually.\n Here these are instead calculated automatically\n from the start and endpoints of the arrow.\n The function also automatically flips the x and y coordinates if the pitch is vertical.\n\n Plot a 2D field of arrows.\n See: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.quiver.html\n\n Parameters\n ----------\n xstart, ystart, xend, yend: array-like or scalar.\n Commonly, these parameters are 1D arrays.\n These should be the start and end coordinates of the lines.\n C: 1D or 2D array-like, optional\n Numeric data that defines the arrow colors by colormapping via norm and cmap.\n This does not support explicit colors.\n If you want to set colors directly, use color instead.\n The size of C must match the number of arrow locations.\n ax : matplotlib.axes.Axes, default None\n The axis to plot on.\n vertical : bool, default False\n If the orientation is vertical (True), then the code switches the x and y coordinates.\n width : float, default 4\n Arrow shaft width in points.\n headwidth : float, default 3\n Head width as a multiple of the arrow shaft width.\n headlength : float, default 5\n Head length as a multiple of the arrow shaft width.\n headaxislength : float, default: 4.5\n Head length at the shaft intersection.\n If this is equal to the headlength then the arrow will be a triangular shape.\n If greater than the headlength then the arrow will be wedge shaped.\n If less than the headlength the arrow will be swept back.\n color : color or color sequence, optional\n Explicit color(s) for the arrows. If C has been set, color has no effect.\n linewidth or linewidths or lw : float or sequence of floats\n Edgewidth of arrow.\n edgecolor or ec or edgecolors : color or sequence of colors or 'face'\n alpha : float or None\n Transparency of arrows.\n **kwargs : All other keyword arguments are passed on to matplotlib.axes.Axes.quiver.\n\n Returns\n -------\n PolyCollection : matplotlib.quiver.Quiver\n\n Examples\n --------\n >>> from mplsoccer import Pitch\n >>> pitch = Pitch()\n >>> fig, ax = pitch.draw()\n >>> pitch.arrows(20, 20, 45, 80, ax=ax)\n\n >>> from mplsoccer.quiver import arrows\n >>> import matplotlib.pyplot as plt\n >>> fig, ax = plt.subplots()\n >>> arrows([0.1, 0.4], [0.1, 0.5], [0.9, 0.4], [0.8, 0.8], ax=ax)\n >>> ax.set_xlim(0, 1)\n >>> ax.set_ylim(0, 1)\n "
validate_ax(ax)
units = kwargs.pop('units', 'inches')
scale_units = kwargs.pop('scale_units', 'xy')
angles = kwargs.pop('angles', 'xy')
scale = kwargs.pop('scale', 1)
width = kwargs.pop('width', 4)
width = (width / 72.0)
xstart = np.ravel(xstart)
ystart = np.ravel(ystart)
xend = np.ravel(xend)
yend = np.ravel(yend)
if (xstart.size != ystart.size):
raise ValueError('xstart and ystart must be the same size')
if (xstart.size != xend.size):
raise ValueError('xstart and xend must be the same size')
if (ystart.size != yend.size):
raise ValueError('ystart and yend must be the same size')
u = (xend - xstart)
v = (yend - ystart)
if vertical:
(ystart, xstart) = (xstart, ystart)
(v, u) = (u, v)
q = ax.quiver(xstart, ystart, u, v, *args, units=units, scale_units=scale_units, angles=angles, scale=scale, width=width, **kwargs)
quiver_handler = HandlerQuiver()
Legend.update_default_handler_map({q: quiver_handler})
return q | def arrows(xstart, ystart, xend, yend, *args, ax=None, vertical=False, **kwargs):
" Utility wrapper around matplotlib.axes.Axes.quiver.\n Quiver uses locations and direction vectors usually.\n Here these are instead calculated automatically\n from the start and endpoints of the arrow.\n The function also automatically flips the x and y coordinates if the pitch is vertical.\n\n Plot a 2D field of arrows.\n See: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.quiver.html\n\n Parameters\n ----------\n xstart, ystart, xend, yend: array-like or scalar.\n Commonly, these parameters are 1D arrays.\n These should be the start and end coordinates of the lines.\n C: 1D or 2D array-like, optional\n Numeric data that defines the arrow colors by colormapping via norm and cmap.\n This does not support explicit colors.\n If you want to set colors directly, use color instead.\n The size of C must match the number of arrow locations.\n ax : matplotlib.axes.Axes, default None\n The axis to plot on.\n vertical : bool, default False\n If the orientation is vertical (True), then the code switches the x and y coordinates.\n width : float, default 4\n Arrow shaft width in points.\n headwidth : float, default 3\n Head width as a multiple of the arrow shaft width.\n headlength : float, default 5\n Head length as a multiple of the arrow shaft width.\n headaxislength : float, default: 4.5\n Head length at the shaft intersection.\n If this is equal to the headlength then the arrow will be a triangular shape.\n If greater than the headlength then the arrow will be wedge shaped.\n If less than the headlength the arrow will be swept back.\n color : color or color sequence, optional\n Explicit color(s) for the arrows. If C has been set, color has no effect.\n linewidth or linewidths or lw : float or sequence of floats\n Edgewidth of arrow.\n edgecolor or ec or edgecolors : color or sequence of colors or 'face'\n alpha : float or None\n Transparency of arrows.\n **kwargs : All other keyword arguments are passed on to matplotlib.axes.Axes.quiver.\n\n Returns\n -------\n PolyCollection : matplotlib.quiver.Quiver\n\n Examples\n --------\n >>> from mplsoccer import Pitch\n >>> pitch = Pitch()\n >>> fig, ax = pitch.draw()\n >>> pitch.arrows(20, 20, 45, 80, ax=ax)\n\n >>> from mplsoccer.quiver import arrows\n >>> import matplotlib.pyplot as plt\n >>> fig, ax = plt.subplots()\n >>> arrows([0.1, 0.4], [0.1, 0.5], [0.9, 0.4], [0.8, 0.8], ax=ax)\n >>> ax.set_xlim(0, 1)\n >>> ax.set_ylim(0, 1)\n "
validate_ax(ax)
units = kwargs.pop('units', 'inches')
scale_units = kwargs.pop('scale_units', 'xy')
angles = kwargs.pop('angles', 'xy')
scale = kwargs.pop('scale', 1)
width = kwargs.pop('width', 4)
width = (width / 72.0)
xstart = np.ravel(xstart)
ystart = np.ravel(ystart)
xend = np.ravel(xend)
yend = np.ravel(yend)
if (xstart.size != ystart.size):
raise ValueError('xstart and ystart must be the same size')
if (xstart.size != xend.size):
raise ValueError('xstart and xend must be the same size')
if (ystart.size != yend.size):
raise ValueError('ystart and yend must be the same size')
u = (xend - xstart)
v = (yend - ystart)
if vertical:
(ystart, xstart) = (xstart, ystart)
(v, u) = (u, v)
q = ax.quiver(xstart, ystart, u, v, *args, units=units, scale_units=scale_units, angles=angles, scale=scale, width=width, **kwargs)
quiver_handler = HandlerQuiver()
Legend.update_default_handler_map({q: quiver_handler})
return q<|docstring|>Utility wrapper around matplotlib.axes.Axes.quiver.
Quiver uses locations and direction vectors usually.
Here these are instead calculated automatically
from the start and endpoints of the arrow.
The function also automatically flips the x and y coordinates if the pitch is vertical.
Plot a 2D field of arrows.
See: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.quiver.html
Parameters
----------
xstart, ystart, xend, yend: array-like or scalar.
Commonly, these parameters are 1D arrays.
These should be the start and end coordinates of the lines.
C: 1D or 2D array-like, optional
Numeric data that defines the arrow colors by colormapping via norm and cmap.
This does not support explicit colors.
If you want to set colors directly, use color instead.
The size of C must match the number of arrow locations.
ax : matplotlib.axes.Axes, default None
The axis to plot on.
vertical : bool, default False
If the orientation is vertical (True), then the code switches the x and y coordinates.
width : float, default 4
Arrow shaft width in points.
headwidth : float, default 3
Head width as a multiple of the arrow shaft width.
headlength : float, default 5
Head length as a multiple of the arrow shaft width.
headaxislength : float, default: 4.5
Head length at the shaft intersection.
If this is equal to the headlength then the arrow will be a triangular shape.
If greater than the headlength then the arrow will be wedge shaped.
If less than the headlength the arrow will be swept back.
color : color or color sequence, optional
Explicit color(s) for the arrows. If C has been set, color has no effect.
linewidth or linewidths or lw : float or sequence of floats
Edgewidth of arrow.
edgecolor or ec or edgecolors : color or sequence of colors or 'face'
alpha : float or None
Transparency of arrows.
**kwargs : All other keyword arguments are passed on to matplotlib.axes.Axes.quiver.
Returns
-------
PolyCollection : matplotlib.quiver.Quiver
Examples
--------
>>> from mplsoccer import Pitch
>>> pitch = Pitch()
>>> fig, ax = pitch.draw()
>>> pitch.arrows(20, 20, 45, 80, ax=ax)
>>> from mplsoccer.quiver import arrows
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> arrows([0.1, 0.4], [0.1, 0.5], [0.9, 0.4], [0.8, 0.8], ax=ax)
>>> ax.set_xlim(0, 1)
>>> ax.set_ylim(0, 1)<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.