Skip to content

Commit

Permalink
0.9.9.6 - Syntax changes only, no functional changes
Browse files Browse the repository at this point in the history
Converted format output on strings to embedded curly brackets
Removed some commented out stuff to clean it up
A couple of extra checks for client being none
Removed partition number on siren (as it is not associated with a particular partition)
In pyvisonic all global constants are consistently named
  • Loading branch information
davesmeghead committed Oct 14, 2024
1 parent ccba259 commit 118d7cd
Show file tree
Hide file tree
Showing 12 changed files with 421 additions and 432 deletions.
5 changes: 2 additions & 3 deletions custom_components/visonic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ async def service_sensor_image(call):

async def handle_reload(call) -> None:
"""Handle reload service call."""
_LOGGER.info("Domain {0} call {1} reload called: reloading integration".format(DOMAIN, call))
_LOGGER.info(f"Domain {DOMAIN} call {call} reload called: reloading integration")
current_entries = hass.config_entries.async_entries(DOMAIN)
reload_tasks = [
hass.config_entries.async_reload(entry.entry_id)
Expand Down Expand Up @@ -450,15 +450,14 @@ def configured_hosts(hass):

# Listener to handle fired events
def handle_core_config_updated(event):
_LOGGER.debug(f"[Visonic Setup] event {str(event)}")
_LOGGER.debug(f"[Visonic Setup] Core configuration has been Updated")
#hass = async_get_hass()
translateLanguage(hass)

if not translatedLanguageAlready:
translatedLanguageAlready = True
translateLanguage(hass)
# Listen for when EVENT_CORE_CONFIG_UPDATE is fired
# hass.bus.async_listen(EVENT_HOMEASSISTANT_STARTED, handle_core_config_updated)
hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, handle_core_config_updated)

# combine and convert python settings map to dictionary
Expand Down
5 changes: 4 additions & 1 deletion custom_components/visonic/alarm_control_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ def async_add_alarm() -> None:
)
#_LOGGER.debug("alarm control panel async_setup_entry exit")


class VisonicAlarm(alarm.AlarmControlPanelEntity):
"""Representation of a Visonic alarm control panel."""

Expand Down Expand Up @@ -219,6 +218,8 @@ def extra_state_attributes(self): #
def supported_features(self) -> int:
"""Return the list of supported features."""
#_LOGGER.debug(f"alarm control panel supported_features {self.entity_id=}")
if self._client is None:
return 0
if self._client.isDisableAllCommands():
return 0
#_LOGGER.debug(f"[AlarmcontrolPanel] Getting Supported Features {self._client.isArmHome()} {self._client.isArmNight()}")
Expand All @@ -242,6 +243,8 @@ def code_format(self):
#_LOGGER.debug(f"alarm control panel code_format {self.entity_id=}")
# Do not show the code panel if the integration is just starting up and
# connecting to the panel
if self._client is None:
return None
if self._client.isDisableAllCommands():
return None
if self.isPanelConnected():
Expand Down
2 changes: 1 addition & 1 deletion custom_components/visonic/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def available(self) -> bool:
def extra_state_attributes(self):
"""Return the state attributes of the device."""
# _LOGGER.debug("in device_state_attributes")
if self._visonic_device is not None:
if self._client is not None and self._visonic_device is not None:
stype = self._visonic_device.getSensorType()

attr = {}
Expand Down
21 changes: 10 additions & 11 deletions custom_components/visonic/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@
# "trigger",
#]

CLIENT_VERSION = "0.9.9.5"
CLIENT_VERSION = "0.9.9.6"

MAX_CLIENT_LOG_ENTRIES = 300

Expand Down Expand Up @@ -313,7 +313,7 @@ def __call__(self):
class VisonicClient:
"""Set up for Visonic devices."""

_LOGGER.debug("Initialising Client - Version {0}".format(CLIENT_VERSION))
_LOGGER.debug(f"Initialising Client - Version {CLIENT_VERSION}")

def __init__(self, hass: HomeAssistant, panelident: int, cf: dict, entry: ConfigEntry):
"""Initialize the Visonic Client."""
Expand Down Expand Up @@ -625,7 +625,7 @@ def _savePanelEventLogFiles(self, available, total):
output = template.render(
entries=self.templatedata,
total=total,
available="{0}".format(available),
available=f"{available}",
)
with open(self.config.get(CONF_LOG_XML_FN), "w") as f:
self.logstate_debug("Panel Event Log - Writing xml file")
Expand Down Expand Up @@ -1258,7 +1258,7 @@ def pmGetPin(self, code: str, forcedKeypad: bool):
return False, None # Return invalid as panel downloading EEPROM
else:
# If the panel mode is UNKNOWN, PROBLEM.
self.logstate_warning("Warning: Valid 4 digit PIN not found, panelmode is {0}".format(panelmode))
self.logstate_warning(f"Warning: Valid 4 digit PIN not found, panelmode is {panelmode}")
return False, None # Return invalid as panel not in correct state to do anything
return True, code

Expand All @@ -1273,7 +1273,7 @@ def pmGetPinSimple(self, code: str):
# Powerlink or StdPlus and so we downloaded the code codes
return True, None
else:
self.logstate_warning("Warning: [pmGetPinSimple] Valid 4 digit PIN not found, panelmode is {0}".format(panelmode))
self.logstate_warning(f"Warning: [pmGetPinSimple] Valid 4 digit PIN not found, panelmode is {panelmode}")
return False, None
return True, code

Expand Down Expand Up @@ -1676,7 +1676,7 @@ def _createSocketConnection(self, address, port):
return sock

except socket.error as err:
self.logstate_debug("Setting TCP socket Options Exception {0}".format(err))
self.logstate_debug(f"Setting TCP socket Options Exception {err}")
if sock is not None:
sock.close()

Expand Down Expand Up @@ -1864,7 +1864,7 @@ async def async_service_panel_start(self, force : bool):
attemptCounter = 0
#self.logstate_debug(f" {attemptCounter} of {self.totalAttempts}")
while force or attemptCounter < self.totalAttempts:
self.logstate_debug("........... connection attempt {0} of {1}".format(attemptCounter + 1, self.totalAttempts))
self.logstate_debug(f"........... connection attempt {attemptCounter + 1} of {self.totalAttempts}")
if await self.connect_to_alarm():
self.logstate_debug("........... connection made")
self._fireHAEvent(event_id = PanelCondition.CONNECTION, datadictionary = {"state": "connected", "attempt": attemptCounter + 1})
Expand All @@ -1873,7 +1873,7 @@ async def async_service_panel_start(self, force : bool):
attemptCounter = attemptCounter + 1
force = False
if attemptCounter < self.totalAttempts:
self.logstate_debug("........... connection attempt delay {0} seconds".format(self.delayBetweenAttempts))
self.logstate_debug(f"........... connection attempt delay {self.delayBetweenAttempts} seconds")
await asyncio.sleep(self.delayBetweenAttempts)

self.createNotification(
Expand Down Expand Up @@ -1948,7 +1948,6 @@ async def connect(self):
except (ConnectTimeout, HTTPError) as ex:
createNotification(
AvailableNotifications.CONNECTION_PROBLEM,
"Visonic Panel Connection Error: {}<br />"
"You will need to restart hass after fixing."
"".format(ex))
"Visonic Panel Connection Error: {ex}<br />"
"You will need to restart hass after fixing.")
#return False
30 changes: 15 additions & 15 deletions custom_components/visonic/examples/complete_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@

# config parameters for myconfig, just to make the defaults easier
CONF_DOWNLOAD_CODE = "download_code"
CONF_LANGUAGE = "language"
#CONF_LANGUAGE = "language"
CONF_EMULATION_MODE = "emulation_mode"
CONF_SIREN_SOUNDING = "siren_sounding"
#CONF_SIREN_SOUNDING = "siren_sounding"

class ConnectionMode(Enum):
POWERLINK = 1
Expand All @@ -54,8 +54,8 @@ class PrintMode(Enum):
myconfig = {
CONF_DOWNLOAD_CODE: "",
CONF_EMULATION_MODE: ConnectionMode.POWERLINK,
CONF_LANGUAGE: "Panel",
CONF_SIREN_SOUNDING: ["Intruder"]
#CONF_LANGUAGE: "EN",
#CONF_SIREN_SOUNDING: ["Intruder"]
}

string_type="string"
Expand Down Expand Up @@ -109,7 +109,7 @@ def format(self, record):
elapsed_seconds = record.created - self.start_time
# using timedelta here for convenient default formatting
elapsed = str(timedelta(seconds=elapsed_seconds))
return "{: <15} <{: <15}:{: >5}> {: >8} {}".format(elapsed, record.filename, record.lineno, record.levelname, record.getMessage())
return f"{elapsed: <15} <{record.filename: <15}:{record.lineno: >5}> {record.levelname: >8} {record.getMessage()}"

# remove existing handlers
while root_logger.hasHandlers():
Expand Down Expand Up @@ -151,7 +151,7 @@ def ConfigureLogger(mode, console = None):
console.print("Setting output mode to ERROR")
else:
if console is not None:
console.print("Not Setting output mode, unknown mode {0}".format(mode))
console.print(f"Not Setting output mode, unknown mode {mode}")


class MyTransport(AlTransport):
Expand Down Expand Up @@ -223,12 +223,12 @@ def __init__(self, loop, config):
def onSensorChange(self, sensor : AlSensorDevice, s : AlSensorCondition):
if self.process_sensor is not None:
self.process_sensor(sensor)
# print("onSensorChange {0} {1}".format(s.name, sensor) )
# print(f"onSensorChange {s.name} {sensor}")

def onSwitchChange(self, switch : AlSwitchDevice):
if self.process_x10 is not None:
self.process_x10(switch)
# print("onSwitchChange {0}".format(switch))
# print(f"onSwitchChange {switch}")

def onNewSwitch(self, switch: AlSwitchDevice):
"""Process a new x10."""
Expand Down Expand Up @@ -369,11 +369,11 @@ async def async_create_tcp_visonic_connection(self, address, port, panelConfig :

except socket.error as _:
err = _
print("Setting TCP socket Options Exception {0}".format(err))
print(f"Setting TCP socket Options Exception {err}")
if sock is not None:
sock.close()
except Exception as exc:
print("Setting TCP Options Exception {0}".format(exc))
print(f"Setting TCP Options Exception {exc}")
return None, None


Expand Down Expand Up @@ -649,7 +649,7 @@ async def controller(client : VisonicClient, console : MyAsyncConsole):
def process_event(event_id : AlCondition, data : dict = None):
# event means there's been a panel state change
if event_id is not AlCondition.PUSH_CHANGE:
console.print("Visonic update event condition {0} {1}".format(str(event_id), data))
console.print(f"Visonic update event condition {str(event_id)} {data}")

def process_log(event_log_entry : AlLogPanelEvent):
""" Process a sequence of panel log events """
Expand Down Expand Up @@ -770,7 +770,7 @@ def help():
command = result[0]
ar = result.split(' ')
processedInput = False
#print("Command Received {0}".format(command))
#print(f"Command Received {command}")
if client.isSystemStarted():
# There must be a panel connection to do the following commands
if command == 'c':
Expand Down Expand Up @@ -829,7 +829,7 @@ def help():
# output mode
if len(ar) > 1:
mode=str(ar[1].strip()).lower()
#console.print("Setting output mode to {0} :{1}:".format(mode, mode[0]))
#console.print(f"Setting output mode to {mode} :{mode[0]}:")
ConfigureLogger(mode, console)
else:
console.print("Current output level is " + str(logger_level))
Expand All @@ -853,7 +853,7 @@ def help():
console.print("")
for key, value in myconfig.items():
s = str(key)
console.print("{0} : {1} = {2}".format(c, s, value))
console.print(f"{c} : {s} = {value}")
c = c + 1
console.print("")
elif command.isnumeric() == True:
Expand All @@ -879,7 +879,7 @@ def help():
ex_type, ex_value, ex_traceback = sys.exc_info()

if str(ex_value) != terminating_clean:
print("Exception {0} {1}".format(len(terminating_clean),len(ex_value)))
print(f"Exception {len(terminating_clean)} {len(ex_value)}")
print("Exception: ")
print(f" type : {ex_type.__name__}")
print(f" message : {ex_value}")
Expand Down
28 changes: 14 additions & 14 deletions custom_components/visonic/examples/simple_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
CONF_DOWNLOAD_CODE = "download_code"
CONF_LANGUAGE = "language"
CONF_EMULATION_MODE = "emulation_mode"
CONF_SIREN_SOUNDING = "siren_sounding"
#CONF_SIREN_SOUNDING = "siren_sounding"

class ConnectionMode(Enum):
POWERLINK = 1
Expand All @@ -36,9 +36,9 @@ class ConnectionMode(Enum):

myconfig = {
CONF_DOWNLOAD_CODE: "",
CONF_EMULATION_MODE: ConnectionMode.POWERLINK,
CONF_LANGUAGE: "Panel",
CONF_SIREN_SOUNDING: ["Intruder"]
CONF_EMULATION_MODE: ConnectionMode.POWERLINK
# CONF_LANGUAGE: "EN"
# CONF_SIREN_SOUNDING: ["Intruder"]
}

def toBool(val) -> bool:
Expand Down Expand Up @@ -108,9 +108,9 @@ def getConfigData() -> PanelConfig:
return {
AlConfiguration.DownloadCode: myconfig.get(CONF_DOWNLOAD_CODE, ""),
AlConfiguration.ForceStandard: ForceStandardMode,
AlConfiguration.DisableAllCommands: DisableAllCommands,
AlConfiguration.PluginLanguage: myconfig.get(CONF_LANGUAGE, "Panel"),
AlConfiguration.SirenTriggerList: myconfig.get(CONF_SIREN_SOUNDING, ["Intruder"])
AlConfiguration.DisableAllCommands: DisableAllCommands
#AlConfiguration.PluginLanguage: myconfig.get(CONF_LANGUAGE, "Panel"),
#AlConfiguration.SirenTriggerList: myconfig.get(CONF_SIREN_SOUNDING, ["Intruder"])
}

def callback_handler(visonic_devices, dict={}):
Expand All @@ -119,14 +119,14 @@ def callback_handler(visonic_devices, dict={}):
_LOGGER.debug("Visonic attempt to add device when sensor is undefined")
return
if type(visonic_devices) == defaultdict:
_LOGGER.debug("Visonic got new sensors {0}".format(visonic_devices))
_LOGGER.debug(f"Visonic got new sensors {visonic_devices}")
elif type(visonic_devices) == pyvisonic.SensorDevice:
# This is an update of an existing device
_LOGGER.debug("Visonic got a sensor update {0}".format(visonic_devices))
_LOGGER.debug(f"Visonic got a sensor update {visonic_devices}")
elif type(visonic_devices) == int:
_LOGGER.debug("Visonic got an Event {0} {1}".format(visonic_devices,dict))
_LOGGER.debug(f"Visonic got an Event {visonic_devices} {dict}")
else:
_LOGGER.debug("Visonic attempt to add device with type {0} device is {1}".format(type(visonic_devices), visonic_devices))
_LOGGER.debug(f"Visonic attempt to add device with type {type(visonic_devices)} device is {visonic_devices}")

def onNewSwitch(dev: AlSwitchDevice):
"""Process a new x10."""
Expand Down Expand Up @@ -215,11 +215,11 @@ async def async_create_tcp_visonic_connection(address, port, panelConfig : Panel

except socket.error as _:
err = _
print("Setting TCP socket Options Exception {0}".format(err))
print(f"Setting TCP socket Options Exception {err}")
if sock is not None:
sock.close()
except Exception as exc:
print("Setting TCP Options Exception {0}".format(exc))
print(f"Setting TCP Options Exception {exc}")
return None, None

# Create a connection using asyncio through a linux port (usb or rs232)
Expand Down Expand Up @@ -281,7 +281,7 @@ def format(self, record):
elapsed_seconds = record.created - self.start_time
# using timedelta here for convenient default formatting
elapsed = str(timedelta(seconds=elapsed_seconds))
return "{: <15} <{: <15}:{: >5}> {: >8} {}".format(elapsed, record.filename, record.lineno, record.levelname, record.getMessage())
return f"{elapsed: <15} <{record.filename: <15}:{record.lineno: >5}> {record.levelname: >8} {record.getMessage()}"

# add custom formatter to root logger
formatter = ElapsedFormatter()
Expand Down
2 changes: 1 addition & 1 deletion custom_components/visonic/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
"loggers": ["visonic"],
"requirements": ["Pillow", "pyserial_asyncio"],
"single_config_entry": false,
"version": "0.9.9.5"
"version": "0.9.9.6"
}
19 changes: 10 additions & 9 deletions custom_components/visonic/pyconst.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,13 +325,13 @@ def __init__(self):

def __str__(self):
strn = ""
strn = strn + ("part=None" if self.partition is None else "part={0:<2}".format(self.partition))
strn = strn + (" current=None" if self.current is None else " current={0:<2}".format(self.current))
strn = strn + (" total=None" if self.total is None else " total={0:<2}".format(self.total))
strn = strn + (" time=None" if self.time is None else " time={0:<2}".format(self.time))
strn = strn + (" date=None" if self.date is None else " date={0:<2}".format(self.date))
strn = strn + (" zone=None" if self.zone is None else " zone={0:<2}".format(self.zone))
strn = strn + (" event=None" if self.event is None else " event={0:<2}".format(self.event))
strn = strn + ("part=None" if self.partition is None else f"part={self.partition:<2}")
strn = strn + (" current=None" if self.current is None else f" current={self.current:<2}")
strn = strn + (" total=None" if self.total is None else f" total={self.total:<2}")
#strn = strn + (" time=None" if self.time is None else f" time={self.time:<2}")
strn = strn + (" date=None" if self.dateandtime is None else f" date={self.dateandtime}")
strn = strn + (" zone=None" if self.zone is None else f" zone={self.zone:<2}")
strn = strn + (" event=None" if self.event is None else f" event={self.event:<2}")
return strn


Expand Down Expand Up @@ -405,7 +405,7 @@ def getMotionDelayTime(self) -> str:

# Do not override me
def createFriendlyName(self) -> str:
return "Z{0:0>2}".format(self.getDeviceID())
return f"Z{self.getDeviceID():0>2}"

# Return the sensor model. This is a string such as "Visonic MTT-302" to show in the HA frontend
def getSensorModel(self) -> str:
Expand Down Expand Up @@ -451,7 +451,7 @@ def onChange(self, callback : Callable = None):
def createFriendlyName(self) -> str:
if self.getDeviceID() == 0:
return "PGM"
return "X{0:0>2}".format(self.getDeviceID())
return f"X{self.getDeviceID():0>2}"


class PanelConfig(TypedDict):
Expand Down Expand Up @@ -515,6 +515,7 @@ def getPanelMode(self) -> AlPanelMode:
""" Get the panel Mode e.g. Standard, Powerlink etc. """
return AlPanelMode.UNKNOWN

@abstractmethod
def isPowerMaster(self) -> bool:
""" Get the panel type, PowerMaster or not """
return False
Expand Down
Loading

0 comments on commit 118d7cd

Please sign in to comment.