Skip to content

Commit

Permalink
Code performance updates
Browse files Browse the repository at this point in the history
  • Loading branch information
theyosh committed Oct 13, 2023
1 parent 7d968a2 commit 138459c
Show file tree
Hide file tree
Showing 15 changed files with 131 additions and 283 deletions.
19 changes: 7 additions & 12 deletions hardware/button/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,21 +75,16 @@ def available_hardware(__cls__):

@classproperty
def available_buttons(__cls__):
data = []
for hardware_type, button in __cls__.available_hardware.items():
data.append({"hardware": hardware_type, "name": button.NAME})

return data
return [{"hardware": hardware_type, "name": button.NAME} for hardware_type, button in __cls__.available_hardware.items()]

# Return polymorph relay....
def __new__(cls, _, hardware_type, address, name="", callback=None):
known_buttons = terrariumButton.available_hardware

if hardware_type not in known_buttons:
try:
known_buttons = terrariumButton.available_hardware
return super(terrariumButton, cls).__new__(known_buttons[hardware_type])
except:
raise terrariumButtonException(f"Button of hardware type {hardware_type} is unknown.")

return super(terrariumButton, cls).__new__(known_buttons[hardware_type])

def __init__(self, button_id, _, address, name="", callback=None):
"Create a new button based on type"

Expand All @@ -116,7 +111,7 @@ def __repr__(self):
return f"{self.NAME} named '{self.name}' at address '{self.address}'"

def _run(self):
self._checker["running"] = True
self._checker["running"] = 1
while self._checker["running"]:
new_state = self._get_state()
if new_state != self._device["state"]:
Expand Down Expand Up @@ -220,7 +215,7 @@ def update(self):
return self.state

def stop(self):
self._checker["running"] = False
self._checker["running"] = 0
self._checker["thread"].join()

if not isinstance(self._device["device"], terrariumIOExpander):
Expand Down
8 changes: 4 additions & 4 deletions hardware/button/ldr_button.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class terrariumLDRSensor(terrariumButton):
__CAPACITOR = 1 # in uF

def __run(self):
self._checker["running"] = True
self._checker["running"] = 1
while self._checker["running"]:
count = 0

Expand All @@ -43,9 +43,9 @@ def __run(self):
sleep(0.1)

except KeyboardInterrupt as ex:
self._checker["running"] = False
print(f"Fetch CTRL-c... and now what..? For now.. press again Ctrl-C .. ({ex})")
self.stop()
# print(f"Fetch CTRL-c... and now what..? For now.. press again Ctrl-C .. ({ex})")


def _get_state(self):
return self._device["internal_state"]
Expand All @@ -64,7 +64,7 @@ def calibrate(self, calibration_data):
self.__CAPACITOR = int(calibration_data.get("ldr_capacitor", self.__CAPACITOR))

def stop(self):
self._checker["running"] = False
self._checker["running"] = 0
try:
self.__thread.join()
except Exception as ex:
Expand Down
4 changes: 2 additions & 2 deletions hardware/button/remote_button.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class terrariumRemoteButton(terrariumButton):
__TIMEOUT = 10

def __run(self):
self._checker["running"] = True
self._checker["running"] = 1
while self._checker["running"]:
try:
value = 1 if int(terrariumUtils.get_remote_data(self._device["device"])) != 0 else 0
Expand All @@ -43,7 +43,7 @@ def calibrate(self, calibration_data):
self.__TIMEOUT = int(calibration_data.get("timeout", self.__TIMEOUT))

def stop(self):
self._checker["running"] = False
self._checker["running"] = 0
try:
self.__thread.join()
except Exception as ex:
Expand Down
29 changes: 9 additions & 20 deletions hardware/display/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,20 +63,15 @@ def available_hardware(__cls__):

@classproperty
def available_displays(__cls__):
data = []
for hardware_type, button in __cls__.available_hardware.items():
data.append({"hardware": hardware_type, "name": button.NAME})

return data
return [{"hardware": hardware_type, "name": display.NAME} for hardware_type, display in __cls__.available_hardware.items()]

# Return polymorph relay....
def __new__(cls, device_id, hardware_type, address, title=None, width=16, height=2):
known_displays = terrariumDisplay.available_hardware

if hardware_type not in known_displays:
raise terrariumDisplayException(f"Dislay of hardware type {hardware_type} is unknown.")

return super(terrariumDisplay, cls).__new__(known_displays[hardware_type])
try:
known_displays = terrariumDisplay.available_hardware
return super(terrariumDisplay, cls).__new__(known_displays[hardware_type])
except:
raise terrariumDisplayException(f"Display of hardware type {hardware_type} is unknown.")

def __init__(self, device_id, _, address, title=None, width=16, height=2):
self._device = {
Expand Down Expand Up @@ -118,7 +113,7 @@ def __run(self):
if self._device["device"] is None:
return

self._device["running"] = True
self._device["running"] = 1
while self._device["running"] or not self._device["queue"].empty():
try:
text = self._device["queue"].get(False)
Expand Down Expand Up @@ -209,7 +204,7 @@ def message(self, text):
self._device["queue"].put(text)

def stop(self, wait=True):
self._device["running"] = False
self._device["running"] = 0
if wait:
self._device["queue"].join()

Expand All @@ -226,10 +221,7 @@ def write_text(self, text="", line=1):
# print('Max chars on 1 line: {}'.format(max_chars_per_line))
text = text.split("\n")
if self.__MODE_TEXT_WRAP == self.mode:
temp_lines = []
for line in text:
temp_lines += textwrap.wrap(line, width=max_chars_per_line)
text = temp_lines
text = [textwrap.wrap(line, width=max_chars_per_line) for line in text]

self.clear()

Expand All @@ -241,9 +233,6 @@ def write_text(self, text="", line=1):
max_screen_lines -= 1

line_animations = max(0, len(text) - max_screen_lines)

# print(f'Line animation: {line_animations}, max lines: {max_screen_lines}')

for animation_step in range(line_animations + 1):
# Here we select the max amount of text we can display once (max height) starting with the animation step as start.
# This will make the text shift up with one line each round
Expand Down
9 changes: 4 additions & 5 deletions hardware/io_expander.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@ def available_hardware(__cls__):

# Return polymorph IO expander....
def __new__(cls, hardware_type, address):
known_devices = terrariumIOExpander.available_hardware

if hardware_type not in known_devices:
try:
known_devices = terrariumIOExpander.available_hardware
return super(terrariumIOExpander, cls).__new__(known_devices[hardware_type]())
except:
raise terrariumIOExpanderException(f"IO Expander of hardware type {hardware_type} is unknown.")

return super(terrariumIOExpander, cls).__new__(known_devices[hardware_type]())

def __init__(self, _, address):
self.port = None
self.active_high = True
Expand Down
15 changes: 5 additions & 10 deletions hardware/relay/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,21 +75,16 @@ def available_hardware(__cls__):

@classproperty
def available_relays(__cls__):
data = []
for hardware_type, relay in __cls__.available_hardware.items():
if relay.NAME is not None:
data.append({"hardware": hardware_type, "name": relay.NAME})

return sorted(data, key=itemgetter("name"))
return [{"hardware": hardware_type, "name": relay.NAME} for hardware_type, relay in __cls__.available_hardware.items() if relay.NAME is not None]

# Return polymorph relay....
def __new__(cls, _, hardware_type, address, name="", prev_state=None, callback=None):
known_relays = terrariumRelay.available_hardware

if hardware_type not in known_relays:
try:
known_relays = terrariumRelay.available_hardware
return super(terrariumRelay, cls).__new__(known_relays[hardware_type])
except:
raise terrariumRelayException(f"Relay of hardware type {hardware_type} is unknown.")

return super(terrariumRelay, cls).__new__(known_relays[hardware_type])

def __init__(self, device_id, _, address, name="", prev_state=None, callback=None):
self._device = {
Expand Down
58 changes: 24 additions & 34 deletions hardware/sensor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,45 +97,35 @@ def available_hardware(__cls__):
# Return a list with type and names of supported switches
@classproperty
def available_sensors(__cls__):
data = []
all_types = ["conductivity"] # For now 'conductivity' is only available through script or remote
for hardware_type, sensor in __cls__.available_hardware.items():
if sensor.NAME is not None:
data.append({"hardware": hardware_type, "name": sensor.NAME, "types": sensor.TYPES})
all_types += sensor.TYPES
data = [{"hardware": hardware_type, "name": sensor.NAME, "types": sensor.TYPES} for hardware_type, sensor in __cls__.available_hardware.items() if sensor.NAME is not None]
# not sure why sum works here: https://stackoverflow.com/a/18114563
all_types = list(set(sum([sensor['types'] for sensor in data], []))) + ["conductivity"]

# Remote and script sensors can handle all the known types
all_types = list(set(all_types))
for sensor in data:
if len(sensor["types"]) == 0:
sensor["types"] = all_types

return sorted(data, key=itemgetter("name"))
return data

@classproperty
def sensor_types(__cls__):
sensor_types = []

for sensor in __cls__.available_sensors:
sensor_types += sensor["types"]

return sorted(list(set(sensor_types)))
return list(set(sum([sensor['types'] for sensor in __cls__.available_sensors], [])))

# Return polymorph sensor....
def __new__(cls, _, hardware_type, sensor_type, address, name="", unit_value_callback=None, trigger_callback=None):
known_sensors = terrariumSensor.available_hardware

if hardware_type not in known_sensors:
raise terrariumSensorUnknownHardwareException(
f"Trying to load an unknown hardware device {hardware_type} at address {address} with name {name}"
)

if sensor_type not in known_sensors[hardware_type].TYPES:
raise terrariumSensorInvalidSensorTypeException(
f"Hardware does not have a {sensor_type} sensor at address {address} with name {name}"
)

return super(terrariumSensor, cls).__new__(known_sensors[hardware_type])
try:
known_sensors = terrariumSensor.available_hardware
return super(terrariumSensor, cls).__new__(known_sensors[hardware_type])
except:
if hardware_type not in known_sensors:
raise terrariumSensorUnknownHardwareException(
f"Trying to load an unknown hardware device {hardware_type} at address {address} with name {name}"
)
else:
raise terrariumSensorInvalidSensorTypeException(
f"Hardware does not have a {sensor_type} sensor at address {address} with name {name}"
)

def __init__(self, sensor_id, _, sensor_type, address, name="", unit_value_callback=None, trigger_callback=None):
self._device = {
Expand All @@ -152,8 +142,8 @@ def __init__(self, sensor_id, _, sensor_type, address, name="", unit_value_callb
}

self._sensor_cache = terrariumCache()
self.__unit_value_callback = unit_value_callback
self.__trigger_callback = trigger_callback
# self.__unit_value_callback = unit_value_callback
# self.__trigger_callback = trigger_callback

# Set the properties
self.id = sensor_id
Expand Down Expand Up @@ -267,13 +257,13 @@ def load_hardware(self, reload=False):
# Could not find valid hardware cache. So create a new hardware device
try:
hardware = func_timeout(self._UPDATE_TIME_OUT, self._load_hardware)
if hardware is not None:
# Store the hardware in the cache for unlimited of time
self._sensor_cache.set_data(hardware_cache_key, hardware, -1)
else:
if hardware is None:
# Raise error that hard is not loaded with an unknown message :(
raise terrariumSensorLoadingException(f"Unable to load sensor {self}: Did not return a device.")

# Store the hardware in the cache for unlimited of time
self._sensor_cache.set_data(hardware_cache_key, hardware, -1)

except FunctionTimedOut:
# What ever fails... does not matter, as the data is still None and will raise a terrariumSensorUpdateException and trigger the retry
raise terrariumSensorLoadingException(
Expand Down Expand Up @@ -346,7 +336,7 @@ def __repr__(self):
# Auto discovery of known and connected sensors
@staticmethod
def scan_sensors(unit_value_callback=None, trigger_callback=None, **kwargs):
for _, sensor_device in terrariumSensor.available_hardware.items():
for sensor_device in terrariumSensor.available_hardware.values():
try:
for sensor in sensor_device._scan_sensors(unit_value_callback, trigger_callback, **kwargs):
yield sensor
Expand Down
8 changes: 3 additions & 5 deletions hardware/sensor/meross_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,9 @@ def _get_data(self):
@staticmethod
def _scan_sensors(unit_value_callback=None, trigger_callback=None):
found_devices = []

EMAIL = terrariumUtils.decrypt(os.environ.get("MEROSS_EMAIL", ""))
PASSWORD = terrariumUtils.decrypt(os.environ.get("MEROSS_PASSWORD", ""))

if EMAIL != "" and PASSWORD != "":
if TerrariumMerossCloud.is_enabled:
EMAIL = terrariumUtils.decrypt(os.environ.get("MEROSS_EMAIL", ""))
PASSWORD = terrariumUtils.decrypt(os.environ.get("MEROSS_PASSWORD", ""))
cloud = TerrariumMerossCloud(EMAIL, PASSWORD)
devices = cloud.scan_hardware("sensors")

Expand Down
Loading

0 comments on commit 138459c

Please sign in to comment.