示例#1
0
def add_to_registry(item: 'HABApp.openhab.items.OpenhabItem', set_value=False):
    name = item.name
    for grp in item.groups:
        MEMBERS.setdefault(grp, set()).add(name)

    if not Items.item_exists(name):
        return Items.add_item(item)

    existing = Items.get_item(name)
    if isinstance(existing, item.__class__):
        # If we load directly through the API and not through an event we have to set the value
        if set_value:
            existing.set_value(item.value)

        # remove old groups
        for grp in set(existing.groups) - set(item.groups):
            MEMBERS.get(grp, set()).discard(name)

        # same type - it was only an item update (e.g. label)!
        existing.tags = item.tags
        existing.groups = item.groups
        return None

    log_warning(
        log,
        f'Item type changed from {existing.__class__} to {item.__class__}')

    # Replace existing item with the updated definition
    Items.pop_item(name)
    Items.add_item(item)
    async def on_connect_function(self):
        data = await async_get_items(disconnect_on_error=True,
                                     all_metadata=True)
        if data is None:
            return None

        fresh_item_sync()

        found_items = len(data)
        for _dict in data:
            item_name = _dict['name']
            new_item = map_item(
                item_name, _dict['type'], _dict['state'],
                frozenset(_dict['tags']), frozenset(_dict['groupNames']),
                _dict.get('metadata',
                          {}))  # type: HABApp.openhab.items.OpenhabItem
            if new_item is None:
                continue
            add_to_registry(new_item, True)

        # remove items which are no longer available
        ist = set(Items.get_all_item_names())
        soll = {k['name'] for k in data}
        for k in ist - soll:
            if isinstance(Items.get_item(k), HABApp.openhab.items.OpenhabItem):
                Items.pop_item(k)

        log.info(f'Updated {found_items:d} Items')

        # try to update things, too
        data = await async_get_things(disconnect_on_error=True)
        if data is None:
            return None

        Thing = HABApp.openhab.items.Thing
        for t_dict in data:
            name = t_dict['UID']
            try:
                thing = Items.get_item(name)
                if not isinstance(thing, Thing):
                    log.warning(
                        f'Item {name} has the wrong type ({type(thing)}), expected Thing'
                    )
                    thing = Thing(name)
            except Items.ItemNotFoundException:
                thing = Thing(name)

            thing.status = t_dict['statusInfo']['status']
            Items.add_item(thing)

        # remove things which were deleted
        ist = set(Items.get_all_item_names())
        soll = {k['UID'] for k in data}
        for k in ist - soll:
            if isinstance(Items.get_item(k), Thing):
                Items.pop_item(k)

        log.info(f'Updated {len(data):d} Things')
        return None
def test_pop(clean_reg):
    Items.add_item(Item('test'))
    assert Items.item_exists('test')

    with pytest.raises(Items.ItemNotFoundException):
        Items.pop_item('asdfadsf')

    Items.pop_item('test')
    assert not Items.item_exists('test')
示例#4
0
    def test_factories(self):
        cls = self.CLS

        ITEM_NAME = 'testitem'
        if Items.item_exists(ITEM_NAME):
            Items.pop_item(ITEM_NAME)

        c = cls.get_create_item(name=ITEM_NAME, **self.TEST_CREATE_ITEM)
        assert isinstance(c, cls)

        assert isinstance(cls.get_item(name=ITEM_NAME), cls)
示例#5
0
def on_sse_event(event_dict: dict):

    # Lookup corresponding OpenHAB event
    event = get_event(event_dict)

    # Update item in registry BEFORE posting to the event bus
    # so the items have the correct state when we process the event in a rule
    try:
        if isinstance(event, HABApp.core.events.ValueUpdateEvent):
            __item = Items.get_item(
                event.name)  # type: HABApp.core.items.base_item.BaseValueItem
            __item.set_value(event.value)
            HABApp.core.EventBus.post_event(event.name, event)
            return None
        elif isinstance(event, HABApp.openhab.events.ThingStatusInfoEvent):
            __thing = Items.get_item(
                event.name)  # type: HABApp.openhab.items.Thing
            __thing.process_event(event)
            HABApp.core.EventBus.post_event(event.name, event)
            return None
    except HABApp.core.Items.ItemNotFoundException:
        pass

    # Events which change the ItemRegistry
    if isinstance(event, (HABApp.openhab.events.ItemAddedEvent,
                          HABApp.openhab.events.ItemUpdatedEvent)):
        item = map_item(event.name, event.type, 'NULL')
        if item is None:
            return None

        # check already existing item so we can print a warning if something changes
        try:
            existing_item = Items.get_item(item.name)
            if isinstance(existing_item, item.__class__):
                # it's the same item class so we don't replace it!
                item = existing_item
            else:
                log.warning(
                    f'Item changed type from {existing_item.__class__} to {item.__class__}'
                )
        except Items.ItemNotFoundException:
            pass

        # always overwrite with new definition
        Items.set_item(item)

    elif isinstance(event, HABApp.openhab.events.ItemRemovedEvent):
        Items.pop_item(event.name)

    # Send Event to Event Bus
    HABApp.core.EventBus.post_event(event.name, event)
    return None
示例#6
0
def test_retain_create():
    topic = '/test/creation'

    assert not Items.item_exists(topic)
    process_msg(None, None, MqttDummyMsg(topic, 'aaa', retain=False))
    assert not Items.item_exists(topic)

    # Retain True will create the item
    process_msg(None, None, MqttDummyMsg(topic, 'adsf123', retain=True))
    assert Items.item_exists(topic)
    assert Items.get_item(topic).value == 'adsf123'

    Items.pop_item(topic)
示例#7
0
def remove_from_registry(name: str):
    if not Items.item_exists(name):
        return None

    item = Items.get_item(name)  # type: HABApp.openhab.items.OpenhabItem
    for grp in item.groups:
        MEMBERS.get(grp, set()).discard(name)

    if isinstance(item, HABApp.openhab.items.GroupItem):
        MEMBERS.pop(name, None)

    Items.pop_item(name)
    return None
    def test_item(self):

        NAME = 'test'
        created_item = Item(NAME)
        Items.add_item(created_item)

        self.assertTrue(Items.item_exists(NAME))
        self.assertIs(created_item, Items.get_item(NAME))

        self.assertEqual(Items.get_all_item_names(), [NAME])
        self.assertEqual(Items.get_all_items(), [created_item])

        self.assertIs(created_item, Items.pop_item(NAME))
        self.assertEqual(Items.get_all_items(), [])
示例#9
0
    async def on_connect_function(self):
        data = await async_get_items()
        if data is None:
            return None

        found_items = len(data)
        for _dict in data:
            item_name = _dict['name']
            new_item = map_item(item_name, _dict['type'], _dict['state'])
            if new_item is None:
                continue

            try:
                # if the item already exists and it has the correct type just update its state
                # Since we load the items before we load the rules this should actually never happen
                existing_item = Items.get_item(
                    item_name)  # type: HABApp.core.items.BaseValueItem
                if isinstance(existing_item, new_item.__class__):
                    existing_item.set_value(
                        new_item.value
                    )  # use the converted state from the new item here
                    new_item = existing_item
            except Items.ItemNotFoundException:
                pass

            # create new item or change item type
            Items.set_item(new_item)

        # remove items which are no longer available
        ist = set(Items.get_all_item_names())
        soll = {k['name'] for k in data}
        for k in ist - soll:
            if isinstance(Items.get_item(k), HABApp.openhab.items.OpenhabItem):
                Items.pop_item(k)

        log.info(f'Updated {found_items:d} Items')

        # try to update things, too
        data = await async_get_things()
        if data is None:
            return None

        Thing = HABApp.openhab.items.Thing
        for t_dict in data:
            name = t_dict['UID']
            try:
                thing = HABApp.core.Items.get_item(name)
                if not isinstance(thing, Thing):
                    log.warning(
                        f'Item {name} has the wrong type ({type(thing)}), expected Thing'
                    )
                    thing = Thing(name)
            except HABApp.core.Items.ItemNotFoundException:
                thing = Thing(name)

            thing.status = t_dict['statusInfo']['status']
            HABApp.core.Items.set_item(thing)

        # remove things which were deleted
        ist = set(HABApp.core.Items.get_all_item_names())
        soll = {k['UID'] for k in data}
        for k in ist - soll:
            if isinstance(HABApp.core.Items.get_item(k), Thing):
                HABApp.core.Items.pop_item(k)

        log.info(f'Updated {len(data):d} Things')
        return None
示例#10
0
 def tearDown(self) -> None:
     for name in Items.get_all_item_names():
         Items.pop_item(name)
示例#11
0
 def setUp(self) -> None:
     for name in Items.get_all_item_names():
         Items.pop_item(name)