Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
jcgoette committed Jul 25, 2021
0 parents commit 9081616
Show file tree
Hide file tree
Showing 14 changed files with 446 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .github/workflows/TODO.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
name: TODO

on: [push, pull_request]

jobs:
TODO:
runs-on: "ubuntu-latest"
steps:
- uses: "actions/checkout@master"
- uses: "alstr/todo-to-issue-action@v4.0-alpha"
with:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
10 changes: 10 additions & 0 deletions .github/workflows/homeassistant.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name: Home Assistant

on: [push, pull_request]

jobs:
hassfest:
runs-on: "ubuntu-latest"
steps:
- uses: "actions/checkout@v2"
- uses: "home-assistant/actions/hassfest@master"
29 changes: 29 additions & 0 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: Lint

on:
pull_request:
paths:
- "**.py"
push:
paths:
- "**.py"

jobs:
lint-isort:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: 3.8
- uses: jamescurtin/isort-action@master
with:
configuration: "--check-only --diff --profile black"
lint-black:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- uses: psf/black@stable
with:
options: ". --check"
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Python files
*.pyc
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Justin Goette

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.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# hi_mama_homeassistant

[![hacs_badge](https://img.shields.io/badge/HACS-Custom-orange.svg)](https://github.com/custom-components/hacs)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/)

This custom integration provides sensors for [HiMama](https://www.himama.com) within [Home Assistant](https://github.com/home-assistant/core).

## Installation

### HACS

1. Go to any of the sections (integrations, frontend, automation).
1. Click on the 3 dots in the top right corner.
1. Select "Custom repositories"
1. Add the URL (i.e., https://github.com/jcgoette/hi_mama_homeassistant) to the repository.
1. Select the Integration category.
1. Click the "ADD" button.

## Configuration

1. Go to "Configuration".
1. Click the "Integrations" button.
1. Click on the "ADD INTEGRATION" in the bottom right corner.
1. Search for HiMama
1. Enter email, password, and child ID and click "Submit"
21 changes: 21 additions & 0 deletions custom_components/hi_mama/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""HiMama integration"""
from .const import DOMAIN


async def async_setup_entry(hass, entry):
"""Set up HiMama platform from a ConfigEntry."""
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = entry.data

hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, "sensor")
)

return True


async def async_unload_entry(hass, entry):
"""Unload HiMama entity."""
await hass.config_entries.async_forward_entry_unload(entry, "sensor")

return True
25 changes: 25 additions & 0 deletions custom_components/hi_mama/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_EMAIL, CONF_ID, CONF_PASSWORD

from .const import ATTR_TITLE, DOMAIN


# TODO: better validation of data
# TODO: translations
class HiMamaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_user(self, user_input):
if user_input is not None:
return self.async_create_entry(title=ATTR_TITLE, data=user_input)

return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_EMAIL): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_ID): cv.string,
}
),
)
4 changes: 4 additions & 0 deletions custom_components/hi_mama/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
"""HiMama integration constants"""
DOMAIN = "hi_mama"

ATTR_TITLE = "HiMama"
11 changes: 11 additions & 0 deletions custom_components/hi_mama/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"codeowners": ["@jcgoette"],
"config_flow": true,
"documentation": "https://github.com/jcgoette/hi_mama_homeassistant",
"domain": "hi_mama",
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/jcgoette/hi_mama_homeassistant/issues",
"name": "HiMama",
"requirements": ["beautifulsoup4==4.9.3"],
"version": "v0.1.1"
}
139 changes: 139 additions & 0 deletions custom_components/hi_mama/pymama.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import re
from datetime import datetime

import requests
from bs4 import BeautifulSoup, Tag

ATTR_REGEX_DURATION = re.compile("\s\([0-9]{1,2}h[0-9]{1,2}m\)$")
ATTR_REGEX_SPLITTER = re.compile("\s?\-\s?")
ATTR_REGEX_TIME = re.compile("\d{1,2}\:\d{2}[a|p]m")
ATTR_REGEX_CSRF_TOKEN = re.compile('csrf\-token content\="(.+?)"')
ATTR_REGEX_REPORTS = re.compile('\<a href\="\/reports\/(\d+)"\>')
ATTR_DATE_FORMAT = "%A, %b %d, %Y"

session = requests.Session()


def response_noline(url: str) -> str:
"""Given a url, returns a Requests session reponse text with newlines removed"""
response = session.get(url)
response = response.text
response = response.replace("\n", "")
return response


def flatten_dict(unflat_dict: dict, date: datetime = None):
"""Given a dictionary, will create a generator to flatten into tuple"""
for key, value in unflat_dict.items():
if isinstance(value, dict):
yield from flatten_dict(value, value.get("Date", None))
if isinstance(value, tuple):
for rv in reversed(value):
yield (key, date, rv)


def get_unique_keys(flat_dict: tuple):
"""Given a dictionary flattened into a tuple, will create a generator to return unique values in slice 0"""
keys = set()
for fd in flat_dict:
keys.add(fd[0])
yield from keys


def get_latest_value(unique_keys, flat_dict):
"""Given unique values as keys and an ordered dictionary, flattened into a tuple, will create generator to return the last value per unique key"""
for uk in unique_keys:
for fd in flat_dict:
if uk in fd[0]:
yield fd
break


def report_parser(report):
if ATTR_REGEX_DURATION.search(report):
report = ATTR_REGEX_DURATION.sub("", report)
split_report = ATTR_REGEX_SPLITTER.split(report)
parsed_tuple = ()
for piece in split_report:
if ATTR_REGEX_TIME.search(piece):
try:
piece = datetime.strptime(piece, "%I:%M%p").time()
except:
pass
parsed_tuple = parsed_tuple + (piece,)
return parsed_tuple


def pymama(login: str, password: str, child_id: str) -> dict:
"""Given a login, password, and child_id, returns a dict containing all available reports and datapoints in dictionary format"""
response = response_noline("https://www.himama.com/login")

csrf_hidden_token = ATTR_REGEX_CSRF_TOKEN.search(response)[1]

data = [
("authenticity_token", csrf_hidden_token),
("user[login]", login),
("user[password]", password),
("commit", "Log In"),
]

response = session.post("https://www.himama.com/login", data=data)
response = response_noline(f"https://www.himama.com/accounts/{child_id}/reports")

reports = ATTR_REGEX_REPORTS.finditer(response)

child_dict = {}

for i, report in enumerate(reports):
report_dict = {}

response = response_noline(f"https://www.himama.com/reports/{report[1]}")
response = BeautifulSoup(response, "html.parser")

response_h2 = response.find_all("h2")
for h2 in response_h2:
h2_text = h2.get_text(strip=True)
h2_next_siblings = h2.next_sibling.contents
if "Preview" not in h2_text:
if "Report" in h2_text:
if i == 0:
child_dict["Child"] = h2_text.replace("'s Report", "")
date_str = h2_next_siblings[0]
date_obj = datetime.strptime(date_str, ATTR_DATE_FORMAT)
report_dict["Date"] = date_obj
else:
# setup to switch dictionary items to promote Fluids to key
report_dict_key = h2_text
tuple_default = ()
tuple_sub = ()
report_dict_value = tuple_default

for next_sibling in h2_next_siblings:
if isinstance(next_sibling, Tag):
if "Fluids" in next_sibling.get_text(strip=True):
report_dict_key = "Fluids"
report_dict_value = tuple_sub
continue
report_dict_value = report_dict_value + (
report_parser(next_sibling.get_text(strip=True)),
)
report_dict[report_dict_key] = report_dict_value
child_dict[f"Report {i}"] = report_dict

latest_dict = {}

child_unique_keys = [uk for uk in get_unique_keys(flatten_dict(child_dict.copy()))]
child_dict_flat = [fd for fd in flatten_dict(child_dict.copy())]

for lv in get_latest_value(child_unique_keys, child_dict_flat):
latest_dict[lv[0]] = dict([("Date", lv[1]), ("Value", lv[2])])

child_dict["Latest"] = latest_dict

return child_dict


if __name__ == "__main__":
import sys

print(pymama(sys.argv[1], sys.argv[2], sys.argv[3]))
Loading

0 comments on commit 9081616

Please sign in to comment.