File: tools.py

package info (click to toggle)
python-aiopvapi 3.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 684 kB
  • sloc: python: 3,123; xml: 850; makefile: 5
file content (58 lines) | stat: -rw-r--r-- 1,751 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""Tools for converting data from powerview hub."""

import base64
import logging

from aiopvapi.helpers.constants import ATTR_ID

_LOGGER = logging.getLogger(__name__)


def unicode_to_base64(string):
    """Convert unicode to base64."""
    try:
        return base64.b64encode(string.encode()).decode("utf-8")
    except (base64.binascii.Error, UnicodeDecodeError) as e:
        # Handle the error and return the string
        _LOGGER.debug("Error encoding string '%s': %s", string, e)
        return string


def base64_to_unicode(string):
    """Convert base64 to unicode."""
    try:
        return base64.b64decode(string).decode("utf-8")
    except (base64.binascii.Error, UnicodeDecodeError) as e:
        # Handle the error and return the base64
        _LOGGER.debug("Error decoding base64 string '%s': %s", string, e)
        return string


def get_base_path(ip_address, url):
    """Convert url and ip to base path."""
    # Remove scheme if present
    ip_address = ip_address.split("://")[-1].strip("/")
    # clean up url (leading or trailing or multiple '/')
    urls = filter(lambda p: p != "", url.split("/"))
    # Put everything back together
    return "http://{}".format(join_path(ip_address, *urls))


def join_path(base, *parts: str):
    """Create urls from base path and additional parts."""
    _parts = "/".join((_part.strip("/") for _part in parts))
    # _parts = '/'.join(parts)
    if base.endswith("/"):
        url = base + _parts
    else:
        url = base + "/" + _parts
    return url


def get_raw_id(id_):
    """Create a dict with the resource id.

    This can serve as the minimal raw input for ie scene instantiation
    and allows for simple activation of that scene.
    """
    return {ATTR_ID: id_}