Skip to content

Commit

Permalink
Merge branch 'format'
Browse files Browse the repository at this point in the history
  • Loading branch information
sampsyo committed Nov 28, 2020
2 parents b4ccbb7 + 8319b2e commit 267a880
Show file tree
Hide file tree
Showing 19 changed files with 903 additions and 762 deletions.
5 changes: 5 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[flake8]
ignore = E203, E266, E501, W503, F403, F401
max-line-length = 79
max-complexity = 18
select = B,C,E,F,W,T4,B9
10 changes: 10 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
repos:
- repo: https://github.com/ambv/black
rev: stable
hooks:
- id: black
language_version: python3.9
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v1.2.3
hooks:
- id: flake8
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ You can also specify one of several other commands:
* `turn <ID> <ONOFF>`: Turn an AC device on or off. Use "on" or "off" as the second argument.
* `ac-config <ID>`: Print out some configuration information about an AC device.

Development
-----------

This project uses the [Black][] code formatting tool. Before submitting pull requests, please run Black to ensure consistent formatting.

If you like, you can install a git hook to automatically run Black and flake8 every time you commit. Install the [pre-commit][] tool and type `pre-commit install` to use it.

Credits
-------
Expand All @@ -41,3 +47,5 @@ I also made a [Home Assistant component][hass-smartthinq] that uses wideq.
[hass-smartthinq]: https://github.com/sampsyo/hass-smartthinq
[adrian]: https://github.com/sampsyo
[mit]: https://opensource.org/licenses/MIT
[black]: https://github.com/psf/black
[pre-commit]: https://pre-commit.com/
162 changes: 94 additions & 68 deletions example.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import logging
from typing import List

STATE_FILE = 'wideq_state.json'
STATE_FILE = "wideq_state.json"
LOGGER = logging.getLogger("wideq.example")


Expand All @@ -20,9 +20,9 @@ def authenticate(gateway):
"""

login_url = gateway.oauth_url()
print('Log in here:')
print("Log in here:")
print(login_url)
print('Then paste the URL where the browser is redirected:')
print("Then paste the URL where the browser is redirected:")
callback_url = input()
return wideq.Auth.from_url(gateway, callback_url)

Expand All @@ -31,7 +31,7 @@ def ls(client):
"""List the user's devices."""

for device in client.devices:
print('{0.id}: {0.name} ({0.type.name} {0.model_id})'.format(device))
print("{0.id}: {0.name} ({0.type.name} {0.model_id})".format(device))


def gen_mon(client, device_id):
Expand All @@ -46,27 +46,33 @@ def gen_mon(client, device_id):
try:
while True:
time.sleep(1)
print('Polling...')
print("Polling...")
data = mon.poll()
if data:
try:
res = model.decode_monitor(data)
except ValueError:
print('status data: {!r}'.format(data))
print("status data: {!r}".format(data))
else:
for key, value in res.items():
try:
desc = model.value(key)
except KeyError:
print('- {}: {}'.format(key, value))
print("- {}: {}".format(key, value))
if isinstance(desc, wideq.EnumValue):
print('- {}: {}'.format(
key, desc.options.get(value, value)
))
print(
"- {}: {}".format(
key, desc.options.get(value, value)
)
)
elif isinstance(desc, wideq.RangeValue):
print('- {0}: {1} ({2.min}-{2.max})'.format(
key, value, desc,
))
print(
"- {0}: {1} ({2.min}-{2.max})".format(
key,
value,
desc,
)
)

except KeyboardInterrupt:
pass
Expand All @@ -80,7 +86,7 @@ def ac_mon(ac):
try:
ac.monitor_start()
except wideq.core.NotConnectedError:
print('Device not available.')
print("Device not available.")
return

try:
Expand All @@ -89,18 +95,16 @@ def ac_mon(ac):
state = ac.poll()
if state:
print(
'{1}; '
'{0.mode.name}; '
'cur {0.temp_cur_f}°F; '
'cfg {0.temp_cfg_f}°F; '
'fan speed {0.fan_speed.name}'
.format(
state,
'on' if state.is_on else 'off'
"{1}; "
"{0.mode.name}; "
"cur {0.temp_cur_f}°F; "
"cfg {0.temp_cfg_f}°F; "
"fan speed {0.fan_speed.name}".format(
state, "on" if state.is_on else "off"
)
)
else:
print('no state. Wait 1 more second.')
print("no state. Wait 1 more second.")

except KeyboardInterrupt:
pass
Expand All @@ -121,8 +125,8 @@ def mon(client, device_id):


class UserError(Exception):
"""A user-visible command-line error.
"""
"""A user-visible command-line error."""

def __init__(self, msg):
self.msg = msg

Expand All @@ -147,11 +151,13 @@ def set_temp(client, device_id, temp):
ac.set_fahrenheit(int(temp))
elif device.type == wideq.client.DeviceType.REFRIGERATOR:
refrigerator = wideq.RefrigeratorDevice(
client, _force_device(client, device_id))
client, _force_device(client, device_id)
)
refrigerator.set_temp_refrigerator_c(int(temp))
else:
raise UserError(
'set-temp only suported for AC or refrigerator devices')
"set-temp only suported for AC or refrigerator devices"
)


def set_temp_freezer(client, device_id, temp):
Expand All @@ -161,18 +167,20 @@ def set_temp_freezer(client, device_id, temp):

if device.type == wideq.client.DeviceType.REFRIGERATOR:
refrigerator = wideq.RefrigeratorDevice(
client, _force_device(client, device_id))
client, _force_device(client, device_id)
)
refrigerator.set_temp_freezer_c(int(temp))
else:
raise UserError(
'set-temp-freezer only suported for refrigerator devices')
"set-temp-freezer only suported for refrigerator devices"
)


def turn(client, device_id, on_off):
"""Turn on/off an AC device."""

ac = wideq.ACDevice(client, _force_device(client, device_id))
ac.set_on(on_off == 'on')
ac.set_on(on_off == "on")


def ac_config(client, device_id):
Expand All @@ -190,26 +198,30 @@ def ac_config(client, device_id):


EXAMPLE_COMMANDS = {
'ls': ls,
'mon': mon,
'set-temp': set_temp,
'set-temp-freezer': set_temp_freezer,
'turn': turn,
'ac-config': ac_config,
"ls": ls,
"mon": mon,
"set-temp": set_temp,
"set-temp-freezer": set_temp_freezer,
"turn": turn,
"ac-config": ac_config,
}


def example_command(client, cmd, args):
func = EXAMPLE_COMMANDS.get(cmd)
if not func:
LOGGER.error("Invalid command: '%s'.\n"
"Use one of: %s", cmd, ', '.join(EXAMPLE_COMMANDS))
LOGGER.error(
"Invalid command: '%s'.\n" "Use one of: %s",
cmd,
", ".join(EXAMPLE_COMMANDS),
)
return
func(client, *args)


def example(country: str, language: str, verbose: bool,
cmd: str, args: List[str]) -> None:
def example(
country: str, language: str, verbose: bool, cmd: str, args: List[str]
) -> None:
if verbose:
wideq.set_log_level(logging.DEBUG)

Expand All @@ -220,8 +232,9 @@ def example(country: str, language: str, verbose: bool,
state = json.load(f)
except IOError:
state = {}
LOGGER.debug("No state file found (tried: '%s')",
os.path.abspath(STATE_FILE))
LOGGER.debug(
"No state file found (tried: '%s')", os.path.abspath(STATE_FILE)
)

client = wideq.Client.load(state)
if country:
Expand All @@ -240,7 +253,7 @@ def example(country: str, language: str, verbose: bool,
break

except wideq.NotLoggedInError:
LOGGER.info('Session expired.')
LOGGER.info("Session expired.")
client.refresh()

except UserError as exc:
Expand All @@ -249,54 +262,67 @@ def example(country: str, language: str, verbose: bool,

# Save the updated state.
state = client.dump()
with open(STATE_FILE, 'w') as f:
with open(STATE_FILE, "w") as f:
json.dump(state, f)
LOGGER.debug("Wrote state file '%s'", os.path.abspath(STATE_FILE))


def main() -> None:
"""The main command-line entry point.
"""
"""The main command-line entry point."""
parser = argparse.ArgumentParser(
description='Interact with the LG SmartThinQ API.'
description="Interact with the LG SmartThinQ API."
)
parser.add_argument(
"cmd",
metavar="CMD",
nargs="?",
default="ls",
help=f'one of: {", ".join(EXAMPLE_COMMANDS)}',
)
parser.add_argument(
"args", metavar="ARGS", nargs="*", help="subcommand arguments"
)
parser.add_argument('cmd', metavar='CMD', nargs='?', default='ls',
help=f'one of: {", ".join(EXAMPLE_COMMANDS)}')
parser.add_argument('args', metavar='ARGS', nargs='*',
help='subcommand arguments')

parser.add_argument(
'--country', '-c',
help=f'country code for account (default: {wideq.DEFAULT_COUNTRY})',
default=wideq.DEFAULT_COUNTRY
"--country",
"-c",
help=f"country code for account (default: {wideq.DEFAULT_COUNTRY})",
default=wideq.DEFAULT_COUNTRY,
)
parser.add_argument(
'--language', '-l',
help=f'language code for the API (default: {wideq.DEFAULT_LANGUAGE})',
default=wideq.DEFAULT_LANGUAGE
"--language",
"-l",
help=f"language code for the API (default: {wideq.DEFAULT_LANGUAGE})",
default=wideq.DEFAULT_LANGUAGE,
)
parser.add_argument(
'--verbose', '-v',
help='verbose mode to help debugging',
action='store_true', default=False
"--verbose",
"-v",
help="verbose mode to help debugging",
action="store_true",
default=False,
)

args = parser.parse_args()
country_regex = re.compile(r"^[A-Z]{2,3}$")
if not country_regex.match(args.country):
LOGGER.error("Country must be two or three letters"
" all upper case (e.g. US, NO, KR) got: '%s'",
args.country)
LOGGER.error(
"Country must be two or three letters"
" all upper case (e.g. US, NO, KR) got: '%s'",
args.country,
)
exit(1)
language_regex = re.compile(r"^[a-z]{2,3}-[A-Z]{2,3}$")
if not language_regex.match(args.language):
LOGGER.error("Language must be a combination of language"
" and country (e.g. en-US, no-NO, kr-KR)"
" got: '%s'",
args.language)
LOGGER.error(
"Language must be a combination of language"
" and country (e.g. en-US, no-NO, kr-KR)"
" got: '%s'",
args.language,
)
exit(1)
example(args.country, args.language, args.verbose, args.cmd, args.args)


if __name__ == '__main__':
if __name__ == "__main__":
main()
16 changes: 16 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,19 @@ requires-python = ">=3.6"
test = [
"responses"
]

[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
\.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| build
| dist
)/
'''
Loading

0 comments on commit 267a880

Please sign in to comment.