Skip to content
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

Fix lint #4

Merged
merged 1 commit into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions custom_components/meridian_energy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""Support for Meridian Energy sensors"""
"""Support for Meridian Energy sensors."""

import logging

from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry

from .api import MeridianEnergyApi
from .const import DOMAIN, SENSOR_NAME, PLATFORMS
from .const import DOMAIN, PLATFORMS


_LOGGER = logging.getLogger(__name__)
Expand All @@ -21,4 +21,4 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
49 changes: 32 additions & 17 deletions custom_components/meridian_energy/api.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Meridian Energy API"""
"""Meridian Energy API."""

import logging
import requests
import json

from datetime import datetime, timedelta
from bs4 import BeautifulSoup
Expand All @@ -11,10 +11,13 @@


class MeridianEnergyApi:
"""Define the Meridian Energy API."""

def __init__(self, email, password):
"""Initialise the API."""
self._email = email
self._password = password
self._url_base = 'https://secure.meridianenergy.co.nz/'
self._url_base = "https://secure.meridianenergy.co.nz/"
self._token = None
self._data = None
self._session = requests.Session()
Expand All @@ -24,43 +27,55 @@ def token(self):
response = self._session.get(self._url_base)

if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
self._token = soup.find('input', {'name': 'authenticity_token'})['value']
soup = BeautifulSoup(response.text, "html.parser")
self._token = soup.find("input", {"name": "authenticity_token"})["value"]
_LOGGER.debug(f"Authenticity Token: {self._token}")
self.login()
else:
_LOGGER.error("Failed to retrieve the token page.")

def login(self):
"""Login to the Meridian Energy API."""
"""Login to the API."""
result = False
form_data = {
"authenticity_token": self._token,
"email": self._email,
"password": self._password,
"commit": "Login"
"commit": "Login",
}
loginResult = self._session.post(self._url_base + "customer/login", data=form_data)
loginResult = self._session.post(
self._url_base + "customer/login", data=form_data
)
if loginResult.status_code == 200:
_LOGGER.debug('Logged in')
_LOGGER.debug("Logged in")
self.get_data()
result = True
else:
_LOGGER.error('Could not login')
_LOGGER.error("Could not login")
return result

def get_data(self):
"""Get data from the API."""
# Get todays date
today = datetime.now().strftime('%d/%m/%Y')
seven_days_ago = (datetime.now() - timedelta(days=365)).strftime('%d/%m/%Y')

response = self._session.get(self._url_base + "reports/consumption_data/detailed_export?date_from=" + seven_days_ago + "&date_to=" + today + "&all_icps=&download=true")
today = datetime.now().strftime("%d/%m/%Y")
seven_days_ago = (datetime.now() - timedelta(days=365)).strftime("%d/%m/%Y")

response = self._session.get(
self._url_base
+ "reports/consumption_data/detailed_export?date_from="
+ seven_days_ago
+ "&date_to="
+ today
+ "&all_icps=&download=true"
)
if response.status_code == 200:
data = response.text
if not data:
_LOGGER.warning('Fetched consumption successfully but there was no data')
_LOGGER.warning(
"Fetched consumption successfully but there was no data"
)
return False
return data
else:
_LOGGER.error('Could not fetch consumption')
return data
_LOGGER.error("Could not fetch consumption")
return data
27 changes: 16 additions & 11 deletions custom_components/meridian_energy/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
"""Config flow for Meridian Energy integration."""

from homeassistant import config_entries
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
import homeassistant.helpers.config_validation as cv
import voluptuous as vol

from .const import (
DOMAIN,
SENSOR_NAME
)
from .const import DOMAIN, SENSOR_NAME


@config_entries.HANDLERS.register(DOMAIN)
class MeridianConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Define the config flow."""

VERSION = 1

async def async_step_user(self, user_input=None):
"""Show user form."""
if user_input is not None:
return self.async_create_entry(
title=SENSOR_NAME,
data={
CONF_EMAIL: user_input[CONF_EMAIL],
CONF_PASSWORD: user_input[CONF_PASSWORD]
}
CONF_PASSWORD: user_input[CONF_PASSWORD],
},
)

return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required(CONF_EMAIL): cv.string,
vol.Required(CONF_PASSWORD): cv.string
})
)
data_schema=vol.Schema(
{
vol.Required(CONF_EMAIL): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
}
),
)
9 changes: 5 additions & 4 deletions custom_components/meridian_energy/const.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""Constants for the Meridian Energy sensors"""
"""Constants for the Meridian Energy sensors."""

from homeassistant.const import Platform

DOMAIN = 'meridian_energy'
SENSOR_NAME = 'Meridian Energy'
DOMAIN = "meridian_energy"
SENSOR_NAME = "Meridian Energy"

PLATFORMS = [
Platform.SENSOR,
]
]
Loading