Skip to content

Commit

Permalink
Add GitHub Actions Workflow, test and format (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
duhow authored Jan 20, 2023
1 parent 06540b5 commit 10206be
Show file tree
Hide file tree
Showing 12 changed files with 196 additions and 139 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
name: Test

on:
push:
branches:
- master
pull_request:

jobs:
test:
name: Valid integration
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Test HACS Action
uses: hacs/[email protected]
with:
category: integration
ignore: brands
- name: Test Home Assistant hassfest
uses: home-assistant/actions/hassfest@master
pre-commit:
name: pre-commit
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: '3.10'
- uses: pre-commit/[email protected]
50 changes: 50 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
default_install_hook_types:
- pre-commit
- commit-msg
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: check-docstring-first
- id: check-json
- id: pretty-format-json
args: [--autofix, --no-sort-keys]
- id: check-added-large-files
- id: check-yaml
- id: debug-statements
- id: end-of-file-fixer
- repo: https://github.com/myint/docformatter
rev: v1.5.1
hooks:
- id: docformatter
args: [--in-place]
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
hooks:
- id: pyupgrade
args: [--py38-plus]
- repo: https://github.com/asottile/reorder_python_imports
rev: v3.9.0
hooks:
- id: reorder-python-imports
args: [--py38-plus]
- repo: https://github.com/psf/black
rev: 22.12.0
hooks:
- id: black
language_version: python3
- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
- id: python-use-type-annotations
- repo: https://github.com/jumanjihouse/pre-commit-hook-yamlfmt
rev: 0.2.2
hooks:
- id: yamlfmt
args: [--mapping, '2', --sequence, '2', --offset, '0']
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Este `custom_component` permite importar los datos de [Aigües de Barcelona](https://www.aiguesdebarcelona.cat/) en [Home Assistant](https://www.home-assistant.io/).

Puedes ver el 🚰 consumo de agua que has hecho directamente en Home Assistant, y con esa información también puedes crear tus propias automatizaciones y avisos :)
Puedes ver el 🚰 consumo de agua que has hecho directamente en Home Assistant, y con esa información también puedes crear tus propias automatizaciones y avisos :)

Si te gusta el proyecto, dale a ⭐ **Star** ! 😊

Expand Down Expand Up @@ -30,7 +30,7 @@ Cuando lo tengas descargado, agrega la integración.

No soy un experto en Home Assistant, hay conceptos que son nuevos para mí en cuanto a la parte Developer. Así que puede que tarde en implementar las nuevas requests.

Se agradece cualquier Pull Request si tienes conocimiento en la materia :)
Se agradece cualquier Pull Request si tienes conocimiento en la materia :)

Si encuentras algún error, puedes abrir un Issue.

Expand Down
21 changes: 8 additions & 13 deletions custom_components/aigues_barcelona/__init__.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
""" Integration for Aigues de Barcelona. """

"""Integration for Aigues de Barcelona."""
from __future__ import annotations

import voluptuous as vol

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_USERNAME,
CONF_PASSWORD,
Platform,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.const import CONF_PASSWORD
from homeassistant.const import CONF_USERNAME
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession

from .const import DOMAIN
from .api import AiguesApiClient
from .const import DOMAIN

PLATFORMS = [Platform.SENSOR]


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

api = AiguesApiClient(entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD])
Expand All @@ -33,6 +27,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
Expand Down
48 changes: 22 additions & 26 deletions custom_components/aigues_barcelona/api.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import logging
import requests
import base64
import datetime
import json
import logging

import datetime
import requests

TIMEOUT = 60

_LOGGER: logging.Logger = logging.getLogger(__name__)


class AiguesApiClient:
def __init__(self, username, password, contract=None, session: requests.Session = None):
def __init__(
self, username, password, contract=None, session: requests.Session = None
):
if session is None:
session = requests.Session()
self.cli = session
Expand All @@ -20,7 +23,7 @@ def __init__(self, username, password, contract=None, session: requests.Session
self.headers = {
"Ocp-Apim-Subscription-Key": "3cca6060fee14bffa3450b19941bd954",
"Ocp-Apim-Trace": "false",
"Content-Type": "application/json; charset=UTF-8"
"Content-Type": "application/json; charset=UTF-8",
}
self._username = username
self._password = password
Expand All @@ -41,7 +44,7 @@ def _return_token_field(self, key):
data = token.split(".")[1]
_LOGGER.debug(data)
# add padding to avoid failures
data = base64.urlsafe_b64decode(data + '==')
data = base64.urlsafe_b64decode(data + "==")

return json.loads(data).get(key)

Expand All @@ -55,7 +58,7 @@ def _query(self, path, query=None, json=None, headers=None, method="GET"):
url=self._generate_url(path, query),
json=json,
headers=headers,
timeout=TIMEOUT
timeout=TIMEOUT,
)
_LOGGER.debug(f"Query done with code {resp.status_code}")
msg = resp.text
Expand Down Expand Up @@ -83,15 +86,12 @@ def login(self, user=None, password=None, recaptcha=None):
recaptcha = ""

path = "/ofex-login-api/auth/getToken"
query = {
"lang": "ca",
"recaptchaClientResponse": recaptcha
}
query = {"lang": "ca", "recaptchaClientResponse": recaptcha}
body = {
"scope": "ofex",
"companyIdentification": "",
"userIdentification": user,
"password": password
"password": password,
}
headers = {
"Content-Type": "application/json",
Expand Down Expand Up @@ -121,11 +121,7 @@ def profile(self, user=None):
user = self._return_token_field("name")

path = "/ofex-login-api/auth/getProfile"
query = {
"lang": "ca",
"userId": user,
"clientId": user
}
query = {"lang": "ca", "userId": user, "clientId": user}
headers = {
"Ocp-Apim-Subscription-Key": "6a98b8b8c7b243cda682a43f09e6588b;product=portlet-login-ofex"
}
Expand All @@ -142,11 +138,7 @@ def contracts(self, user=None, status=["ASSIGNED", "PENDING"]):
status = [status]

path = "/ofex-contracts-api/contracts"
query = {
"lang": "ca",
"userId": user,
"clientId": user
}
query = {"lang": "ca", "userId": user, "clientId": user}
for idx, stat in enumerate(status):
query[f"assignationStatus[{str(idx)}]"] = stat.upper()

Expand All @@ -162,7 +154,9 @@ def contract_id(self):
@property
def first_contract(self):
contract_ids = self.contract_id
assert len(contract_ids) == 1, "Provide a Contract ID to retrieve specific invoices"
assert (
len(contract_ids) == 1
), "Provide a Contract ID to retrieve specific invoices"
return contract_ids[0]

def invoices(self, contract=None, user=None, last_months=36, mode="ALL"):
Expand All @@ -178,7 +172,7 @@ def invoices(self, contract=None, user=None, last_months=36, mode="ALL"):
"clientId": user,
"lang": "ca",
"lastMonths": last_months,
"mode": mode
"mode": mode,
}

r = self._query(path, query)
Expand All @@ -189,7 +183,9 @@ def invoices(self, contract=None, user=None, last_months=36, mode="ALL"):
def invoices_debt(self, contract=None, user=None):
return self.invoices(contract, user, last_months=0, mode="DEBT")

def consumptions(self, date_from, date_to=None, contract=None, user=None, frequency="HOURLY"):
def consumptions(
self, date_from, date_to=None, contract=None, user=None, frequency="HOURLY"
):
if user is None:
user = self._return_token_field("name")
if contract is None:
Expand All @@ -213,7 +209,7 @@ def consumptions(self, date_from, date_to=None, contract=None, user=None, freque
"lang": "ca",
"fromDate": date_from,
"toDate": date_to,
"showNegativeValues": "false"
"showNegativeValues": "false",
}

r = self._query(path, query)
Expand Down
38 changes: 18 additions & 20 deletions custom_components/aigues_barcelona/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,31 @@
import logging
from typing import Any

import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant import config_entries, core
from homeassistant.exceptions import HomeAssistantError
from homeassistant.const import (
CONF_USERNAME,
CONF_PASSWORD,
CONF_SCAN_INTERVAL
)
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD
from homeassistant.const import CONF_USERNAME
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.aiohttp_client import async_create_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.exceptions import HomeAssistantError

from .const import (
DOMAIN,
CONF_CONTRACT
)
from .api import AiguesApiClient
from .const import CONF_CONTRACT
from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

ACCOUNT_CONFIG_SCHEMA = vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
#vol.Optional(CONF_SCAN_INTERVAL, default=const.DEFAULT_SCAN_PERIOD): cv.time_period_seconds
}
)

async def validate_credentials(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:

async def validate_credentials(
hass: HomeAssistant, data: dict[str, Any]
) -> dict[str, Any]:
username = data[CONF_USERNAME]
password = data[CONF_PASSWORD]

Expand All @@ -57,13 +53,12 @@ async def validate_credentials(hass: HomeAssistant, data: dict[str, Any]) -> dic
except Exception:
return False

class AiguesBarcelonaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):

class AiguesBarcelonaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1

async def async_step_user(
self,
user_input: dict[str, Any] | None = None
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle configuration step from UI."""
if user_input is None:
Expand Down Expand Up @@ -101,11 +96,14 @@ async def async_step_user(
step_id="user", data_schema=ACCOUNT_CONFIG_SCHEMA, errors=errors
)


class AlreadyConfigured(HomeAssistantError):
"""Error to indicate integration is already configured."""


class InvalidAuth(HomeAssistantError):
"""Error to indicate credentials are invalid"""
"""Error to indicate credentials are invalid."""


class InvalidUsername(HomeAssistantError):
"""Error to indicate invalid username"""
"""Error to indicate invalid username."""
2 changes: 1 addition & 1 deletion custom_components/aigues_barcelona/const.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""" Constants definition """
"""Constants definition."""

DOMAIN = "aigues_barcelona"

Expand Down
8 changes: 6 additions & 2 deletions custom_components/aigues_barcelona/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@
"integration_type": "hub",
"documentation": "https://github.com/duhow/hass-aigues-barcelona/tree/master",
"issue_tracker": "https://github.com/duhow/hass-aigues-barcelona/issues",
"dependencies": ["http"],
"codeowners": ["@duhow"],
"dependencies": [
"http"
],
"codeowners": [
"@duhow"
],
"requirements": [],
"iot_class": "cloud_polling"
}
Loading

0 comments on commit 10206be

Please sign in to comment.