start refactoring the way ha api is called

This commit is contained in:
Johannes
2022-09-14 20:58:51 +02:00
parent 1cbdb05f81
commit c2cfab2faa
5 changed files with 119 additions and 114 deletions

View File

@@ -0,0 +1 @@
ha_api = None

View File

@@ -1,4 +1,5 @@
import uuid import uuid
import apis
class Entity(object): class Entity(object):
def __init__(self, entity_input_config): def __init__(self, entity_input_config):
@@ -76,7 +77,7 @@ class LuiBackendConfig(object):
return target return target
def __init__(self, ha_api, config_in): def __init__(self, ha_api, config_in):
self._ha_api = ha_api apis.ha_api = ha_api
self._config = {} self._config = {}
self._config_cards = [] self._config_cards = []
self._config_screensaver = None self._config_screensaver = None
@@ -142,9 +143,9 @@ class LuiBackendConfig(object):
self.load(config_in) self.load(config_in)
def load(self, inconfig): def load(self, inconfig):
self._ha_api.log("Input config: %s", inconfig) apis.ha_api.log("Input config: %s", inconfig)
self._config = self.dict_recursive_update(inconfig, self._DEFAULT_CONFIG) self._config = self.dict_recursive_update(inconfig, self._DEFAULT_CONFIG)
self._ha_api.log("Loaded config: %s", self._config) apis.ha_api.log("Loaded config: %s", self._config)
# parse cards displayed on panel # parse cards displayed on panel
pos = 0 pos = 0

View File

@@ -1,12 +1,14 @@
import datetime import datetime
import apis
from helper import scale, pos_to_color, rgb_dec565 from helper import scale, pos_to_color, rgb_dec565
from pages import LuiPagesGen from pages import LuiPagesGen
class LuiController(object): class LuiController(object):
def __init__(self, ha_api, config, send_mqtt_msg): def __init__(self, config, send_mqtt_msg):
self._ha_api = ha_api
self._config = config self._config = config
self._send_mqtt_msg = send_mqtt_msg self._send_mqtt_msg = send_mqtt_msg
@@ -15,17 +17,17 @@ class LuiController(object):
# first card (default, after startup) # first card (default, after startup)
self._previous_cards.append(self._config.getCard(0)) self._previous_cards.append(self._config.getCard(0))
self._pages_gen = LuiPagesGen(ha_api, config, send_mqtt_msg) self._pages_gen = LuiPagesGen(config, send_mqtt_msg)
# send panel back to startup page on restart of this script # send panel back to startup page on restart of this script
self._pages_gen.page_type("pageStartup") self._pages_gen.page_type("pageStartup")
# time update callback # time update callback
time = datetime.time(0, 0, 0) time = datetime.time(0, 0, 0)
ha_api.run_minutely(self._pages_gen.update_time, time) apis.ha_api.run_minutely(self._pages_gen.update_time, time)
# Setup date callback # Setup date callback
ha_api.run_daily(self._pages_gen.update_date, time) apis.ha_api.run_daily(self._pages_gen.update_date, time)
# register callbacks # register callbacks
self.register_callbacks() self.register_callbacks()
@@ -37,31 +39,31 @@ class LuiController(object):
# register callbacks for each time # register callbacks for each time
if type(self._config.get("sleepBrightness")) == list: if type(self._config.get("sleepBrightness")) == list:
for index, timeset in enumerate(self._config.get("sleepBrightness")): for index, timeset in enumerate(self._config.get("sleepBrightness")):
self._ha_api.run_daily(self.update_screensaver_brightness, timeset["time"], ssbr=timeset["value"], sbr=self.current_screen_brightness) apis.ha_api.run_daily(self.update_screensaver_brightness, timeset["time"], ssbr=timeset["value"], sbr=self.current_screen_brightness)
# call update_screensaver_brightness on changes of entity configured in sleepTracking # call update_screensaver_brightness on changes of entity configured in sleepTracking
bst = self._config.get("sleepTracking") bst = self._config.get("sleepTracking")
if bst is not None and self._ha_api.entity_exists(bst): if bst is not None and apis.ha_api.entity_exists(bst):
self._ha_api.listen_state(self.update_screensaver_brightness_state_callback, entity_id=bst) apis.ha_api.listen_state(self.update_screensaver_brightness_state_callback, entity_id=bst)
# call update_screensaver_brightness on entity configured in sleepOverride # call update_screensaver_brightness on entity configured in sleepOverride
sleepOverride = self._config.get("sleepOverride") sleepOverride = self._config.get("sleepOverride")
if sleepOverride is not None and type(sleepOverride) is dict and sleepOverride["entity"] is not None and sleepOverride["brightness"] is not None and self._ha_api.entity_exists(sleepOverride["entity"]): if sleepOverride is not None and type(sleepOverride) is dict and sleepOverride["entity"] is not None and sleepOverride["brightness"] is not None and apis.ha_api.entity_exists(sleepOverride["entity"]):
self._ha_api.log(f"Configuring Sleep Override. Config is {sleepOverride}") apis.ha_api.log(f"Configuring Sleep Override. Config is {sleepOverride}")
self._ha_api.listen_state(self.update_screensaver_brightness_state_callback, entity_id=sleepOverride["entity"]) apis.ha_api.listen_state(self.update_screensaver_brightness_state_callback, entity_id=sleepOverride["entity"])
# register callback for state changes on tracked value (for input_number) - sleepBrightness # register callback for state changes on tracked value (for input_number) - sleepBrightness
sleep_brightness_config = self._config.get("sleepBrightness") sleep_brightness_config = self._config.get("sleepBrightness")
if type(sleep_brightness_config) == str and self._ha_api.entity_exists(sleep_brightness_config): if type(sleep_brightness_config) == str and apis.ha_api.entity_exists(sleep_brightness_config):
self._ha_api.listen_state(self.update_screensaver_brightness_state_callback, entity_id=sleep_brightness_config) apis.ha_api.listen_state(self.update_screensaver_brightness_state_callback, entity_id=sleep_brightness_config)
# register callback for state changes on tracked value (for input_number) - screenBrightness # register callback for state changes on tracked value (for input_number) - screenBrightness
screen_brightness_config = self._config.get("screenBrightness") screen_brightness_config = self._config.get("screenBrightness")
if type(screen_brightness_config) == str and self._ha_api.entity_exists(screen_brightness_config): if type(screen_brightness_config) == str and apis.ha_api.entity_exists(screen_brightness_config):
self._ha_api.listen_state(self.update_screensaver_brightness_state_callback, entity_id=screen_brightness_config) apis.ha_api.listen_state(self.update_screensaver_brightness_state_callback, entity_id=screen_brightness_config)
def startup(self): def startup(self):
self._ha_api.log(f"Startup Event") apis.ha_api.log(f"Startup Event")
# send time and date on startup # send time and date on startup
self._pages_gen.update_time("") self._pages_gen.update_time("")
self._pages_gen.update_date("") self._pages_gen.update_date("")
@@ -94,12 +96,12 @@ class LuiController(object):
sleepBrightness = 0 sleepBrightness = 0
brightness = self.calc_current_brightness(self._config.get("screenBrightness")) brightness = self.calc_current_brightness(self._config.get("screenBrightness"))
if bst is not None and self._ha_api.entity_exists(bst) and self._ha_api.get_entity(bst).state in self._config.get("sleepTrackingZones"): if bst is not None and apis.ha_api.entity_exists(bst) and apis.ha_api.get_entity(bst).state in self._config.get("sleepTrackingZones"):
self._ha_api.log(f"sleepTracking setting brightness to 0") apis.ha_api.log(f"sleepTracking setting brightness to 0")
sleepBrightness = 0 sleepBrightness = 0
elif sOEntity is not None and sOBrightness is not None and self._ha_api.entity_exists(sOEntity) and self._ha_api.get_entity(sOEntity).state in ["on", "true", "home"]: elif sOEntity is not None and sOBrightness is not None and apis.ha_api.entity_exists(sOEntity) and apis.ha_api.get_entity(sOEntity).state in ["on", "true", "home"]:
self._ha_api.log(f"sleepOverride setting brightness to {sOBrightness}") apis.ha_api.log(f"sleepOverride setting brightness to {sOBrightness}")
sleepBrightness = sOBrightness sleepBrightness = sOBrightness
else: else:
@@ -131,34 +133,34 @@ class LuiController(object):
if type(sleep_brightness_config) == int: if type(sleep_brightness_config) == int:
current_screensaver_brightness = sleep_brightness_config current_screensaver_brightness = sleep_brightness_config
elif type(sleep_brightness_config) == str: elif type(sleep_brightness_config) == str:
current_screensaver_brightness = int(float(self._ha_api.get_state(sleep_brightness_config))) current_screensaver_brightness = int(float(apis.ha_api.get_state(sleep_brightness_config)))
elif type(sleep_brightness_config) == list: elif type(sleep_brightness_config) == list:
sorted_timesets = sorted(sleep_brightness_config, key=lambda d: self._ha_api.parse_time(d['time'])) sorted_timesets = sorted(sleep_brightness_config, key=lambda d: apis.ha_api.parse_time(d['time']))
# calc current screensaver brightness # calc current screensaver brightness
found_current_dim_value = False found_current_dim_value = False
for i in range(len(sorted_timesets)): for i in range(len(sorted_timesets)):
found = self._ha_api.now_is_between(sorted_timesets[i-1]['time'], sorted_timesets[i]['time']) found = apis.ha_api.now_is_between(sorted_timesets[i-1]['time'], sorted_timesets[i]['time'])
if found: if found:
found_current_dim_value = True found_current_dim_value = True
current_screensaver_brightness = sorted_timesets[i-1]['value'] current_screensaver_brightness = sorted_timesets[i-1]['value']
# still no dim value # still no dim value
if not found_current_dim_value: if not found_current_dim_value:
self._ha_api.log("Chooseing %s as fallback", sorted_timesets[0]) apis.ha_api.log("Chooseing %s as fallback", sorted_timesets[0])
current_screensaver_brightness = sorted_timesets[0]["value"] current_screensaver_brightness = sorted_timesets[0]["value"]
return current_screensaver_brightness return current_screensaver_brightness
def register_callbacks(self): def register_callbacks(self):
items = self._config.get_all_entity_names() items = self._config.get_all_entity_names()
self._ha_api.log(f"Registering callbacks for the following items: {items}") apis.ha_api.log(f"Registering callbacks for the following items: {items}")
for item in items: for item in items:
if self._ha_api.entity_exists(item): if apis.ha_api.entity_exists(item):
self._ha_api.listen_state(self.state_change_callback, entity_id=item, attribute="all") apis.ha_api.listen_state(self.state_change_callback, entity_id=item, attribute="all")
def state_change_callback(self, entity, attribute, old, new, kwargs): def state_change_callback(self, entity, attribute, old, new, kwargs):
self._ha_api.log(f"Got callback for: {entity}", level="DEBUG") apis.ha_api.log(f"Got callback for: {entity}", level="DEBUG")
self._ha_api.log(f"Current page has the following items: {self._current_card.get_entity_names()}", level="DEBUG") apis.ha_api.log(f"Current page has the following items: {self._current_card.get_entity_names()}", level="DEBUG")
if entity in self._current_card.get_entity_names(): if entity in self._current_card.get_entity_names():
self._ha_api.log(f"Callback Entity is on current page: {entity}", level="DEBUG") apis.ha_api.log(f"Callback Entity is on current page: {entity}", level="DEBUG")
self._pages_gen.render_card(self._current_card, send_page_type=False) self._pages_gen.render_card(self._current_card, send_page_type=False)
# send detail page update, just in case # send detail page update, just in case
if self._current_card.cardType in ["cardGrid", "cardEntities"]: if self._current_card.cardType in ["cardGrid", "cardEntities"]:
@@ -179,16 +181,16 @@ class LuiController(object):
self._pages_gen.generate_fan_detail_page(entity_id) self._pages_gen.generate_fan_detail_page(entity_id)
def button_press(self, entity_id, button_type, value): def button_press(self, entity_id, button_type, value):
self._ha_api.log(f"Button Press Event; entity_id: {entity_id}; button_type: {button_type}; value: {value} ") apis.ha_api.log(f"Button Press Event; entity_id: {entity_id}; button_type: {button_type}; value: {value} ")
# internal buttons # internal buttons
if entity_id == "screensaver" and button_type == "bExit": if entity_id == "screensaver" and button_type == "bExit":
# get default card if there is one # get default card if there is one
defaultCard = self._config.get("screensaver.defaultCard") defaultCard = self._config.get("screensaver.defaultCard")
if defaultCard is not None: if defaultCard is not None:
defaultCard = self._ha_api.render_template(defaultCard) defaultCard = apis.ha_api.render_template(defaultCard)
self._ha_api.log(f"Searching for the following page as defaultPage: {defaultCard}") apis.ha_api.log(f"Searching for the following page as defaultPage: {defaultCard}")
dstCard = self._config.searchCard(defaultCard) dstCard = self._config.searchCard(defaultCard)
self._ha_api.log(f"Result for the following page as defaultPage: {dstCard}") apis.ha_api.log(f"Result for the following page as defaultPage: {dstCard}")
if dstCard is not None: if dstCard is not None:
self._previous_cards = [] self._previous_cards = []
self._previous_cards.append(dstCard) self._previous_cards.append(dstCard)
@@ -231,37 +233,37 @@ class LuiController(object):
# buttons with actions on HA # buttons with actions on HA
if button_type == "OnOff": if button_type == "OnOff":
if value == "1": if value == "1":
self._ha_api.turn_on(entity_id) apis.ha_api.turn_on(entity_id)
else: else:
self._ha_api.turn_off(entity_id) apis.ha_api.turn_off(entity_id)
if button_type == "number-set": if button_type == "number-set":
if entity_id.startswith('fan'): if entity_id.startswith('fan'):
entity = self._ha_api.get_entity(entity_id) entity = apis.ha_api.get_entity(entity_id)
value = float(value)*float(entity.attributes.get("percentage_step", 0)) value = float(value)*float(entity.attributes.get("percentage_step", 0))
entity.call_service("set_percentage", percentage=value) entity.call_service("set_percentage", percentage=value)
else: else:
self._ha_api.get_entity(entity_id).call_service("set_value", value=value) apis.ha_api.get_entity(entity_id).call_service("set_value", value=value)
# for shutter / covers # for shutter / covers
if button_type == "up": if button_type == "up":
self._ha_api.get_entity(entity_id).call_service("open_cover") apis.ha_api.get_entity(entity_id).call_service("open_cover")
if button_type == "stop": if button_type == "stop":
self._ha_api.get_entity(entity_id).call_service("stop_cover") apis.ha_api.get_entity(entity_id).call_service("stop_cover")
if button_type == "down": if button_type == "down":
self._ha_api.get_entity(entity_id).call_service("close_cover") apis.ha_api.get_entity(entity_id).call_service("close_cover")
if button_type == "positionSlider": if button_type == "positionSlider":
pos = int(value) pos = int(value)
self._ha_api.get_entity(entity_id).call_service("set_cover_position", position=pos) apis.ha_api.get_entity(entity_id).call_service("set_cover_position", position=pos)
if button_type == "tiltOpen": if button_type == "tiltOpen":
self._ha_api.get_entity(entity_id).call_service("open_cover_tilt") apis.ha_api.get_entity(entity_id).call_service("open_cover_tilt")
if button_type == "tiltStop": if button_type == "tiltStop":
self._ha_api.get_entity(entity_id).call_service("stop_cover_tilt") apis.ha_api.get_entity(entity_id).call_service("stop_cover_tilt")
if button_type == "tiltClose": if button_type == "tiltClose":
self._ha_api.get_entity(entity_id).call_service("close_cover_tilt") apis.ha_api.get_entity(entity_id).call_service("close_cover_tilt")
if button_type == "tiltSlider": if button_type == "tiltSlider":
pos = int(value) pos = int(value)
self._ha_api.get_entity(entity_id).call_service("set_cover_tilt_position", position=pos) apis.ha_api.get_entity(entity_id).call_service("set_cover_tilt_position", position=pos)
if button_type == "button": if button_type == "button":
@@ -277,92 +279,92 @@ class LuiController(object):
self._current_card = dstCard self._current_card = dstCard
self._pages_gen.render_card(self._current_card) self._pages_gen.render_card(self._current_card)
else: else:
self._ha_api.log(f"No page with key {entity_id} found") apis.ha_api.log(f"No page with key {entity_id} found")
elif entity_id.startswith('scene'): elif entity_id.startswith('scene'):
self._ha_api.get_entity(entity_id).call_service("turn_on") apis.ha_api.get_entity(entity_id).call_service("turn_on")
elif entity_id.startswith('script'): elif entity_id.startswith('script'):
self._ha_api.get_entity(entity_id).call_service("turn_on") apis.ha_api.get_entity(entity_id).call_service("turn_on")
elif entity_id.startswith('light') or entity_id.startswith('switch') or entity_id.startswith('input_boolean') or entity_id.startswith('automation') or entity_id.startswith('fan'): elif entity_id.startswith('light') or entity_id.startswith('switch') or entity_id.startswith('input_boolean') or entity_id.startswith('automation') or entity_id.startswith('fan'):
self._ha_api.get_entity(entity_id).call_service("toggle") apis.ha_api.get_entity(entity_id).call_service("toggle")
elif entity_id.startswith('lock'): elif entity_id.startswith('lock'):
if self._ha_api.get_entity(entity_id).state == "locked": if apis.ha_api.get_entity(entity_id).state == "locked":
self._ha_api.get_entity(entity_id).call_service("unlock") apis.ha_api.get_entity(entity_id).call_service("unlock")
else: else:
self._ha_api.get_entity(entity_id).call_service("lock") apis.ha_api.get_entity(entity_id).call_service("lock")
elif entity_id.startswith('button') or entity_id.startswith('input_button'): elif entity_id.startswith('button') or entity_id.startswith('input_button'):
self._ha_api.get_entity(entity_id).call_service("press") apis.ha_api.get_entity(entity_id).call_service("press")
elif entity_id.startswith('input_select'): elif entity_id.startswith('input_select'):
self._ha_api.get_entity(entity_id).call_service("select_next") apis.ha_api.get_entity(entity_id).call_service("select_next")
elif entity_id.startswith('vacuum'): elif entity_id.startswith('vacuum'):
if self._ha_api.get_entity(entity_id).state == "docked": if apis.ha_api.get_entity(entity_id).state == "docked":
self._ha_api.get_entity(entity_id).call_service("start") apis.ha_api.get_entity(entity_id).call_service("start")
else: else:
self._ha_api.get_entity(entity_id).call_service("return_to_base") apis.ha_api.get_entity(entity_id).call_service("return_to_base")
elif entity_id.startswith('service'): elif entity_id.startswith('service'):
self._ha_api.call_service(entity_id.replace('service.', '', 1).replace('.','/', 1), **le.data) apis.ha_api.call_service(entity_id.replace('service.', '', 1).replace('.','/', 1), **le.data)
# for media page # for media page
if button_type == "media-next": if button_type == "media-next":
self._ha_api.get_entity(entity_id).call_service("media_next_track") apis.ha_api.get_entity(entity_id).call_service("media_next_track")
if button_type == "media-back": if button_type == "media-back":
self._ha_api.get_entity(entity_id).call_service("media_previous_track") apis.ha_api.get_entity(entity_id).call_service("media_previous_track")
if button_type == "media-pause": if button_type == "media-pause":
self._ha_api.get_entity(entity_id).call_service("media_play_pause") apis.ha_api.get_entity(entity_id).call_service("media_play_pause")
if button_type == "media-OnOff": if button_type == "media-OnOff":
if self._ha_api.get_entity(entity_id).state == "off": if apis.ha_api.get_entity(entity_id).state == "off":
self._ha_api.get_entity(entity_id).call_service("turn_on") apis.ha_api.get_entity(entity_id).call_service("turn_on")
else: else:
self._ha_api.get_entity(entity_id).call_service("turn_off") apis.ha_api.get_entity(entity_id).call_service("turn_off")
if button_type == "volumeSlider": if button_type == "volumeSlider":
pos = int(value) pos = int(value)
# HA wants this value between 0 and 1 as float # HA wants this value between 0 and 1 as float
pos = pos/100 pos = pos/100
self._ha_api.get_entity(entity_id).call_service("volume_set", volume_level=pos) apis.ha_api.get_entity(entity_id).call_service("volume_set", volume_level=pos)
if button_type == "speaker-sel": if button_type == "speaker-sel":
self._ha_api.get_entity(entity_id).call_service("select_source", source=value) apis.ha_api.get_entity(entity_id).call_service("select_source", source=value)
# for light detail page # for light detail page
if button_type == "brightnessSlider": if button_type == "brightnessSlider":
# scale 0-100 to ha brightness range # scale 0-100 to ha brightness range
brightness = int(scale(int(value),(0,100),(0,255))) brightness = int(scale(int(value),(0,100),(0,255)))
self._ha_api.get_entity(entity_id).call_service("turn_on", brightness=brightness) apis.ha_api.get_entity(entity_id).call_service("turn_on", brightness=brightness)
if button_type == "colorTempSlider": if button_type == "colorTempSlider":
entity = self._ha_api.get_entity(entity_id) entity = apis.ha_api.get_entity(entity_id)
#scale 0-100 from slider to color range of lamp #scale 0-100 from slider to color range of lamp
color_val = scale(int(value), (0, 100), (entity.attributes.min_mireds, entity.attributes.max_mireds)) color_val = scale(int(value), (0, 100), (entity.attributes.min_mireds, entity.attributes.max_mireds))
self._ha_api.get_entity(entity_id).call_service("turn_on", color_temp=color_val) apis.ha_api.get_entity(entity_id).call_service("turn_on", color_temp=color_val)
if button_type == "colorWheel": if button_type == "colorWheel":
self._ha_api.log(value) apis.ha_api.log(value)
value = value.split('|') value = value.split('|')
color = pos_to_color(int(value[0]), int(value[1]), int(value[2])) color = pos_to_color(int(value[0]), int(value[1]), int(value[2]))
self._ha_api.log(color) apis.ha_api.log(color)
self._ha_api.get_entity(entity_id).call_service("turn_on", rgb_color=color) apis.ha_api.get_entity(entity_id).call_service("turn_on", rgb_color=color)
# for climate page # for climate page
if button_type == "tempUpd": if button_type == "tempUpd":
temp = int(value)/10 temp = int(value)/10
self._ha_api.get_entity(entity_id).call_service("set_temperature", temperature=temp) apis.ha_api.get_entity(entity_id).call_service("set_temperature", temperature=temp)
if button_type == "tempUpdHighLow": if button_type == "tempUpdHighLow":
value = value.split("|") value = value.split("|")
temp_high = int(value[0])/10 temp_high = int(value[0])/10
temp_low = int(value[1])/10 temp_low = int(value[1])/10
self._ha_api.get_entity(entity_id).call_service("set_temperature", target_temp_high=temp_high, target_temp_low=temp_low) apis.ha_api.get_entity(entity_id).call_service("set_temperature", target_temp_high=temp_high, target_temp_low=temp_low)
if button_type == "hvac_action": if button_type == "hvac_action":
self._ha_api.get_entity(entity_id).call_service("set_hvac_mode", hvac_mode=value) apis.ha_api.get_entity(entity_id).call_service("set_hvac_mode", hvac_mode=value)
# for alarm page # for alarm page
if button_type in ["disarm", "arm_home", "arm_away", "arm_night", "arm_vacation"]: if button_type in ["disarm", "arm_home", "arm_away", "arm_night", "arm_vacation"]:
self._ha_api.get_entity(entity_id).call_service(f"alarm_{button_type}", code=value) apis.ha_api.get_entity(entity_id).call_service(f"alarm_{button_type}", code=value)
if button_type == "opnSensorNotify": if button_type == "opnSensorNotify":
msg = "" msg = ""
entity = self._ha_api.get_entity(entity_id) entity = apis.ha_api.get_entity(entity_id)
if "open_sensors" in entity.attributes and entity.attributes.open_sensors is not None: if "open_sensors" in entity.attributes and entity.attributes.open_sensors is not None:
for e in entity.attributes.open_sensors: for e in entity.attributes.open_sensors:
msg += f"- {self._ha_api.get_entity(e).attributes.friendly_name}\r\n" msg += f"- {apis.ha_api.get_entity(e).attributes.friendly_name}\r\n"
self._pages_gen.send_message_page("opnSensorNotifyRes", "", msg, "", "") self._pages_gen.send_message_page("opnSensorNotifyRes", "", msg, "", "")
# for fan popup / preset selection # for fan popup / preset selection
if button_type == "mode-sel": if button_type == "mode-sel":
entity = self._ha_api.get_entity(entity_id) entity = apis.ha_api.get_entity(entity_id)
preset_mode = entity.attributes.preset_modes[int(value)] preset_mode = entity.attributes.preset_modes[int(value)]
entity.call_service("set_preset_mode", preset_mode=preset_mode) entity.call_service("set_preset_mode", preset_mode=preset_mode)

View File

@@ -1,6 +1,8 @@
import datetime import datetime
import dateutil.parser as dp import dateutil.parser as dp
import apis
from theme import get_screensaver_color_output from theme import get_screensaver_color_output
from icon_mapping import get_icon_id from icon_mapping import get_icon_id
from icons import get_icon_id_ha from icons import get_icon_id_ha
@@ -16,8 +18,7 @@ if babel_spec is not None:
class LuiPagesGen(object): class LuiPagesGen(object):
def __init__(self, ha_api, config, send_mqtt_msg): def __init__(self, config, send_mqtt_msg):
self._ha_api = ha_api
self._config = config self._config = config
self._locale = config.get("locale") self._locale = config.get("locale")
self._send_mqtt_msg = send_mqtt_msg self._send_mqtt_msg = send_mqtt_msg
@@ -62,7 +63,7 @@ class LuiPagesGen(object):
def update_time(self, kwargs): def update_time(self, kwargs):
time = datetime.datetime.now().strftime(self._config.get("timeFormat")) time = datetime.datetime.now().strftime(self._config.get("timeFormat"))
addTemplate = self._config.get("timeAdditionalTemplate") addTemplate = self._config.get("timeAdditionalTemplate")
addTimeText = self._ha_api.render_template(addTemplate) addTimeText = apis.ha_api.render_template(addTemplate)
self._send_mqtt_msg(f"time~{time}~{addTimeText}") self._send_mqtt_msg(f"time~{time}~{addTimeText}")
def update_date(self, kwargs): def update_date(self, kwargs):
@@ -75,7 +76,7 @@ class LuiPagesGen(object):
date = datetime.datetime.now().strftime(dateformat) date = datetime.datetime.now().strftime(dateformat)
addTemplate = self._config.get("dateAdditionalTemplate") addTemplate = self._config.get("dateAdditionalTemplate")
addDateText = self._ha_api.render_template(addTemplate) addDateText = apis.ha_api.render_template(addTemplate)
self._send_mqtt_msg(f"date~{date}{addDateText}") self._send_mqtt_msg(f"date~{date}{addDateText}")
def page_type(self, target_page): def page_type(self, target_page):
@@ -87,10 +88,10 @@ class LuiPagesGen(object):
unit = self._config._config_screensaver.raw_config.get("weatherUnit", "celsius") unit = self._config._config_screensaver.raw_config.get("weatherUnit", "celsius")
state = {} state = {}
if self._ha_api.entity_exists(we_name): if apis.ha_api.entity_exists(we_name):
we = self._ha_api.get_entity(we_name) we = apis.ha_api.get_entity(we_name)
else: else:
self._ha_api.error(f"Skipping Weather Update, entity {we_name} not found") apis.ha_api.error(f"Skipping Weather Update, entity {we_name} not found")
return return
icon_cur = get_icon_id_ha("weather", state=we.state) icon_cur = get_icon_id_ha("weather", state=we.state)
@@ -135,10 +136,10 @@ class LuiPagesGen(object):
icon = "" icon = ""
down = "" down = ""
else: else:
self._ha_api.log(f"Forecast {i} is overriden with {wOF}") apis.ha_api.log(f"Forecast {i} is overriden with {wOF}")
icon = wOF.get("icon") icon = wOF.get("icon")
name = wOF.get("name") name = wOF.get("name")
entity = self._ha_api.get_entity(wOF.get("entity")) entity = apis.ha_api.get_entity(wOF.get("entity"))
up = name if name is not None else entity.attributes.friendly_name up = name if name is not None else entity.attributes.friendly_name
icon = get_icon_id_ha("sensor", state=entity.state, device_class=entity.attributes.get("device_class", ""), overwrite=icon) icon = get_icon_id_ha("sensor", state=entity.state, device_class=entity.attributes.get("device_class", ""), overwrite=icon)
if "color" in wOF: if "color" in wOF:
@@ -172,7 +173,7 @@ class LuiPagesGen(object):
statusIcon = self._config._config_screensaver.raw_config.get(f"statusIcon{i}") statusIcon = self._config._config_screensaver.raw_config.get(f"statusIcon{i}")
if statusIcon is not None: if statusIcon is not None:
icon = statusIcon.get("icon") icon = statusIcon.get("icon")
entity = self._ha_api.get_entity(statusIcon.get("entity")) entity = apis.ha_api.get_entity(statusIcon.get("entity"))
entityType = statusIcon.get("entity").split(".")[0] entityType = statusIcon.get("entity").split(".")[0]
icon = get_icon_id_ha(entityType, state=entity.state, device_class=entity.attributes.get("device_class", ""), overwrite=icon) icon = get_icon_id_ha(entityType, state=entity.state, device_class=entity.attributes.get("device_class", ""), overwrite=icon)
color = self.get_entity_color(entity, overwrite=statusIcon.get("color", None)) color = self.get_entity_color(entity, overwrite=statusIcon.get("color", None))
@@ -195,7 +196,7 @@ class LuiPagesGen(object):
# type of the item is the string before the "." in the entityId # type of the item is the string before the "." in the entityId
entityType = entityId.split(".")[0] entityType = entityId.split(".")[0]
self._ha_api.log(f"Generating item for {entityId} with type {entityType}", level="DEBUG") apis.ha_api.log(f"Generating item for {entityId} with type {entityType}", level="DEBUG")
# Internal types # Internal types
if entityType == "delete": if entityType == "delete":
return f"~{entityType}~~~~~" return f"~{entityType}~~~~~"
@@ -206,8 +207,8 @@ class LuiPagesGen(object):
status_entity = None status_entity = None
name = name if name is not None else page_search_res.title name = name if name is not None else page_search_res.title
text = get_translation(self._locale, "frontend.ui.card.button.press") text = get_translation(self._locale, "frontend.ui.card.button.press")
if item.status is not None and self._ha_api.entity_exists(item.status): if item.status is not None and apis.ha_api.entity_exists(item.status):
status_entity = self._ha_api.get_entity(item.status) status_entity = apis.ha_api.get_entity(item.status)
icon_res = get_icon_id_ha(item.status.split(".")[0], state=status_entity.state, device_class=status_entity.attributes.get("device_class", "_"), overwrite=icon) icon_res = get_icon_id_ha(item.status.split(".")[0], state=status_entity.state, device_class=status_entity.attributes.get("device_class", "_"), overwrite=icon)
icon_color = self.get_entity_color(status_entity, ha_type=item.status.split(".")[0], overwrite=colorOverride) icon_color = self.get_entity_color(status_entity, ha_type=item.status.split(".")[0], overwrite=colorOverride)
if item.status.startswith("sensor") and cardType == "cardGrid": if item.status.startswith("sensor") and cardType == "cardGrid":
@@ -228,8 +229,8 @@ class LuiPagesGen(object):
icon_id = get_icon_id_ha("script", overwrite=icon) icon_id = get_icon_id_ha("script", overwrite=icon)
text = get_translation(self._locale, "frontend.ui.card.script.run") text = get_translation(self._locale, "frontend.ui.card.script.run")
icon_color = 17299 icon_color = 17299
if item.status is not None and self._ha_api.entity_exists(item.status): if item.status is not None and apis.ha_api.entity_exists(item.status):
status_entity = self._ha_api.get_entity(item.status) status_entity = apis.ha_api.get_entity(item.status)
icon_id = get_icon_id_ha(item.status.split(".")[0], state=status_entity.state, device_class=status_entity.attributes.get("device_class", "_"), overwrite=icon) icon_id = get_icon_id_ha(item.status.split(".")[0], state=status_entity.state, device_class=status_entity.attributes.get("device_class", "_"), overwrite=icon)
icon_color = self.get_entity_color(status_entity, ha_type=item.status.split(".")[0], overwrite=colorOverride) icon_color = self.get_entity_color(status_entity, ha_type=item.status.split(".")[0], overwrite=colorOverride)
if item.status.startswith("sensor") and cardType == "cardGrid": if item.status.startswith("sensor") and cardType == "cardGrid":
@@ -237,11 +238,11 @@ class LuiPagesGen(object):
if icon_id[-1] == ".": if icon_id[-1] == ".":
icon_id = icon_id[:-1] icon_id = icon_id[:-1]
return f"~button~{uuid}~{icon_id}~{icon_color}~{name}~{text}" return f"~button~{uuid}~{icon_id}~{icon_color}~{name}~{text}"
if not self._ha_api.entity_exists(entityId): if not apis.ha_api.entity_exists(entityId):
return f"~text~{entityId}~{get_icon_id('alert-circle-outline')}~17299~Not found check~ apps.yaml" return f"~text~{entityId}~{get_icon_id('alert-circle-outline')}~17299~Not found check~ apps.yaml"
# HA Entities # HA Entities
entity = self._ha_api.get_entity(entityId) entity = apis.ha_api.get_entity(entityId)
# check state for if a condition is defined # check state for if a condition is defined
if item.condState is not None and item.condState == entity.state: if item.condState is not None and item.condState == entity.state:
return "" return ""
@@ -366,10 +367,10 @@ class LuiPagesGen(object):
temperature_unit_icon = get_icon_id("temperature-fahrenheit") temperature_unit_icon = get_icon_id("temperature-fahrenheit")
temperature_unit = "°F" temperature_unit = "°F"
if not self._ha_api.entity_exists(item): if not apis.ha_api.entity_exists(item):
command = f"entityUpd~Not found~{navigation}~{item}~check~220~apps.yaml~150~300~5~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Please~your~~" command = f"entityUpd~Not found~{navigation}~{item}~check~220~apps.yaml~150~300~5~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Please~your~~"
else: else:
entity = self._ha_api.get_entity(item) entity = apis.ha_api.get_entity(item)
heading = title if title != "unknown" else entity.attributes.friendly_name heading = title if title != "unknown" else entity.attributes.friendly_name
current_temp = get_attr_safe(entity, "current_temperature", "") current_temp = get_attr_safe(entity, "current_temperature", "")
dest_temp = get_attr_safe(entity, "temperature", None) dest_temp = get_attr_safe(entity, "temperature", None)
@@ -445,10 +446,10 @@ class LuiPagesGen(object):
def generate_media_page(self, navigation, title, entity, mediaBtn): def generate_media_page(self, navigation, title, entity, mediaBtn):
item = entity.entityId item = entity.entityId
if not self._ha_api.entity_exists(item): if not apis.ha_api.entity_exists(item):
command = f"entityUpd~Not found~{navigation}~{item}~{get_icon_id('alert-circle-outline')}~Please check your~apps.yaml in AppDaemon~~0~{get_icon_id('alert-circle-outline')}~~~disable" command = f"entityUpd~Not found~{navigation}~{item}~{get_icon_id('alert-circle-outline')}~Please check your~apps.yaml in AppDaemon~~0~{get_icon_id('alert-circle-outline')}~~~disable"
else: else:
entity = self._ha_api.get_entity(item) entity = apis.ha_api.get_entity(item)
heading = title if title != "unknown" else entity.attributes.friendly_name heading = title if title != "unknown" else entity.attributes.friendly_name
icon = get_icon_id('speaker-off') icon = get_icon_id('speaker-off')
title = get_attr_safe(entity, "media_title", "") title = get_attr_safe(entity, "media_title", "")
@@ -479,10 +480,10 @@ class LuiPagesGen(object):
def generate_alarm_page(self, navigation, entity, overwrite_supported_modes, alarmBtn): def generate_alarm_page(self, navigation, entity, overwrite_supported_modes, alarmBtn):
item = entity.entityId item = entity.entityId
if not self._ha_api.entity_exists(item): if not apis.ha_api.entity_exists(item):
command = f"entityUpd~{item}~{navigation}~Not found~Not found~Check your~Check your~apps.~apps.~yaml~yaml~0~~0" command = f"entityUpd~{item}~{navigation}~Not found~Not found~Check your~Check your~apps.~apps.~yaml~yaml~0~~0"
else: else:
entity = self._ha_api.get_entity(item) entity = apis.ha_api.get_entity(item)
icon = get_icon_id("shield-off") icon = get_icon_id("shield-off")
color = rgb_dec565([255,255,255]) color = rgb_dec565([255,255,255])
supported_modes = [] supported_modes = []
@@ -538,8 +539,8 @@ class LuiPagesGen(object):
entity = alarmBtn.get("entity") entity = alarmBtn.get("entity")
iconnav = get_icon_id_ha("alarm-arm-fail", overwrite=alarmBtn.get("icon")) iconnav = get_icon_id_ha("alarm-arm-fail", overwrite=alarmBtn.get("icon"))
status = alarmBtn.get("status") status = alarmBtn.get("status")
if status is not None and self._ha_api.entity_exists(status): if status is not None and apis.ha_api.entity_exists(status):
icon_color = self.get_entity_color(self._ha_api.get_entity(status)) icon_color = self.get_entity_color(apis.ha_api.get_entity(status))
else: else:
icon_color = rgb_dec565([243,179,0]) icon_color = rgb_dec565([243,179,0])
add_btn=f"{iconnav}~{icon_color}~{entity}" add_btn=f"{iconnav}~{icon_color}~{entity}"
@@ -556,7 +557,7 @@ class LuiPagesGen(object):
def generate_qr_page(self, navigation, heading, items, cardType, qrcode): def generate_qr_page(self, navigation, heading, items, cardType, qrcode):
qrcode = self._ha_api.render_template(qrcode) qrcode = apis.ha_api.render_template(qrcode)
command = f"entityUpd~{heading}~{navigation}~{qrcode}" command = f"entityUpd~{heading}~{navigation}~{qrcode}"
# Get items and construct cmd string # Get items and construct cmd string
for item in items: for item in items:
@@ -565,7 +566,7 @@ class LuiPagesGen(object):
def render_card(self, card, send_page_type=True): def render_card(self, card, send_page_type=True):
self._ha_api.log(f"Started rendering of page {card.pos} with type {card.cardType}") apis.ha_api.log(f"Started rendering of page {card.pos} with type {card.cardType}")
if len(self._config._config_cards) == 1: if len(self._config._config_cards) == 1:
navigation = "0|0" navigation = "0|0"
@@ -601,7 +602,7 @@ class LuiPagesGen(object):
def generate_light_detail_page(self, entity_id): def generate_light_detail_page(self, entity_id):
entity = self._ha_api.get_entity(entity_id) entity = apis.ha_api.get_entity(entity_id)
switch_val = 1 if entity.state == "on" else 0 switch_val = 1 if entity.state == "on" else 0
icon_color = self.get_entity_color(entity) icon_color = self.get_entity_color(entity)
brightness = "disable" brightness = "disable"
@@ -635,7 +636,7 @@ class LuiPagesGen(object):
self._send_mqtt_msg(f"entityUpdateDetail~{entity_id}~{get_icon_id('lightbulb')}~{icon_color}~{switch_val}~{brightness}~{color_temp}~{color}~{color_translation}~{color_temp_translation}~{brightness_translation}") self._send_mqtt_msg(f"entityUpdateDetail~{entity_id}~{get_icon_id('lightbulb')}~{icon_color}~{switch_val}~{brightness}~{color_temp}~{color}~{color_translation}~{color_temp_translation}~{brightness_translation}")
def generate_shutter_detail_page(self, entity_id): def generate_shutter_detail_page(self, entity_id):
entity = self._ha_api.get_entity(entity_id) entity = apis.ha_api.get_entity(entity_id)
entityType="cover" entityType="cover"
device_class = entity.attributes.get("device_class", "window") device_class = entity.attributes.get("device_class", "window")
icon_id = get_icon_id_ha(entityType, state=entity.state, device_class=device_class) icon_id = get_icon_id_ha(entityType, state=entity.state, device_class=device_class)
@@ -703,7 +704,7 @@ class LuiPagesGen(object):
self._send_mqtt_msg(f"entityUpdateDetail~{entity_id}~{pos}~{pos_translation}: {pos_status}~{pos_translation}~{icon_id}~{icon_up}~{icon_stop}~{icon_down}~{icon_up_status}~{icon_stop_status}~{icon_down_status}~{textTilt}~{iconTiltLeft}~{iconTiltStop}~{iconTiltRight}~{iconTiltLeftStatus}~{iconTiltStopStatus}~{iconTiltRightStatus}~{tilt_pos}") self._send_mqtt_msg(f"entityUpdateDetail~{entity_id}~{pos}~{pos_translation}: {pos_status}~{pos_translation}~{icon_id}~{icon_up}~{icon_stop}~{icon_down}~{icon_up_status}~{icon_stop_status}~{icon_down_status}~{textTilt}~{iconTiltLeft}~{iconTiltStop}~{iconTiltRight}~{iconTiltLeftStatus}~{iconTiltStopStatus}~{iconTiltRightStatus}~{tilt_pos}")
def generate_fan_detail_page(self, entity_id): def generate_fan_detail_page(self, entity_id):
entity = self._ha_api.get_entity(entity_id) entity = apis.ha_api.get_entity(entity_id)
switch_val = 1 if entity.state == "on" else 0 switch_val = 1 if entity.state == "on" else 0
icon_color = self.get_entity_color(entity) icon_color = self.get_entity_color(entity)
speed = entity.attributes.get("percentage") speed = entity.attributes.get("percentage")

View File

@@ -18,7 +18,7 @@ class NsPanelLovelaceUIManager(hass.Hass):
# Request Tasmota Driver Version # Request Tasmota Driver Version
mqtt_api.mqtt_publish(topic_send.replace("CustomSend", "GetDriverVersion"), "x") mqtt_api.mqtt_publish(topic_send.replace("CustomSend", "GetDriverVersion"), "x")
controller = LuiController(self, cfg, mqttsend.send_mqtt_msg) controller = LuiController(cfg, mqttsend.send_mqtt_msg)
desired_display_firmware_version = 41 desired_display_firmware_version = 41
version = "v3.3.1" version = "v3.3.1"