-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 27ab2fa
Showing
16 changed files
with
1,011 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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,38 @@ | ||
name: 🚀 Create release | ||
|
||
on: | ||
push: | ||
branches: | ||
- main | ||
paths: | ||
- custom_components/** | ||
- pyproject.toml | ||
- .github/** | ||
|
||
jobs: | ||
create_release: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: ⚙️ Setup Python | ||
uses: actions/setup-python@v2 | ||
with: | ||
python-version: 3.9 | ||
|
||
- name: 🔃 Checkout code | ||
uses: actions/checkout@v2 | ||
with: | ||
fetch-depth: 0 | ||
|
||
- name: ✅ Hassfest validation | ||
uses: home-assistant/actions/hassfest@master | ||
|
||
- name: ✅ HACS validation | ||
uses: hacs/action@main | ||
with: | ||
category: integration | ||
ignore: brands | ||
|
||
- name: 📢 Semantic Release | ||
uses: relekang/python-semantic-release@master | ||
with: | ||
github_token: ${{ secrets.GITHUB_TOKEN }} |
This file contains 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 @@ | ||
__pycache__ |
This file contains 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,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2021 Pavel Roslovets | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains 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,3 @@ | ||
# Jablotron RS485 Home Assistant Integration | ||
|
||
For connecting to a JA-121-T using a Modbus to Ethernet adapter. |
This file contains 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,16 @@ | ||
import logging | ||
|
||
PLATFORMS = ["light", "switch"] | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
async def async_setup(hass, config): | ||
"""Setup Lumic.""" | ||
_LOGGER.info("Setting up.") | ||
return True | ||
|
||
async def async_setup_entry(hass, config_entry): | ||
"""Set up entry.""" | ||
_LOGGER.info("Initializing config entry.") | ||
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) | ||
return True |
This file contains 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,193 @@ | ||
import asyncio | ||
import logging, os | ||
from requests.adapters import HTTPAdapter | ||
from requests_oauthlib import OAuth2Session | ||
from oauthlib.oauth2.rfc6749.errors import InvalidGrantError | ||
from oauthlib.oauth2 import BackendApplicationClient | ||
from requests.auth import HTTPBasicAuth | ||
from urllib3.util import Retry | ||
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET | ||
import json | ||
from gql import gql, Client | ||
from gql.transport.aiohttp import AIOHTTPTransport | ||
import time | ||
|
||
from .const import ( | ||
CONF_HOME_ID, | ||
API_ENDPOINT, | ||
OAUTH2_CALLBACK_PATH, | ||
OAUTH2_SCOPE, | ||
OAUTH2_FILE, | ||
OAUTH2_TOKEN_URL, | ||
QUERY_HOME_DEVICES, | ||
QUERY_DEVICE_BY_ID, | ||
MUTATION_DEVICE_PARAMETER_SET, | ||
) | ||
|
||
|
||
class LumicAPI: | ||
def __init__(self, auth, hass, config): | ||
self._auth = auth | ||
self._hass = hass | ||
self._config = config | ||
self._logger = logging.getLogger(__name__ + ":" + self.__class__.__name__) | ||
|
||
async def _request(self, query, vars): | ||
if self._auth is None: | ||
_LOGGER.error( | ||
"Cannot originate requets to Lumic API, not authenticated (no token)." | ||
) | ||
return None | ||
|
||
self._logger.debug("Query: %s", query) | ||
self._logger.debug("Vars: %s", vars) | ||
|
||
try: | ||
access_token = (await self._auth.getToken())["access_token"] | ||
self._logger.debug("Access Token: %s", access_token) | ||
|
||
transport = AIOHTTPTransport( | ||
url=API_ENDPOINT, | ||
headers={"Authorization": "Bearer %s" % access_token}, | ||
) | ||
session = Client(transport=transport) | ||
|
||
gql_query = gql(query) | ||
result = await self._hass.async_add_executor_job(session.execute, gql_query, vars) | ||
|
||
return result | ||
except Exception as e: | ||
self._logger.error("Error while executing GraphQL query:") | ||
self._logger.error(e) | ||
return {} | ||
|
||
async def sleep(self, _time): | ||
def _sleep(): | ||
time.sleep(_time) | ||
await self._hass.async_add_executor_job(_sleep) | ||
|
||
async def getHomeDevices(self, _type): | ||
result = await self._request(QUERY_HOME_DEVICES, { | ||
"id": self._config.get(CONF_HOME_ID) | ||
}) | ||
|
||
devices = [] | ||
for i in result["homeById"]["devices"]: | ||
if i["deviceType"] == _type: | ||
devices.append(i) | ||
|
||
return devices | ||
|
||
async def getDeviceById(self, id): | ||
try: | ||
result = await self._request(QUERY_DEVICE_BY_ID, { | ||
"id": id | ||
}) | ||
|
||
return result["deviceById"] | ||
except Exception as e: | ||
self._logger.error("Error while executing GraphQL query:") | ||
self._logger.error(e) | ||
return None | ||
|
||
async def setDeviceParameter(self, uuid, _type, value): | ||
try: | ||
await self._request(MUTATION_DEVICE_PARAMETER_SET, { | ||
"uuid": uuid, | ||
"type": _type, | ||
"value": value, | ||
}) | ||
return True | ||
except Exception as e: | ||
self._logger.error("Error while executing GraphQL mutation:") | ||
self._logger.error(e) | ||
return False | ||
|
||
|
||
class OAuth2Client: | ||
"""Define an OAuth2 client.""" | ||
|
||
def __init__(self, hass, config): | ||
self._oauth = None | ||
self._token = None | ||
self._mutex = asyncio.Lock() | ||
self._hass = hass | ||
self._config = config | ||
self._logger = logging.getLogger(__name__ + ":" + self.__class__.__name__) | ||
|
||
async def getToken(self): | ||
try: | ||
self._logger.debug("Acquiring lock for OAuth2 client...") | ||
await self._mutex.acquire() | ||
self._logger.debug("Acquired lock.") | ||
config_path = self._hass.config.path(OAUTH2_FILE) | ||
if os.path.isfile(config_path): | ||
with open(config_path, "r") as json_file: | ||
try: | ||
self._token = json.loads(json_file.read()) | ||
except Exception as e: | ||
self._logger.error("Error while reading token file:") | ||
self._logger.error(e) | ||
finally: | ||
json_file.close() | ||
|
||
def fetch_token(oauth): | ||
print(self._config.get(CONF_CLIENT_ID)) | ||
print(self._config.get(CONF_CLIENT_SECRET)) | ||
auth = HTTPBasicAuth(self._config.get(CONF_CLIENT_ID), self._config.get(CONF_CLIENT_SECRET)) | ||
return oauth.fetch_token( | ||
token_url=OAUTH2_TOKEN_URL, | ||
auth=auth, | ||
) | ||
|
||
def refresh_token(oauth): | ||
auth = HTTPBasicAuth(self._config.get(CONF_CLIENT_ID), self._config.get(CONF_CLIENT_SECRET)) | ||
return oauth.fetch_token( | ||
token_url=OAUTH2_TOKEN_URL, | ||
auth=auth, | ||
) | ||
|
||
if self._token is None: | ||
oauth = OAuth2Session( | ||
client=BackendApplicationClient( | ||
client_id=self._config.get(CONF_CLIENT_ID) | ||
) | ||
) | ||
self._token = await self._hass.async_add_executor_job( | ||
fetch_token, oauth | ||
) | ||
else: | ||
try: | ||
oauth = OAuth2Session( | ||
client=BackendApplicationClient( | ||
client_id=self._config.get(CONF_CLIENT_ID) | ||
), | ||
token=self._token, | ||
) | ||
self._token = await self._hass.async_add_executor_job( | ||
refresh_token, oauth | ||
) | ||
except Exception as e: | ||
self._logger.error( | ||
"Error while obtaining token via RefreshToken flow, reauthenticating:" | ||
) | ||
self._logger.error(e) | ||
oauth = OAuth2Session( | ||
client=BackendApplicationClient( | ||
client_id=self._config.get(CONF_CLIENT_ID) | ||
) | ||
) | ||
self._token = await self._hass.async_add_executor_job( | ||
fetch_token, oauth | ||
) | ||
|
||
with open(self._hass.config.path(OAUTH2_FILE), "w") as json_file: | ||
json_file.write(json.dumps(self._token)) | ||
json_file.close() | ||
|
||
self._logger.debug("Tokenset: %s", self._token) | ||
|
||
return self._token | ||
finally: | ||
self._mutex.release() | ||
self._logger.debug("Released lock.") |
This file contains 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,29 @@ | ||
from homeassistant import config_entries | ||
from .const import DOMAIN | ||
import voluptuous as vol | ||
import logging | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
class LumicConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): | ||
"""Example config flow.""" | ||
|
||
data = None | ||
|
||
async def async_step_user(self, info): | ||
"""Config flow step user.""" | ||
if info is not None: | ||
if not info.get("client_id") is None and not info.get("client_secret") is None and not info.get("home_id") is None: | ||
self.data = info | ||
return await self.async_step_finish() | ||
|
||
return self.async_show_form( | ||
step_id="user", data_schema=vol.Schema({ | ||
vol.Required("home_id"): int, | ||
vol.Required("client_id"): str, | ||
vol.Required("client_secret"): str, | ||
}) | ||
) | ||
|
||
async def async_step_finish(self, user_input=None): | ||
return self.async_create_entry(title="Lumic Lighting", data=self.data) |
This file contains 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,61 @@ | ||
"""Constants for the Lumic Lighting integration.""" | ||
|
||
DOMAIN = "lumic" | ||
|
||
API_ENDPOINT = "https://lumic-v1.apis.cedgetec.com/gql/graphql" | ||
|
||
OAUTH2_TOKEN_URL = ( | ||
"https://auth.cedgetec.com/auth/realms/cedgetec-id/protocol/openid-connect/token" | ||
) | ||
OAUTH2_CALLBACK_PATH = "/api/lumic" | ||
OAUTH2_SCOPE = ["lumic", "offline_access"] | ||
OAUTH2_FILE = ".lumic_oauth2.json" | ||
|
||
CONF_HOME_ID = "home_id" | ||
|
||
ATTR_DEVICE_TYPE_LIGHT = "LIGHT" | ||
ATTR_DEVICE_TYPE_SWITCH = "SWITCH" | ||
ATTR_DEVICE_TYPE_COVER = "ROLLER_SHUTTER" | ||
|
||
QUERY_HOME_DEVICES = """ | ||
query get_home_devices($id: Float!) { | ||
homeById(id: $id) { | ||
devices { | ||
id | ||
uuid | ||
name | ||
hardwareAddress | ||
deviceType | ||
room { | ||
name | ||
} | ||
} | ||
} | ||
} | ||
""" | ||
|
||
QUERY_DEVICE_BY_ID = """ | ||
query get_device_by_id($id: Float!) { | ||
deviceById(id: $id) { | ||
uuid | ||
name | ||
hardwareAddress | ||
deviceType | ||
room { | ||
name | ||
} | ||
deviceParameters { | ||
type | ||
valueType | ||
value | ||
valueNumeric | ||
} | ||
} | ||
} | ||
""" | ||
|
||
MUTATION_DEVICE_PARAMETER_SET = """ | ||
mutation device_parameter_set($uuid: String!, $type: ParameterType!, $value: String!) { | ||
deviceParameterSet(uuid: $uuid, type: $type, value: $value) | ||
} | ||
""" |
Oops, something went wrong.