Skip to content

Commit

Permalink
Switch to f"" string formatting.
Browse files Browse the repository at this point in the history
  • Loading branch information
mletenay committed Jul 5, 2024
1 parent f3d85b4 commit daace96
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 51 deletions.
2 changes: 1 addition & 1 deletion goodwe/dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ async def read_device_info(self):
self.arm_version = read_unsigned_int(response, 70) # 30036
self.dsp_svn_version = read_unsigned_int(response, 72) # 35037
self.arm_svn_version = read_unsigned_int(response, 74) # 35038
self.firmware = "{}.{}.{:02x}".format(self.dsp1_version, self.dsp2_version, self.arm_version)
self.firmware = f"{self.dsp1_version}.{self.dsp2_version}.{self.arm_version:02x}"

if is_single_phase(self):
# this is single phase inverter, filter out all L2 and L3 sensors
Expand Down
27 changes: 12 additions & 15 deletions goodwe/es.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ async def get_grid_export_limit(self) -> int:
async def set_grid_export_limit(self, export_limit: int) -> None:
if export_limit >= 0:
await self._read_from_socket(
Aa55ProtocolCommand("033502" + "{:04x}".format(export_limit), "03b5")
Aa55ProtocolCommand(f"033502{export_limit:04x}", "03b5")
)

async def get_operation_modes(self, include_emulated: bool) -> tuple[OperationMode, ...]:
Expand Down Expand Up @@ -396,33 +396,30 @@ async def _set_eco_mode(self) -> None:
async def _clear_battery_mode_param(self) -> None:
await self._read_from_socket(Aa55WriteCommand(0x0700, 1))

async def _set_limit_power_for_charge(self, startH: int, startM: int, stopH: int, stopM: int, limit: int) -> None:
async def _set_limit_power_for_charge(self, start_h: int, start_m: int, stop_h: int, stop_m: int,
limit: int) -> None:
if limit < 0 or limit > 100:
raise ValueError()
await self._read_from_socket(Aa55ProtocolCommand("032c05"
+ "{:02x}".format(startH) + "{:02x}".format(startM)
+ "{:02x}".format(stopH) + "{:02x}".format(stopM)
+ "{:02x}".format(limit), "03AC"))
await self._read_from_socket(Aa55ProtocolCommand(
f"032c05{start_h:02x}{start_m:02x}{stop_h:02x}{stop_m:02x}{limit:02x}", "03AC"))

async def _set_limit_power_for_discharge(self, startH: int, startM: int, stopH: int, stopM: int,
async def _set_limit_power_for_discharge(self, start_h: int, start_m: int, stop_h: int, stop_m: int,
limit: int) -> None:
if limit < 0 or limit > 100:
raise ValueError()
await self._read_from_socket(Aa55ProtocolCommand("032d05"
+ "{:02x}".format(startH) + "{:02x}".format(startM)
+ "{:02x}".format(stopH) + "{:02x}".format(stopM)
+ "{:02x}".format(limit), "03AD"))
await self._read_from_socket(Aa55ProtocolCommand(
f"032d05{start_h:02x}{start_m:02x}{stop_h:02x}{stop_m:02x}{limit:02x}", "03AD"))

async def _set_offgrid_work_mode(self, mode: int) -> None:
await self._read_from_socket(Aa55ProtocolCommand("033601" + "{:02x}".format(mode), "03B6"))
await self._read_from_socket(Aa55ProtocolCommand(f"033601{mode:02x}", "03B6"))

async def _set_relay_control(self, mode: int) -> None:
param = 0
if mode == 2:
param = 16
elif mode == 3:
param = 48
await self._read_from_socket(Aa55ProtocolCommand("03270200" + "{:02x}".format(param), "03B7"))
await self._read_from_socket(Aa55ProtocolCommand(f"03270200{param:02x}", "03B7"))

async def _set_store_energy_mode(self, mode: int) -> None:
param = 0
Expand All @@ -434,10 +431,10 @@ async def _set_store_energy_mode(self, mode: int) -> None:
param = 8
elif mode == 3:
param = 1
await self._read_from_socket(Aa55ProtocolCommand("032601" + "{:02x}".format(param), "03B6"))
await self._read_from_socket(Aa55ProtocolCommand(f"032601{param:02x}", "03B6"))

async def _set_work_mode(self, mode: int) -> None:
await self._read_from_socket(Aa55ProtocolCommand("035901" + "{:02x}".format(mode), "03D9"))
await self._read_from_socket(Aa55ProtocolCommand(f"035901{mode:02x}", "03D9"))

def _is_modbus_setting(self, sensor: Sensor) -> bool:
return sensor.offset > 30000
53 changes: 21 additions & 32 deletions goodwe/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,11 @@ def _ensure_lock(self) -> asyncio.Lock:
"""
if self._lock and self._running_loop == asyncio.get_event_loop():
return self._lock
else:
logger.debug("Creating lock instance for current event loop.")
self._lock = asyncio.Lock()
self._running_loop = asyncio.get_event_loop()
self._close_transport()
return self._lock
logger.debug("Creating lock instance for current event loop.")
self._lock = asyncio.Lock()
self._running_loop = asyncio.get_event_loop()
self._close_transport()
return self._lock

def _max_retries_reached(self) -> Future:
logger.debug("Max number of retries (%d) reached, request %s failed.", self.retries, self.command)
Expand Down Expand Up @@ -193,8 +192,7 @@ async def send_request(self, command: ProtocolCommand) -> Future:
if not self.keep_alive:
self._close_transport()
return await self.send_request(command)
else:
return self._max_retries_reached()
return self._max_retries_reached()
finally:
if self._lock and self._lock.locked():
self._lock.release()
Expand Down Expand Up @@ -272,7 +270,6 @@ async def _connect(self) -> None:
def connection_made(self, transport: asyncio.DatagramTransport) -> None:
"""On connection made"""
logger.debug("Connection opened.")
pass

def eof_received(self) -> None:
logger.debug("EOF received.")
Expand Down Expand Up @@ -341,17 +338,15 @@ async def send_request(self, command: ProtocolCommand) -> Future:
self._lock.release()
self._close_transport()
return await self.send_request(command)
else:
return self._max_retries_reached()
return self._max_retries_reached()
except (ConnectionRefusedError, TimeoutError, OSError, asyncio.TimeoutError):
if self._retry < self.retries:
logger.debug("Connection refused error.")
self._retry += 1
if self._lock and self._lock.locked():
self._lock.release()
return await self.send_request(command)
else:
return self._max_retries_reached()
return self._max_retries_reached()
finally:
if self._lock and self._lock.locked():
self._lock.release()
Expand Down Expand Up @@ -403,8 +398,7 @@ def __repr__(self):
def response_data(self) -> bytes:
if self.command is not None:
return self.command.trim_response(self.raw_data)
else:
return self.raw_data
return self.raw_data

def seek(self, address: int) -> None:
if self.command is not None:
Expand Down Expand Up @@ -458,10 +452,9 @@ async def execute(self, protocol: InverterProtocol) -> ProtocolResponse:
result = response_future.result()
if result is not None:
return ProtocolResponse(result, self)
else:
raise RequestFailedException(
"No response received to '" + self.request.hex() + "' request."
)
raise RequestFailedException(
"No response received to '" + self.request.hex() + "' request."
)
except (asyncio.CancelledError, ConnectionRefusedError):
raise RequestFailedException(
"No valid response received to '" + self.request.hex() + "' request."
Expand Down Expand Up @@ -544,12 +537,11 @@ def __repr__(self):
if self.request[4] == 1:
if self.request[5] == 2:
return f'READ device info ({self.request.hex()})'
elif self.request[5] == 6:
if self.request[5] == 6:
return f'READ runtime data ({self.request.hex()})'
elif self.request[5] == 9:
if self.request[5] == 9:
return f'READ settings ({self.request.hex()})'
else:
return self.request.hex()
return self.request.hex()


class Aa55ReadCommand(Aa55ProtocolCommand):
Expand All @@ -558,13 +550,12 @@ class Aa55ReadCommand(Aa55ProtocolCommand):
"""

def __init__(self, offset: int, count: int):
super().__init__("011A03" + "{:04x}".format(offset) + "{:02x}".format(count), "019A", offset, count)
super().__init__(f"011A03{offset:04x}{count:02x}", "019A", offset, count)

def __repr__(self):
if self.value > 1:
return f'READ {self.value} registers from {self.first_address} ({self.request.hex()})'
else:
return f'READ register {self.first_address} ({self.request.hex()})'
return f'READ register {self.first_address} ({self.request.hex()})'


class Aa55WriteCommand(Aa55ProtocolCommand):
Expand All @@ -573,7 +564,7 @@ class Aa55WriteCommand(Aa55ProtocolCommand):
"""

def __init__(self, register: int, value: int):
super().__init__("023905" + "{:04x}".format(register) + "01" + "{:04x}".format(value), "02B9", register, value)
super().__init__(f"023905{register:04x}01{value:04x}", "02B9", register, value)

def __repr__(self):
return f'WRITE {self.value} to register {self.first_address} ({self.request.hex()})'
Expand All @@ -585,7 +576,7 @@ class Aa55WriteMultiCommand(Aa55ProtocolCommand):
"""

def __init__(self, offset: int, values: bytes):
super().__init__("02390B" + "{:04x}".format(offset) + "{:02x}".format(len(values)) + values.hex(),
super().__init__(f"02390B{offset:04x}{len(values):02x}{values.hex()}",
"02B9", offset, len(values) // 2)


Expand Down Expand Up @@ -641,8 +632,7 @@ def __init__(self, comm_addr: int, offset: int, count: int):
def __repr__(self):
if self.value > 1:
return f'READ {self.value} registers from {self.first_address} ({self.request.hex()})'
else:
return f'READ register {self.first_address} ({self.request.hex()})'
return f'READ register {self.first_address} ({self.request.hex()})'


class ModbusRtuWriteCommand(ModbusRtuProtocolCommand):
Expand Down Expand Up @@ -711,8 +701,7 @@ def __init__(self, comm_addr: int, offset: int, count: int):
def __repr__(self):
if self.value > 1:
return f'READ {self.value} registers from {self.first_address} ({self.request.hex()})'
else:
return f'READ register {self.first_address} ({self.request.hex()})'
return f'READ register {self.first_address} ({self.request.hex()})'


class ModbusTcpWriteCommand(ModbusTcpProtocolCommand):
Expand Down
5 changes: 2 additions & 3 deletions goodwe/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,9 @@ def is_in_range(self, value: int) -> bool:
"""Check if the value fits in allowed values range"""
if self == ScheduleType.ECO_MODE:
return -100 <= value <= 100
elif self == ScheduleType.ECO_MODE_745:
if self == ScheduleType.ECO_MODE_745:
return -1000 <= value <= 1000
else:
return True
return True


class Voltage(Sensor):
Expand Down

0 comments on commit daace96

Please sign in to comment.