Skip to content

Commit

Permalink
Merge pull request #126 from bdraco/min_version_py37
Browse files Browse the repository at this point in the history
Upgrade code to python 3.7+
  • Loading branch information
icemanch authored Oct 12, 2021
2 parents 553f7fa + a69b3f3 commit 9ca9d59
Show file tree
Hide file tree
Showing 10 changed files with 95 additions and 60 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ and/or programmatically.
The classes in this project could very easily be used as an API, and incorporated into a GUI app written
in PyQt, Kivy, or some other framework.

#### Minimum python version

3.7

##### Available:
* Discovering bulbs on LAN
* Turning on/off bulb
Expand Down
4 changes: 2 additions & 2 deletions flux_led/aioprotocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def write(self, data: bytes) -> None:
_LOGGER.debug(
"%s => %s (%d)",
self.peername,
" ".join("0x{:02X}".format(x) for x in data),
" ".join(f"0x{x:02X}" for x in data),
len(data),
)
self.transport.write(data)
Expand All @@ -43,7 +43,7 @@ def data_received(self, data: bytes) -> None:
_LOGGER.debug(
"%s <= %s (%d)",
self.peername,
" ".join("0x{:02X}".format(x) for x in data),
" ".join(f"0x{x:02X}" for x in data),
len(data),
)
self._data_receive_callback(data)
35 changes: 21 additions & 14 deletions flux_led/device.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import print_function

import colorsys
import datetime
import logging
Expand Down Expand Up @@ -43,6 +41,8 @@
from .models_db import (
BASE_MODE_MAP,
CHANNEL_REMAP,
MODEL_DESCRIPTIONS,
UNKNOWN_MODEL,
MODEL_MAP,
RGBW_PROTOCOL_MODELS,
USE_9BYTE_PROTOCOL_MODELS,
Expand Down Expand Up @@ -91,6 +91,13 @@ def model_num(self):
"""Return the model number."""
return self.raw_state.model_num if self.raw_state else None

@property
def model(self):
"""Return the human readable model description."""
model_num = self.model_num
description = MODEL_DESCRIPTIONS.get(model_num) or UNKNOWN_MODEL
return f"{description} (0x{model_num:02X})"

@property
def version_num(self):
"""Return the version number."""
Expand Down Expand Up @@ -274,7 +281,7 @@ def close(self):
return
try:
self._socket.close()
except socket.error:
except OSError:
pass
finally:
self._socket = None
Expand Down Expand Up @@ -441,14 +448,14 @@ def __str__(self):
red = rx.red
green = rx.green
blue = rx.blue
mode_str = "Color: {}".format((red, green, blue))
mode_str = f"Color: {(red, green, blue)}"
# Should add ability to get CCT from rgbwcapable*
if self.rgbwcapable:
mode_str += " White: {}".format(ww_level)
mode_str += f" White: {ww_level}"
else:
mode_str += " Brightness: {}".format(self.brightness)
mode_str += f" Brightness: {self.brightness}"
elif color_mode == COLOR_MODE_DIM:
mode_str = "Warm White: {}%".format(utils.byteToPercent(ww_level))
mode_str = f"Warm White: {utils.byteToPercent(ww_level)}%"
elif color_mode == COLOR_MODE_CCT:
cct_value = self.getWhiteTemperature()
mode_str = "CCT: {}K Brightness: {}%".format(
Expand All @@ -458,20 +465,20 @@ def __str__(self):
mode_str = "Addressable"
elif mode == MODE_PRESET:
pat = PresetPattern.valtostr(pattern)
mode_str = "Pattern: {} (Speed {}%)".format(pat, speed)
mode_str = f"Pattern: {pat} (Speed {speed}%)"
elif mode == MODE_CUSTOM:
mode_str = "Custom pattern (Speed {}%)".format(speed)
mode_str = f"Custom pattern (Speed {speed}%)"
elif BuiltInTimer.valid(pattern):
mode_str = BuiltInTimer.valtostr(pattern)
elif mode == MODE_MUSIC:
mode_str = "Music"
elif mode == MODE_SWITCH:
mode_str = "Switch"
else:
mode_str = "Unknown mode 0x{:x}".format(pattern)
mode_str = f"Unknown mode 0x{pattern:x}"
mode_str += " raw state: "
mode_str += utils.raw_state_to_dec(rx)
return "{} [{}]".format(power_str, mode_str)
return f"{power_str} [{mode_str}]"

@_socket_retry(attempts=2)
def _change_state(self, turn_on=True):
Expand Down Expand Up @@ -760,7 +767,7 @@ def _send_msg(self, bytes):
_LOGGER.debug(
"%s => %s (%d)",
self.ipaddr,
" ".join("0x{:02X}".format(x) for x in bytes),
" ".join(f"0x{x:02X}" for x in bytes),
len(bytes),
)
self._socket.send(bytes)
Expand All @@ -785,14 +792,14 @@ def _read_msg(self, expected):
_LOGGER.debug(
"%s <= %s (%d)",
self.ipaddr,
" ".join("0x{:02X}".format(x) for x in chunk),
" ".join(f"0x{x:02X}" for x in chunk),
len(chunk),
)
if chunk:
begin = time.monotonic()
remaining -= len(chunk)
rx.extend(chunk)
except socket.error as ex:
except OSError as ex:
_LOGGER.debug("%s: socket error: %s", self.ipaddr, ex)
pass
finally:
Expand Down
43 changes: 21 additions & 22 deletions flux_led/fluxled.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
See the following for valid color names: http://www.w3schools.com/html/html_colornames.asp
"""
from __future__ import print_function

import datetime
import logging
Expand Down Expand Up @@ -217,9 +216,9 @@ def processSetTimerArgs(parser, args):
timer.setActive(True)

if "time" not in keys:
parser.error("This mode needs a time: {}".format(mode))
parser.error(f"This mode needs a time: {mode}")
if "repeat" in keys and "date" in keys:
parser.error("This mode only a repeat or a date, not both: {}".format(mode))
parser.error(f"This mode only a repeat or a date, not both: {mode}")

# validate time format
if len(settings_dict["time"]) != 4 or not settings_dict["time"].isdigit():
Expand Down Expand Up @@ -294,9 +293,9 @@ def processSetTimerArgs(parser, args):

if mode == "preset":
if "code" not in keys:
parser.error("preset mode needs a code: {}".format(mode))
parser.error(f"preset mode needs a code: {mode}")
if "speed" not in keys:
parser.error("preset mode needs a speed: {}".format(mode))
parser.error(f"preset mode needs a speed: {mode}")
code = settings_dict["code"]
speed = settings_dict["speed"]
if not speed.isdigit() or int(speed) > 100:
Expand All @@ -307,7 +306,7 @@ def processSetTimerArgs(parser, args):

if mode == "warmwhite":
if "level" not in keys:
parser.error("warmwhite mode needs a level: {}".format(mode))
parser.error(f"warmwhite mode needs a level: {mode}")
level = settings_dict["level"]
if not level.isdigit() or int(level) > 100:
parser.error("warmwhite level must be a percentage (0-100)")
Expand All @@ -316,16 +315,16 @@ def processSetTimerArgs(parser, args):
if mode == "sunrise" or mode == "sunset":
if "startbrightness" not in keys:
parser.error(
"{} mode needs a startBrightness (0% -> 100%)".format(mode)
f"{mode} mode needs a startBrightness (0% -> 100%)"
)
startBrightness = int(settings_dict["startbrightness"])

if "endbrightness" not in keys:
parser.error("{} mode needs an endBrightness (0% -> 100%)".format(mode))
parser.error(f"{mode} mode needs an endBrightness (0% -> 100%)")
endBrightness = int(settings_dict["endbrightness"])

if "duration" not in keys:
parser.error("{} mode needs a duration (minutes)".format(mode))
parser.error(f"{mode} mode needs a duration (minutes)")
duration = int(settings_dict["duration"])

if mode == "sunrise":
Expand All @@ -335,14 +334,14 @@ def processSetTimerArgs(parser, args):
timer.setModeSunset(startBrightness, endBrightness, duration)

else:
parser.error("Not a valid timer mode: {}".format(mode))
parser.error(f"Not a valid timer mode: {mode}")

return timer


def processCustomArgs(parser, args):
if args[0] not in ["gradual", "jump", "strobe"]:
parser.error("bad pattern type: {}".format(args[0]))
parser.error(f"bad pattern type: {args[0]}")
return None

speed = int(args[1])
Expand Down Expand Up @@ -586,12 +585,12 @@ def parseArgs():
for c in range(
PresetPattern.seven_color_cross_fade, PresetPattern.seven_color_jumping + 1
):
print("{:2} {}".format(c, PresetPattern.valtostr(c)))
print(f"{c:2} {PresetPattern.valtostr(c)}")
sys.exit(0)

if options.listcolors:
for c in utils.get_color_names_list():
print("{}, ".format(c))
print(f"{c}, ")
print("")
sys.exit(0)

Expand Down Expand Up @@ -682,7 +681,7 @@ def main():
for b in bulb_info_list:
addrs.append(b["ipaddr"])
else:
print("{} bulbs found".format(len(bulb_info_list)))
print(f"{len(bulb_info_list)} bulbs found")
for b in bulb_info_list:
print(" {} {}".format(b["id"], b["ipaddr"]))
sys.exit(0)
Expand Down Expand Up @@ -715,11 +714,11 @@ def main():
bulb.setProtocol(options.protocol)

if options.ww is not None:
print("Setting warm white mode, level: {}%".format(options.ww))
print(f"Setting warm white mode, level: {options.ww}%")
bulb.setWarmWhite(options.ww, not options.volatile)

if options.cw is not None:
print("Setting cold white mode, level: {}%".format(options.cw))
print(f"Setting cold white mode, level: {options.cw}%")
bulb.setColdWhite(options.cw, not options.volatile)

if options.cct is not None:
Expand All @@ -734,13 +733,13 @@ def main():

if options.color is not None:
print(
"Setting color RGB:{}".format(options.color),
f"Setting color RGB:{options.color}",
)
name = utils.color_tuple_to_string(options.color)
if name is None:
print()
else:
print("[{}]".format(name))
print(f"[{name}]")
if len(options.color) == 3:
bulb.setRgb(
options.color[0],
Expand Down Expand Up @@ -786,10 +785,10 @@ def main():
bulb.setPresetPattern(options.preset[0], options.preset[1])

if options.on:
print("Turning on bulb at {}".format(bulb.ipaddr))
print(f"Turning on bulb at {bulb.ipaddr}")
bulb.turnOn()
elif options.off:
print("Turning off bulb at {}".format(bulb.ipaddr))
print(f"Turning off bulb at {bulb.ipaddr}")
bulb.turnOff()

if options.info:
Expand All @@ -799,7 +798,7 @@ def main():
if options.settimer:
timers = bulb.getTimers()
num = int(options.settimer[0])
print("New Timer ---- #{}: {}".format(num, options.new_timer))
print(f"New Timer ---- #{num}: {options.new_timer}")
if options.new_timer.isExpired():
print("[timer is already expired, will be deactivated]")
timers[num - 1] = options.new_timer
Expand All @@ -810,7 +809,7 @@ def main():
num = 0
for t in timers:
num += 1
print(" Timer #{}: {}".format(num, t))
print(f" Timer #{num}: {t}")
print("")

sys.exit(0)
Expand Down
Loading

0 comments on commit 9ca9d59

Please sign in to comment.