diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2024-02-25 23:07:46 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2024-02-25 23:07:46 +0300 |
commit | c4f87ddad4058c0f331446fdfd8d762b8fc26c18 (patch) | |
tree | 4c64e4b685670939c6401b4bdfdbeb6e4ed6a9fd /include/py/hikvision/util.py | |
parent | d43ca74063d8d931325c4498b02f40bb03e9e104 (diff) |
homekit: move hikvision and xmeye api stuff out of homekit package
Diffstat (limited to 'include/py/hikvision/util.py')
-rw-r--r-- | include/py/hikvision/util.py | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/include/py/hikvision/util.py b/include/py/hikvision/util.py new file mode 100644 index 0000000..581c6ea --- /dev/null +++ b/include/py/hikvision/util.py @@ -0,0 +1,48 @@ +import requests +import hashlib +import xml.etree.ElementTree as ET + + +def xml_to_dict(xml_data: str) -> dict: + # Parse the XML data + root = ET.fromstring(xml_data) + + # Function to remove namespace from the tag name + def remove_namespace(tag): + return tag.split('}')[-1] # Splits on '}' and returns the last part, the actual tag name without namespace + + # Function to recursively convert XML elements to a dictionary + def elem_to_dict(elem): + tag = remove_namespace(elem.tag) + elem_dict = {tag: {}} + + # If the element has attributes, add them to the dictionary + elem_dict[tag].update({'@' + remove_namespace(k): v for k, v in elem.attrib.items()}) + + # Handle the element's text content, if present and not just whitespace + text = elem.text.strip() if elem.text and elem.text.strip() else None + if text: + elem_dict[tag]['#text'] = text + + # Process child elements + for child in elem: + child_dict = elem_to_dict(child) + child_tag = remove_namespace(child.tag) + if child_tag not in elem_dict[tag]: + elem_dict[tag][child_tag] = [] + elem_dict[tag][child_tag].append(child_dict[child_tag]) + + # Simplify structure if there's only text or no children and no attributes + if len(elem_dict[tag]) == 1 and '#text' in elem_dict[tag]: + return {tag: elem_dict[tag]['#text']} + elif not elem_dict[tag]: + return {tag: ''} + + return elem_dict + + # Convert the root element to dictionary + return elem_to_dict(root) + + +def sha256_hex(input_string: str) -> str: + return hashlib.sha256(input_string.encode()).hexdigest() |