Uber sensor now works with UberPool and has a bit cleaner logic. Also upgraded to latest version of the SDK and switched all single quotes to double quotes (#2507)

This commit is contained in:
Robbie Trencheny 2016-07-12 21:52:21 -07:00 committed by Paulus Schoutsen
parent 8ed2c8e6a4
commit 011f82f9e3
2 changed files with 78 additions and 81 deletions

View File

@ -11,9 +11,9 @@ from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['uber_rides==0.2.1'] REQUIREMENTS = ["uber_rides==0.2.4"]
ICON = 'mdi:taxi' ICON = "mdi:taxi"
# Return cached results if last scan was less then this time ago. # Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
@ -21,35 +21,35 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Uber sensor.""" """Set up the Uber sensor."""
if None in (config.get('start_latitude'), config.get('start_longitude')): if None in (config.get("start_latitude"), config.get("start_longitude")):
_LOGGER.error( _LOGGER.error(
"You must set start latitude and longitude to use the Uber sensor!" "You must set start latitude and longitude to use the Uber sensor!"
) )
return False return False
if config.get('server_token') is None: if config.get("server_token") is None:
_LOGGER.error("You must set a server_token to use the Uber sensor!") _LOGGER.error("You must set a server_token to use the Uber sensor!")
return False return False
from uber_rides.session import Session from uber_rides.session import Session
session = Session(server_token=config.get('server_token')) session = Session(server_token=config.get("server_token"))
wanted_product_ids = config.get('product_ids') wanted_product_ids = config.get("product_ids")
dev = [] dev = []
timeandpriceest = UberEstimate(session, config['start_latitude'], timeandpriceest = UberEstimate(session, config["start_latitude"],
config['start_longitude'], config["start_longitude"],
config.get('end_latitude'), config.get("end_latitude"),
config.get('end_longitude')) config.get("end_longitude"))
for product_id, product in timeandpriceest.products.items(): for product_id, product in timeandpriceest.products.items():
if (wanted_product_ids is not None) and \ if (wanted_product_ids is not None) and \
(product_id not in wanted_product_ids): (product_id not in wanted_product_ids):
continue continue
dev.append(UberSensor('time', timeandpriceest, product_id, product)) dev.append(UberSensor("time", timeandpriceest, product_id, product))
is_metered = (product['price_details']['estimate'] == "Metered") if (product.get("price_details") is not None) and \
if 'price_details' in product and is_metered is False: product["price_details"]["estimate"] is not "Metered":
dev.append(UberSensor('price', timeandpriceest, dev.append(UberSensor("price", timeandpriceest,
product_id, product)) product_id, product))
add_devices(dev) add_devices(dev)
@ -64,30 +64,30 @@ class UberSensor(Entity):
self._product_id = product_id self._product_id = product_id
self._product = product self._product = product
self._sensortype = sensorType self._sensortype = sensorType
self._name = "{} {}".format(self._product['display_name'], self._name = "{} {}".format(self._product["display_name"],
self._sensortype) self._sensortype)
if self._sensortype == "time": if self._sensortype == "time":
self._unit_of_measurement = "min" self._unit_of_measurement = "min"
time_estimate = self._product.get('time_estimate_seconds', 0) time_estimate = self._product.get("time_estimate_seconds", 0)
self._state = int(time_estimate / 60) self._state = int(time_estimate / 60)
elif self._sensortype == "price": elif self._sensortype == "price":
if 'price_details' in self._product: if self._product.get("price_details") is not None:
price_details = self._product['price_details'] price_details = self._product["price_details"]
self._unit_of_measurement = price_details.get('currency_code', self._unit_of_measurement = price_details.get("currency_code")
'N/A') if price_details.get("low_estimate") is not None:
if 'low_estimate' in price_details: statekey = "minimum"
statekey = 'minimum'
else: else:
statekey = 'low_estimate' statekey = "low_estimate"
self._state = int(price_details.get(statekey, 0)) self._state = int(price_details.get(statekey, 0))
else: else:
self._unit_of_measurement = 'N/A'
self._state = 0 self._state = 0
self.update() self.update()
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
if "uber" not in self._name.lower():
self._name = "Uber{}".format(self._name)
return self._name return self._name
@property @property
@ -103,43 +103,41 @@ class UberSensor(Entity):
@property @property
def device_state_attributes(self): def device_state_attributes(self):
"""Return the state attributes.""" """Return the state attributes."""
time_estimate = self._product.get('time_estimate_seconds', 'N/A') time_estimate = self._product.get("time_estimate_seconds")
params = { params = {
'Product ID': self._product['product_id'], "Product ID": self._product["product_id"],
'Product short description': self._product['short_description'], "Product short description": self._product["short_description"],
'Product display name': self._product['display_name'], "Product display name": self._product["display_name"],
'Product description': self._product['description'], "Product description": self._product["description"],
'Pickup time estimate (in seconds)': time_estimate, "Pickup time estimate (in seconds)": time_estimate,
'Trip duration (in seconds)': self._product.get('duration', 'N/A'), "Trip duration (in seconds)": self._product.get("duration"),
'Vehicle Capacity': self._product['capacity'] "Vehicle Capacity": self._product["capacity"]
} }
if 'price_details' in self._product: if self._product.get("price_details") is not None:
price_details = self._product['price_details'] price_details = self._product["price_details"]
distance_key = 'Trip distance (in {}s)'.format(price_details[ dunit = price_details.get("distance_unit")
'distance_unit']) distance_key = "Trip distance (in {}s)".format(dunit)
distance_val = self._product.get('distance') distance_val = self._product.get("distance")
params['Minimum price'] = price_details['minimum'], params["Cost per minute"] = price_details.get("cost_per_minute")
params['Cost per minute'] = price_details['cost_per_minute'], params["Distance units"] = price_details.get("distance_unit")
params['Distance units'] = price_details['distance_unit'], params["Cancellation fee"] = price_details.get("cancellation_fee")
params['Cancellation fee'] = price_details['cancellation_fee'], cpd = price_details.get("cost_per_distance")
params['Cost per distance'] = price_details['cost_per_distance'], params["Cost per distance"] = cpd
params['Base price'] = price_details['base'], params["Base price"] = price_details.get("base")
params['Price estimate'] = price_details.get('estimate', 'N/A'), params["Minimum price"] = price_details.get("minimum")
params['Price currency code'] = price_details.get('currency_code'), params["Price estimate"] = price_details.get("estimate")
params['High price estimate'] = price_details.get('high_estimate', params["Price currency code"] = price_details.get("currency_code")
'N/A'), params["High price estimate"] = price_details.get("high_estimate")
params['Low price estimate'] = price_details.get('low_estimate', params["Low price estimate"] = price_details.get("low_estimate")
'N/A'), params["Surge multiplier"] = price_details.get("surge_multiplier")
params['Surge multiplier'] = price_details.get('surge_multiplier',
'N/A')
else: else:
distance_key = 'Trip distance (in miles)' distance_key = "Trip distance (in miles)"
distance_val = self._product.get('distance', 'N/A') distance_val = self._product.get("distance")
params[distance_key] = distance_val params[distance_key] = distance_val
return params return {k: v for k, v in params.items() if v is not None}
@property @property
def icon(self): def icon(self):
@ -152,13 +150,13 @@ class UberSensor(Entity):
self.data.update() self.data.update()
self._product = self.data.products[self._product_id] self._product = self.data.products[self._product_id]
if self._sensortype == "time": if self._sensortype == "time":
time_estimate = self._product.get('time_estimate_seconds', 0) time_estimate = self._product.get("time_estimate_seconds", 0)
self._state = int(time_estimate / 60) self._state = int(time_estimate / 60)
elif self._sensortype == "price": elif self._sensortype == "price":
price_details = self._product.get('price_details') price_details = self._product.get("price_details")
if price_details is not None: if price_details is not None:
min_price = price_details.get('minimum') min_price = price_details.get("minimum")
self._state = int(price_details.get('low_estimate', min_price)) self._state = int(price_details.get("low_estimate", min_price))
else: else:
self._state = 0 self._state = 0
@ -190,40 +188,39 @@ class UberEstimate(object):
products_response = client.get_products( products_response = client.get_products(
self.start_latitude, self.start_longitude) self.start_latitude, self.start_longitude)
products = products_response.json.get('products') products = products_response.json.get("products")
for product in products: for product in products:
self.products[product['product_id']] = product self.products[product["product_id"]] = product
if self.end_latitude is not None and self.end_longitude is not None: if self.end_latitude is not None and self.end_longitude is not None:
price_response = client.get_price_estimates( price_response = client.get_price_estimates(
self.start_latitude, self.start_latitude, self.start_longitude,
self.start_longitude, self.end_latitude, self.end_longitude)
self.end_latitude,
self.end_longitude)
prices = price_response.json.get('prices', []) prices = price_response.json.get("prices", [])
for price in prices: for price in prices:
product = self.products[price['product_id']] product = self.products[price["product_id"]]
product["duration"] = price.get("duration", "0")
product["distance"] = price.get("distance", "0")
price_details = product.get("price_details") price_details = product.get("price_details")
product["duration"] = price.get('duration', '0') if product.get("price_details") is None:
product["distance"] = price.get('distance', '0') price_details = {}
if price_details is not None: price_details["estimate"] = price.get("estimate", "0")
price_details["estimate"] = price.get('estimate', price_details["high_estimate"] = price.get("high_estimate",
'0') "0")
price_details["high_estimate"] = price.get('high_estimate', price_details["low_estimate"] = price.get("low_estimate", "0")
'0') price_details["currency_code"] = price.get("currency_code")
price_details["low_estimate"] = price.get('low_estimate', surge_multiplier = price.get("surge_multiplier", "0")
'0') price_details["surge_multiplier"] = surge_multiplier
surge_multiplier = price.get('surge_multiplier', '0') product["price_details"] = price_details
price_details["surge_multiplier"] = surge_multiplier
estimate_response = client.get_pickup_time_estimates( estimate_response = client.get_pickup_time_estimates(
self.start_latitude, self.start_longitude) self.start_latitude, self.start_longitude)
estimates = estimate_response.json.get('times') estimates = estimate_response.json.get("times")
for estimate in estimates: for estimate in estimates:
self.products[estimate['product_id']][ self.products[estimate["product_id"]][
"time_estimate_seconds"] = estimate.get('estimate', '0') "time_estimate_seconds"] = estimate.get("estimate", "0")

View File

@ -417,7 +417,7 @@ transmissionrpc==0.11
twilio==5.4.0 twilio==5.4.0
# homeassistant.components.sensor.uber # homeassistant.components.sensor.uber
uber_rides==0.2.1 uber_rides==0.2.4
# homeassistant.components.device_tracker.unifi # homeassistant.components.device_tracker.unifi
unifi==1.2.5 unifi==1.2.5