-
-
Notifications
You must be signed in to change notification settings - Fork 38.3k
Add Google pubsub component #20049
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add Google pubsub component #20049
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4ce0813
Add google pubsub component
timvancann c6dd89a
Add tests and requirements
timvancann f8f3d6f
Make python3.5 compatible
timvancann cb66716
Fix linting
timvancann a85faf6
Fix pubsub test
timvancann 3a6fdf3
Code review comments
timvancann e968410
Add missing docstrings
timvancann 20022ca
Merge branch 'dev' into google_pubsub
timvancann 81d7b55
Update requirements_all
timvancann c08a13a
Code review comment
timvancann File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| """ | ||
| Support for Google Cloud Pub/Sub. | ||
|
|
||
| For more details about this component, please refer to the documentation at | ||
| https://home-assistant.io/components/google_pubsub/ | ||
| """ | ||
| import datetime | ||
| import json | ||
| import logging | ||
| import os | ||
| from typing import Any, Dict | ||
|
|
||
| import voluptuous as vol | ||
|
|
||
| from homeassistant.const import ( | ||
| EVENT_STATE_CHANGED, STATE_UNAVAILABLE, STATE_UNKNOWN) | ||
| from homeassistant.core import Event, HomeAssistant | ||
| import homeassistant.helpers.config_validation as cv | ||
| from homeassistant.helpers.entityfilter import FILTER_SCHEMA | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
| REQUIREMENTS = ['google-cloud-pubsub==0.39.1'] | ||
|
|
||
| DOMAIN = 'google_pubsub' | ||
|
|
||
| CONF_PROJECT_ID = 'project_id' | ||
| CONF_TOPIC_NAME = 'topic_name' | ||
| CONF_SERVICE_PRINCIPAL = 'credentials_json' | ||
| CONF_FILTER = 'filter' | ||
|
|
||
| CONFIG_SCHEMA = vol.Schema({ | ||
| DOMAIN: vol.Schema({ | ||
| vol.Required(CONF_PROJECT_ID): cv.string, | ||
| vol.Required(CONF_TOPIC_NAME): cv.string, | ||
| vol.Required(CONF_SERVICE_PRINCIPAL): cv.string, | ||
| vol.Required(CONF_FILTER): FILTER_SCHEMA | ||
| }), | ||
| }, extra=vol.ALLOW_EXTRA) | ||
|
|
||
|
|
||
| def setup(hass: HomeAssistant, yaml_config: Dict[str, Any]): | ||
|
timvancann marked this conversation as resolved.
|
||
| """Activate Google Pub/Sub component.""" | ||
| from google.cloud import pubsub_v1 | ||
|
|
||
| config = yaml_config[DOMAIN] | ||
| project_id = config[CONF_PROJECT_ID] | ||
| topic_name = config[CONF_TOPIC_NAME] | ||
| service_principal_path = os.path.join(hass.config.config_dir, | ||
| config[CONF_SERVICE_PRINCIPAL]) | ||
|
|
||
| if not os.path.isfile(service_principal_path): | ||
| _LOGGER.error("Path to credentials file cannot be found") | ||
| return False | ||
|
|
||
| entities_filter = config[CONF_FILTER] | ||
|
|
||
| publisher = (pubsub_v1 | ||
| .PublisherClient | ||
| .from_service_account_json(service_principal_path) | ||
| ) | ||
|
|
||
| topic_path = publisher.topic_path(project_id, # pylint: disable=E1101 | ||
|
MartinHjelmare marked this conversation as resolved.
|
||
| topic_name) | ||
|
|
||
| encoder = DateTimeJSONEncoder() | ||
|
|
||
| def send_to_pubsub(event: Event): | ||
|
timvancann marked this conversation as resolved.
|
||
| """Send states to Pub/Sub.""" | ||
| state = event.data.get('new_state') | ||
| if (state is None | ||
| or state.state in (STATE_UNKNOWN, '', STATE_UNAVAILABLE) | ||
| or not entities_filter(state.entity_id)): | ||
| return | ||
|
|
||
| as_dict = state.as_dict() | ||
| data = json.dumps( | ||
| obj=as_dict, | ||
| default=encoder.encode | ||
| ).encode('utf-8') | ||
|
|
||
| publisher.publish(topic_path, data=data) | ||
|
timvancann marked this conversation as resolved.
|
||
|
|
||
| hass.bus.listen(EVENT_STATE_CHANGED, send_to_pubsub) | ||
|
|
||
| return True | ||
|
|
||
|
|
||
| class DateTimeJSONEncoder(json.JSONEncoder): | ||
|
timvancann marked this conversation as resolved.
|
||
| """Encode python objects. | ||
|
|
||
| Additionally add encoding for datetime objects as isoformat. | ||
| """ | ||
|
|
||
| def default(self, o): # pylint: disable=E0202 | ||
| """Implement encoding logic.""" | ||
| if isinstance(o, datetime.datetime): | ||
| return o.isoformat() | ||
| return super().default(o) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| """The tests for the Google Pub/Sub component.""" | ||
| from datetime import datetime | ||
|
|
||
| from homeassistant.components.google_pubsub import ( | ||
| DateTimeJSONEncoder as victim) | ||
|
|
||
|
|
||
| class TestDateTimeJSONEncoder(object): | ||
| """Bundle for DateTimeJSONEncoder tests.""" | ||
|
|
||
| def test_datetime(self): | ||
| """Test datetime encoding.""" | ||
| time = datetime(2019, 1, 13, 12, 30, 5) | ||
| assert victim().encode(time) == '"2019-01-13T12:30:05"' | ||
|
|
||
| def test_no_datetime(self): | ||
| """Test integer encoding.""" | ||
| assert victim().encode(42) == '42' | ||
|
|
||
| def test_nested(self): | ||
| """Test dictionary encoding.""" | ||
| assert victim().encode({'foo': 'bar'}) == '{"foo": "bar"}' |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.