Add services for adding and removing items to shopping list (#14574)

This commit is contained in:
Max Muth 2018-05-26 13:53:48 +02:00 committed by Sebastian Muszynski
parent 28d6910e56
commit a55fbd2be7
2 changed files with 54 additions and 1 deletions

View File

@ -556,3 +556,17 @@ xiaomi_aqara:
device_id:
description: Hardware address of the device to remove.
example: 158d0000000000
shopping_list:
add_item:
description: Adds an item to the shopping list.
fields:
name:
description: The name of the item to add.
example: Beer
complete_item:
description: Marks an item as completed in the shopping list. It does not remove the item.
fields:
name:
description: The name of the item to mark as completed.
example: Beer

View File

@ -14,6 +14,8 @@ from homeassistant.helpers import intent
import homeassistant.helpers.config_validation as cv
from homeassistant.util.json import load_json, save_json
ATTR_NAME = 'name'
DOMAIN = 'shopping_list'
DEPENDENCIES = ['http']
_LOGGER = logging.getLogger(__name__)
@ -23,20 +25,57 @@ INTENT_ADD_ITEM = 'HassShoppingListAddItem'
INTENT_LAST_ITEMS = 'HassShoppingListLastItems'
ITEM_UPDATE_SCHEMA = vol.Schema({
'complete': bool,
'name': str,
ATTR_NAME: str,
})
PERSISTENCE = '.shopping_list.json'
SERVICE_ADD_ITEM = 'add_item'
SERVICE_COMPLETE_ITEM = 'complete_item'
SERVICE_ITEM_SCHEMA = vol.Schema({
vol.Required(ATTR_NAME): vol.Any(None, cv.string)
})
@asyncio.coroutine
def async_setup(hass, config):
"""Initialize the shopping list."""
@asyncio.coroutine
def add_item_service(call):
"""Add an item with `name`."""
data = hass.data[DOMAIN]
name = call.data.get(ATTR_NAME)
if name is not None:
data.async_add(name)
@asyncio.coroutine
def complete_item_service(call):
"""Mark the item provided via `name` as completed."""
data = hass.data[DOMAIN]
name = call.data.get(ATTR_NAME)
if name is None:
return
try:
item = [item for item in data.items if item['name'] == name][0]
except IndexError:
_LOGGER.error("Removing of item failed: %s cannot be found", name)
else:
data.async_update(item['id'], {'name': name, 'complete': True})
data = hass.data[DOMAIN] = ShoppingData(hass)
yield from data.async_load()
intent.async_register(hass, AddItemIntent())
intent.async_register(hass, ListTopItemsIntent())
hass.services.async_register(
DOMAIN, SERVICE_ADD_ITEM, add_item_service, schema=SERVICE_ITEM_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_COMPLETE_ITEM, complete_item_service,
schema=SERVICE_ITEM_SCHEMA
)
hass.http.register_view(ShoppingListView)
hass.http.register_view(CreateShoppingListItemView)
hass.http.register_view(UpdateShoppingListItemView)