Skip to content

Commit 6cf5437

Browse files
author
Khole
authored
Merge pull request #7 from Pyhive/2020.1_code
2020.1 code
2 parents 6230071 + e42300d commit 6cf5437

31 files changed

Lines changed: 7630 additions & 3345 deletions

.travis.yml

Lines changed: 0 additions & 14 deletions
This file was deleted.

MANIFEST.in

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
recursive-include pyhiveapi *
2+
include requirements.txt
3+
include requirements_test.txt

examples/pyhiveapi_example_1.py

Lines changed: 0 additions & 126 deletions
This file was deleted.

pyhiveapi/__init__.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,27 @@
1-
"""__init__.py"""
2-
from .pyhiveapi import Pyhiveapi
1+
"""__init__.py"""
2+
from .hive import Hive
3+
from .hive_session import Session
4+
from .const import *
5+
from .helper import HiveHelper
6+
from .client import Client
7+
from .hive_api import HiveApi
8+
from .hive_async_api import HiveAsync
9+
from .hive_auth_async import HiveAuthAsync
10+
11+
12+
def getMessage(__message, __type):
13+
"""
14+
Gets a message
15+
"""
16+
from cryptography.fernet import Fernet
17+
import os
18+
import json
19+
20+
__key = open(os.path.dirname(os.path.realpath(
21+
__file__)) + "/.info.key", "rb").read()
22+
__f = Fernet(__key)
23+
__result = __f.decrypt(__message).decode()
24+
25+
if __type == "JSON":
26+
__result = json.loads(__result)
27+
return __result

pyhiveapi/action.py

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
"""Hive Action Module."""
2+
from .hive_session import Session
3+
from .hive_data import Data
4+
5+
6+
class Action(Session):
7+
"""Hive Action Code."""
8+
actionType = 'Actions'
9+
10+
async def get_action(self, device):
11+
"""Get smart plug current power usage."""
12+
await self.logger.log(device["hiveID"], self.actionType, "Getting action data.")
13+
dev_data = {}
14+
15+
if device["hiveID"] in Data.actions:
16+
dev_data = {"hiveID": device["hiveID"],
17+
"hiveName": device["hiveName"],
18+
"hiveType": device["hiveType"],
19+
"haName": device["haName"],
20+
"haType": device["haType"],
21+
"status": {
22+
"state": await self.get_state(device)},
23+
"power_usage": None,
24+
"deviceData": {},
25+
"custom": device.get("custom", None)
26+
}
27+
28+
await self.logger.log(device["hiveID"], self.actionType,
29+
"action update {0}", info=[dev_data["status"]])
30+
Data.ha_devices.update({device['hiveID']: dev_data})
31+
return dev_data
32+
else:
33+
exists = Data.actions.get('hiveID', False)
34+
if exists == False:
35+
return 'REMOVE'
36+
return device
37+
38+
async def get_state(self, device):
39+
"""Get action state."""
40+
await self.logger.log(device["hiveID"], self.actionType + "_Extra", "Getting state")
41+
state = None
42+
final = None
43+
44+
if device["hiveID"] in Data.actions:
45+
data = Data.actions[device["hiveID"]]
46+
final = data["enabled"]
47+
await self.logger.log(device["hiveID"], self.actionType + "_Extra", "Status is {0}", info=[final])
48+
if device["hiveID"] in Data.errorList:
49+
Data.errorList.pop(device["hiveID"])
50+
else:
51+
await self.logger.error_check(device["hiveID"], "ERROR", "Failed")
52+
53+
return final
54+
55+
async def turn_on(self, device):
56+
"""Set action turn on."""
57+
import json
58+
await self.logger.log(device["hiveID"], self.actionType + "_Extra", "Enabling action")
59+
final = False
60+
61+
if device["hiveID"] in Data.actions:
62+
await self.hiveRefreshTokens()
63+
data = Data.actions[device["hiveID"]]
64+
data.update({"enabled": True})
65+
send = json.dumps(data)
66+
resp = await self.api.set_action(device["hiveID"], send)
67+
if resp["original"] == 200:
68+
final = True
69+
await self.getDevices(device["hiveID"])
70+
await self.logger.log(device["hiveID"], "API", "Enabled action - " + device["hiveName"])
71+
else:
72+
await self.logger.error_check(
73+
device["hiveID"], "ERROR", "Failed_API", resp=resp["original"])
74+
75+
return final
76+
77+
async def turn_off(self, device):
78+
"""Set action to turn off."""
79+
import json
80+
await self.logger.log(device["hiveID"], self.actionType + "_Extra", "Disabling action")
81+
final = False
82+
83+
if device["hiveID"] in Data.actions:
84+
await self.hiveRefreshTokens()
85+
data = Data.actions[device["hiveID"]]
86+
data.update({"enabled": False})
87+
send = json.dumps(data)
88+
resp = await self.api.set_action(device["hiveID"], send)
89+
if resp["original"] == 200:
90+
final = True
91+
await self.getDevices(device["hiveID"])
92+
await self.logger.log(device["hiveID"], "API", "Disabled action - " + device["hiveName"])
93+
else:
94+
await self.logger.error_check(
95+
device["hiveID"], "ERROR", "Failed_API", resp=resp["original"])
96+
97+
return final

pyhiveapi/client.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""Define a client to interact with the Hive APIs."""
2+
import logging
3+
from typing import Optional
4+
5+
from aiohttp import ClientSession
6+
from .hive_async_api import HiveAsync
7+
8+
_LOGGER = logging.getLogger(__name__)
9+
10+
DEFAULT_API_VERSION = 1
11+
12+
13+
class Client: # pylint: disable=too-few-public-methods
14+
"""Define the client."""
15+
16+
def __init__(self, session: Optional[ClientSession] = None,):
17+
"""Initialize."""
18+
client = HiveAsync(session)

pyhiveapi/const.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""Constants for Pyhiveapi."""
2+
PACKAGE_NAME = "Pyhiveapi"
3+
PACKAGE_DIR = "/pyhiveapi/"

pyhiveapi/custom_logging.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
"""Custom Logging Module."""
2+
import logging
3+
4+
from datetime import datetime
5+
from .hive_data import Data
6+
from .helper import HiveHelper
7+
8+
_LOGGER = logging.getLogger(__name__)
9+
10+
11+
class Logger:
12+
"""Custom Logging Code."""
13+
14+
@staticmethod
15+
async def checkDebugging(enable_debug: list):
16+
"""Check Logging Active"""
17+
18+
if len(enable_debug) > 0:
19+
Data.debugEnabled = True
20+
else:
21+
Data.debugEnabled = False
22+
23+
Data.debugList = enable_debug
24+
return Data.debugEnabled
25+
26+
@staticmethod
27+
async def log(n_id, l_type, new_message, **kwargs):
28+
"""Output new log entry if logging is turned on."""
29+
name = HiveHelper.get_device_name(n_id) + ' - '
30+
data = kwargs.get("info", [])
31+
if "_" in l_type:
32+
nxt = l_type.split("_")
33+
for i in nxt:
34+
if i != "Extra":
35+
if i in Data.debugList and "Extra" in Data.debugList:
36+
l_type = i
37+
break
38+
39+
if Data.debugEnabled and new_message is not None and any(elem in Data.debugList for elem in [l_type, 'All']):
40+
if l_type != "ERROR":
41+
logging_data = name + new_message.format(*data)
42+
_LOGGER.debug(logging_data)
43+
44+
try:
45+
l_file = open(Data.debugOutFile, "a")
46+
l_file.write(
47+
datetime.now().strftime(
48+
"%d-%b-%Y %H:%M:%S")
49+
+ " - "
50+
+ l_type
51+
+ " - "
52+
+ name
53+
+ " : "
54+
+ new_message.format(data)
55+
+ "\n"
56+
)
57+
l_file.close()
58+
except FileNotFoundError:
59+
pass
60+
else:
61+
pass
62+
63+
async def error_check(self, n_id, n_type, error_type, **kwargs):
64+
"""Error has occurred."""
65+
message = None
66+
new_data = None
67+
result = False
68+
name = HiveHelper.get_device_name(n_id)
69+
70+
if error_type == False:
71+
message = "Device offline could not update entity - " + name
72+
result = True
73+
if n_id not in Data.errorList:
74+
_LOGGER.warning(message)
75+
Data.errorList.update({n_id: datetime.now()})
76+
elif error_type == "Failed":
77+
message = "ERROR - No data found for device - " + name
78+
result = True
79+
if n_id not in Data.errorList:
80+
_LOGGER.error(message)
81+
Data.errorList.update({n_id: datetime.now()})
82+
elif error_type == "Failed_API":
83+
new_data = str(kwargs.get("resp"))
84+
message = "ERROR - Received {0} response from API."
85+
result = True
86+
_LOGGER.error(message.format(new_data))
87+
88+
await self.log(n_id, n_type, message, info=[new_data])
89+
return result

0 commit comments

Comments
 (0)