Exemplo n.º 1
0
def setup(hass, config):
    """Set up the Watson IoT Platform component."""
    from ibmiotf import gateway

    conf = config[DOMAIN]

    include = conf[CONF_INCLUDE]
    exclude = conf[CONF_EXCLUDE]
    whitelist_e = set(include[CONF_ENTITIES])
    whitelist_d = set(include[CONF_DOMAINS])
    blacklist_e = set(exclude[CONF_ENTITIES])
    blacklist_d = set(exclude[CONF_DOMAINS])

    client_args = {
        'org': conf[CONF_ORG],
        'type': conf[CONF_TYPE],
        'id': conf[CONF_ID],
        'auth-method': 'token',
        'auth-token': conf[CONF_TOKEN],
    }
    watson_gateway = gateway.Client(client_args)

    def event_to_json(event):
        """Add an event to the outgoing list."""
        state = event.data.get('new_state')
        if state is None or state.state in (
                STATE_UNKNOWN, '', STATE_UNAVAILABLE) or \
                state.entity_id in blacklist_e or state.domain in blacklist_d:
            return

        if (whitelist_e and state.entity_id not in whitelist_e) or \
                (whitelist_d and state.domain not in whitelist_d):
            return

        try:
            _state_as_value = float(state.state)
        except ValueError:
            _state_as_value = None

        if _state_as_value is None:
            try:
                _state_as_value = float(state_helper.state_as_number(state))
            except ValueError:
                _state_as_value = None

        out_event = {
            'tags': {
                'domain': state.domain,
                'entity_id': state.object_id,
            },
            'time': event.time_fired.isoformat(),
            'fields': {
                'state': state.state,
            }
        }
        if _state_as_value is not None:
            out_event['fields']['state_value'] = _state_as_value

        for key, value in state.attributes.items():
            if key != 'unit_of_measurement':
                # If the key is already in fields
                if key in out_event['fields']:
                    key = '{}_'.format(key)
                # For each value we try to cast it as float
                # But if we can not do it we store the value
                # as string
                try:
                    out_event['fields'][key] = float(value)
                except (ValueError, TypeError):
                    out_event['fields'][key] = str(value)

        return out_event

    instance = hass.data[DOMAIN] = WatsonIOTThread(
        hass, watson_gateway, event_to_json)
    instance.start()

    def shutdown(event):
        """Shut down the thread."""
        instance.queue.put(None)
        instance.join()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, shutdown)

    return True
Exemplo n.º 2
0
def setup(hass, config):
    """Set up the Watson IoT Platform component."""
    from ibmiotf import gateway

    conf = config[DOMAIN]

    include = conf[CONF_INCLUDE]
    exclude = conf[CONF_EXCLUDE]
    whitelist_e = set(include[CONF_ENTITIES])
    whitelist_d = set(include[CONF_DOMAINS])
    blacklist_e = set(exclude[CONF_ENTITIES])
    blacklist_d = set(exclude[CONF_DOMAINS])

    client_args = {
        "org": conf[CONF_ORG],
        "type": conf[CONF_TYPE],
        "id": conf[CONF_ID],
        "auth-method": "token",
        "auth-token": conf[CONF_TOKEN],
    }
    watson_gateway = gateway.Client(client_args)

    def event_to_json(event):
        """Add an event to the outgoing list."""
        state = event.data.get("new_state")
        if (
            state is None
            or state.state in (STATE_UNKNOWN, "", STATE_UNAVAILABLE)
            or state.entity_id in blacklist_e
            or state.domain in blacklist_d
        ):
            return

        if (whitelist_e and state.entity_id not in whitelist_e) or (
            whitelist_d and state.domain not in whitelist_d
        ):
            return

        try:
            _state_as_value = float(state.state)
        except ValueError:
            _state_as_value = None

        if _state_as_value is None:
            try:
                _state_as_value = float(state_helper.state_as_number(state))
            except ValueError:
                _state_as_value = None

        out_event = {
            "tags": {"domain": state.domain, "entity_id": state.object_id},
            "time": event.time_fired.isoformat(),
            "fields": {"state": state.state},
        }
        if _state_as_value is not None:
            out_event["fields"]["state_value"] = _state_as_value

        for key, value in state.attributes.items():
            if key != "unit_of_measurement":
                # If the key is already in fields
                if key in out_event["fields"]:
                    key = f"{key}_"
                # For each value we try to cast it as float
                # But if we can not do it we store the value
                # as string
                try:
                    out_event["fields"][key] = float(value)
                except (ValueError, TypeError):
                    out_event["fields"][key] = str(value)

        return out_event

    instance = hass.data[DOMAIN] = WatsonIOTThread(hass, watson_gateway, event_to_json)
    instance.start()

    def shutdown(event):
        """Shut down the thread."""
        instance.queue.put(None)
        instance.join()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, shutdown)

    return True