Skip to content

Commit

Permalink
Merge pull request #93 from sHedC/sHedC/issue92
Browse files Browse the repository at this point in the history
SHedC/issue92
  • Loading branch information
sHedC authored Mar 9, 2023
2 parents cc33ece + 21fbd30 commit dda0d67
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 13 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,16 @@ This is used as a libary but it can also be run directly for debug purposes and
> :warning: **Do Not Run This Too Frequently**: The new API may lock you're IP out for an unknown period of time. The app and web app refresh every 30 seconds. I don't know how many times in succession would lock you out, probably frequent calls over a period of time such as an hour.
```
usage: masterthermconnect [-h] [--version] {get,set} ...
usage: masterthermconnect [-h] [--version] [-d] [-v] {get,set} ...
Python Mastertherm Connect API Module, used for debug purposes, allows you to get and set registers and other information for testing, use with
caution!!!
options:
-h, --help show this help message and exit
--version display the Mastertherm Connect API version
-d, --debug display Debug Logging
-v, --verbose display Verbose/ Info logging
commands:
Valid commands to access the API, use -h to get more help after the command for specific help.
Expand Down
18 changes: 18 additions & 0 deletions masterthermconnect/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,23 @@ def get_arguments(argv) -> argparse.Namespace:
version="Mastertherm Connect API Version: " + __version__,
help="display the Mastertherm Connect API version",
)
parser.add_argument(
"-d",
"--debug",
help="Print debugging statements.",
action="store_const",
dest="loglevel",
const=logging.DEBUG,
default=logging.WARNING,
)
parser.add_argument(
"-v",
"--verbose",
help="Print verbose statements.",
action="store_const",
dest="loglevel",
const=logging.INFO,
)

# Sub Commands are get and set:
subparsers = parser.add_subparsers(
Expand Down Expand Up @@ -399,6 +416,7 @@ def main(argv=None) -> int:
# If User/ Pass is not provided then get from the command line.
login_user = input("User: ") if args.user is None else args.user
login_pass = getpass.getpass() if args.password is None else args.password
logging.basicConfig(level=args.loglevel)

if args.command == "get":
return asyncio.run(get_command(login_user, login_pass, args))
Expand Down
35 changes: 24 additions & 11 deletions masterthermconnect/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ async def __token_expired(self) -> bool:
async def __post(self, url: str, params: str) -> dict:
"""Push updates to the API."""
if await self.__token_expired():
_LOGGER.info("__post: Token Expired, Refreshing Token.")
await self.__connect_refresh()

_LOGGER.debug("__post: data to: %s, params: %s", url, params)
try:
if self.__api_version == "v1":
# Original uses post, with Cookie Token
Expand All @@ -134,6 +136,11 @@ async def __post(self, url: str, params: str) -> dict:
},
)

_LOGGER.debug(
"__post: response status: %s, content: %s",
response.status,
await response.text(),
)
response_json = await response.json()
except ClientConnectionError as ex:
_LOGGER.error("Client Connection Error: %s", ex)
Expand Down Expand Up @@ -178,8 +185,10 @@ async def __post(self, url: str, params: str) -> dict:
async def __get(self, url: str, params: str) -> dict:
"""Get updates from the API, for old this mostly uses Post."""
if await self.__token_expired():
_LOGGER.info("__get: Token Expired, Refreshing Token.")
await self.__connect_refresh()

_LOGGER.debug("__get: data from: %s", url)
try:
if self.__api_version == "v1":
# Original uses post, with Cookie Token
Expand All @@ -201,6 +210,11 @@ async def __get(self, url: str, params: str) -> dict:
},
)

_LOGGER.debug(
"__get: response status: %s, content: %s",
response.status,
await response.text(),
)
response_json = await response.json()
except ClientConnectionError as ex:
_LOGGER.error("Client Connection Error: %s", ex)
Expand Down Expand Up @@ -358,17 +372,18 @@ async def get_device_info(self, module_id: str, unit_id: str) -> dict:
retry = False
params = f"moduleid={module_id}&unitid={unit_id}&application=android"

_LOGGER.info("Get Device Info %s:%s", module_id, unit_id)
try:
response_json = await self.__get(
url=URL_PUMPINFO if self.__api_version == "v1" else URL_PUMPINFO_NEW,
params=params,
)
except MasterthermTokenInvalid as ex:
_LOGGER.warning("Token Expired Early Retry: %s:%s", ex.status, ex.message)
_LOGGER.info("Token Expired Early Retry: %s:%s", ex.status, ex.message)
retry = True
self.__expires = None
except MasterthermServerTimeoutError as ex:
_LOGGER.warning("API Timed Out Retry: %s:%s", ex.status, ex.message)
_LOGGER.info("API Timed Out Retry: %s:%s", ex.status, ex.message)
retry = True

if retry:
Expand Down Expand Up @@ -412,19 +427,18 @@ async def get_device_data(
+ f"messageId=2&lastUpdateTime={last_update_time}&errorResponse=true&fullRange=true"
)

_LOGGER.info("Get Device Data %s:%s", module_id, unit_id)
try:
response_json = await self.__get(
url=URL_PUMPDATA if self.__api_version == "v1" else URL_PUMPDATA_NEW,
params=params,
)
except MasterthermTokenInvalid as ex:
_LOGGER.warning(
"Token Expired Early Retrying: %s:%s", ex.status, ex.message
)
_LOGGER.info("Token Expired Early Retrying: %s:%s", ex.status, ex.message)
retry = True
self.__expires = None
except MasterthermServerTimeoutError as ex:
_LOGGER.warning("API Timed Out Retry: %s:%s", ex.status, ex.message)
_LOGGER.info("API Timed Out Retry: %s:%s", ex.status, ex.message)
retry = True

if retry:
Expand Down Expand Up @@ -490,6 +504,7 @@ async def set_device_data(
+ f"variableId={register}&variableValue={value}&application=android"
)

_LOGGER.info("Set Device Reg %s:%s:%s:%s", module_id, unit_id, register, value)
try:
response_json = await self.__post(
url=URL_POSTUPDATE
Expand All @@ -498,13 +513,11 @@ async def set_device_data(
params=params,
)
except MasterthermTokenInvalid as ex:
_LOGGER.warning(
"Token Expired Early Retrying: %s:%s", ex.status, ex.message
)
_LOGGER.info("Token Expired Early Retrying: %s:%s", ex.status, ex.message)
retry = True
self.__expires = None
except MasterthermServerTimeoutError as ex:
_LOGGER.warning("API Timed Out Retry: %s:%s", ex.status, ex.message)
_LOGGER.info("API Timed Out Retry: %s:%s", ex.status, ex.message)
retry = True

if retry:
Expand All @@ -516,7 +529,7 @@ async def set_device_data(
params=params,
)

_LOGGER.debug("Set Response Received: %s", response_json)
_LOGGER.info("Set Device Reg response: %s", response_json)

# Check the response for any errors:
if response_json["error"]["errorId"] != 0:
Expand Down
9 changes: 9 additions & 0 deletions masterthermconnect/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,15 @@ async def set_device_data_item(
# If Normal just set it from the Value
entry_reg = entry_value

_LOGGER.info(
"Set module %s:%s property: %s, register: %s, value: %s",
module_id,
unit_id,
entry,
entry_reg,
value,
)

# Test if the entry_type matches our value type.
if isinstance(value, entry_type):
if isinstance(value, bool):
Expand Down
4 changes: 3 additions & 1 deletion tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ def test_help(capsys):
MasterthermConnect(["--help"])

out, err = capsys.readouterr()
assert out.startswith("usage: masterthermconnect [-h] [--version] {get,set}")
assert out.startswith(
"usage: masterthermconnect [-h] [--version] [-d] [-v] {get,set}"
)
assert err == ""


Expand Down

0 comments on commit dda0d67

Please sign in to comment.