blueprint:
  name: "HASPone p[x].b[y] displays the current temperature from a weather provider, coloured icon only"
  description: |

    ## Blueprint Version: `1.06.00`

    # Description

    A HASPone button displays the current temperature from a weather provider as an icon that is optionally coloured.

    ![Preview](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/hasp_Display_Weather_Temperature_Color_Icon_Only.png)

    ## HASPone Page and Button reference

    <details>

    | Page 0 | Pages 1-3 | Pages 4-5 |
    |--------|-----------|-----------|
    | ![Page 0](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/NextionUI_p0_Init_Screen.png) | ![Pages 1-3](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/NextionUI_p1-p3_4buttons.png) | ![Pages 4-5](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/NextionUI_p4-p5_3sliders.png) |

    | Page 6 | Page 7 | Page 8 |
    |--------|--------|--------|
    | ![Page 6](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/NextionUI_p6_8buttons.png) | ![Page 7](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/NextionUI_p7_12buttons.png) | ![Page 8](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/NextionUI_p8_5buttons+1slider.png) |

    | Page 9 | Page 10 | Page 11 |
    |--------|---------|---------|
    | ![Page 9](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/NextionUI_p9_9buttons.png) | ![Page 10](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/NextionUI_p10_5buttons.png) | ![Page 11](https://raw.githubusercontent.com/HASwitchPlate/HASPone/main/images/NextionUI_p11_1button+1slider.png)

    </details>

    ## Nextion color codes

    <details>

    The Nextion environment utilizes RGB 565 encoding.  [Use this handy convertor](https://nodtem66.github.io/nextion-hmi-color-convert/index.html) to select your colors and convert to the RGB 565 format.

    Here are some example colors:

    | Color  | Code  |
    |--------|-------|
    | White  | 65535 |
    | Black  | 0     |
    | Grey   | 25388 |
    | Red    | 63488 |
    | Green  | 2016  |
    | Blue   | 31    |
    | Yellow | 65504 |
    | Orange | 64512 |
    | Brown  | 48192 |

    </details>
  domain: automation
  input:
    haspdevice:
      name: "HASPone Device"
      description: "Select the HASPone device"
      selector:
        device:
          integration: mqtt
          manufacturer: "HASwitchPlate"
          model: "HASPone v1.0.0"
    hasppage:
      name: "HASPone Page"
      description: "Select the HASPone page (1-11) for the temperature icon. Refer to the HASPone Page and Button reference above."
      default: 1
      selector:
        number:
          min: 1
          max: 11
          mode: slider
          unit_of_measurement: page
    haspbutton:
      name: "HASPone Button"
      description: "Select the HASPone button (4-15) for the temperature icon. Refer to the HASPone Page and Button reference above."
      default: 4
      selector:
        number:
          min: 4
          max: 15
          mode: slider
          unit_of_measurement: button
    weather_provider:
      name: "Weather provider"
      description: "Select the weather provider to obtain the current outdoor temperature."
      default:
      selector:
        entity:
          domain: weather
    thermometer_empty_color:
      name: "Thermometer empty color"
      description: 'Icon color for an empty thermometer in Nextion RGB565 format (see "Nextion color codes" above for reference). -1 = Current theme foreground color, or 2047 = Ice blue'
      default: 2047
      selector:
        number:
          min: -1
          max: 65535
          mode: slider
    thermometer_quarter_threshold:
      name: "Thermometer one quarter threshold"
      description: "Temperatures above this threshold will show a one-quarter full thermometer.  Below, show an empty thermometer."
      default: 0
      selector:
        number:
          min: -20
          max: 125
          mode: slider
    thermometer_quarter_color:
      name: "Thermometer one quarter color"
      description: "Icon color for a one-quarter full thermometer in Nextion RGB565 format. -1 = Current theme foreground color, or 31 = Blue"
      default: 31
      selector:
        number:
          min: -1
          max: 65535
          mode: slider
    thermometer_half_threshold:
      name: "Thermometer half threshold"
      description: "Temperatures above this threshold will show a half full thermometer.  This value must be higher than the value selected above."
      default: 32
      selector:
        number:
          min: -10
          max: 125
          mode: slider
    thermometer_half_color:
      name: "Thermometer half color"
      description: "Icon color for a half full thermometer in Nextion RGB565 format. -1 = Current theme foreground color, or 1536 = Green"
      default: 1536
      selector:
        number:
          min: -1
          max: 65535
          mode: slider
    thermometer_three_quarter_threshold:
      name: "Thermometer three quarter threshold"
      description: "Temperatures above this threshold will show a three-quarters full thermometer.  This value must be higher than the value selected above."
      default: 80
      selector:
        number:
          min: 0
          max: 125
          mode: slider
    thermometer_three_quarter_color:
      name: "Thermometer three quarter color"
      description: "Icon color for a three-quarter full thermometer in Nextion RGB565 format. -1 = Current theme foreground color, or 64512 = Orange"
      default: 64512
      selector:
        number:
          min: -1
          max: 65535
          mode: slider
    thermometer_full_threshold:
      name: "Thermometer full threshold"
      description: "Temperatures above this threshold will show a full thermometer.  This value must be higher than the value selected above."
      default: 95
      selector:
        number:
          min: 10
          max: 125
          mode: slider
    thermometer_full_color:
      name: "Thermometer full color"
      description: "Icon color for a full thermometer in Nextion RGB565 format. -1 = Current theme foreground color, or 63488 = Red"
      default: 63488
      selector:
        number:
          min: -1
          max: 65535
          mode: slider

mode: parallel
max_exceeded: silent

variables:
  haspname: >-
    {%- for entity in device_entities(haspdevice) -%}
      {%- if entity|regex_search("^sensor\..+_sensor(?:_\d+|)$") -%}
        {{- entity|regex_replace(find="^sensor\.", replace="", ignorecase=true)|regex_replace(find="_sensor(?:_\d+|)$", replace="", ignorecase=true) -}}
      {%- endif -%}
    {%- endfor -%}
  haspsensor: >-
    {%- for entity in device_entities(haspdevice) -%}
      {%- if entity|regex_search("^sensor\..+_sensor(?:_\d+|)$") -%}
        {{ entity }}
      {%- endif -%}
    {%- endfor -%}
  hasppage: !input hasppage
  haspbutton: !input haspbutton
  weather_provider: !input weather_provider
  thermometer_empty_color: !input thermometer_empty_color
  thermometer_quarter_threshold: !input thermometer_quarter_threshold
  thermometer_quarter_color: !input thermometer_quarter_color
  thermometer_half_threshold: !input thermometer_half_threshold
  thermometer_half_color: !input thermometer_half_color
  thermometer_three_quarter_threshold: !input thermometer_three_quarter_threshold
  thermometer_three_quarter_color: !input thermometer_three_quarter_color
  thermometer_full_threshold: !input thermometer_full_threshold
  thermometer_full_color: !input thermometer_full_color
  haspobject: '{{ "p[" ~ hasppage ~ "].b[" ~ haspbutton ~ "]" }}'
  commandtopic: '{{ "hasp/" ~ haspname ~ "/command/" ~ haspobject }}'
  jsoncommandtopic: '{{ "hasp/" ~ haspname ~ "/command/json" }}'
  temperature: '{{ state_attr(weather_provider, "temperature") }}'
  icon: >-
    {%- set temp = temperature|int(default=0) -%}
    {%- if temp <= thermometer_quarter_threshold|int -%}
      
    {%- elif temp < thermometer_half_threshold|int -%}
      
    {% elif temp < thermometer_three_quarter_threshold|int -%}
      
    {%- elif temp < thermometer_full_threshold|int -%}
      
    {%- else -%}
      
    {%- endif -%}
  font: 8
  xcen: 1
  ycen: 1
  selectedfgtopic: '{{ "hasp/" ~ haspname ~ "/light/selectedforegroundcolor/rgb" }}'
  selectedbgtopic: '{{ "hasp/" ~ haspname ~ "/light/selectedbackgroundcolor/rgb" }}'
  unselectedfgtopic: '{{ "hasp/" ~ haspname ~ "/light/unselectedforegroundcolor/rgb" }}'
  unselectedbgtopic: '{{ "hasp/" ~ haspname ~ "/light/unselectedbackgroundcolor/rgb" }}'
  selectedfg: >-
    {%- set color = namespace() -%}
    {%- for entity in device_entities(haspdevice) -%}
      {%- if entity|regex_search("^light\..*_selected_foreground_color(?:_\d+|)$") -%}
        {%- set color.source=entity -%}
      {%- endif -%}
    {%- endfor -%}
    {%- set brightness = state_attr(color.source, "brightness")|int(default=255) / 255 -%}
    {%- set red=(state_attr(color.source, "rgb_color")[0] * brightness)|int(default=0) -%}
    {%- set green=(state_attr(color.source, "rgb_color")[1] * brightness)|int(default=0) -%}
    {%- set blue=(state_attr(color.source, "rgb_color")[2] * brightness)|int(default=0) -%}
    {{ (red|bitwise_and(248)*256) + (green|bitwise_and(252)*8) + (blue|bitwise_and(248)/8)|int }}
  selectedbg: >-
    {%- set color = namespace() -%}
    {%- for entity in device_entities(haspdevice) -%}
      {%- if entity|regex_search("^light\..*_selected_background_color(?:_\d+|)$") -%}
        {%- set color.source=entity -%}
      {%- endif -%}
    {%- endfor -%}
    {%- set brightness = state_attr(color.source, "brightness")|int(default=255) / 255 -%}
    {%- set red=(state_attr(color.source, "rgb_color")[0] * brightness)|int(default=0) -%}
    {%- set green=(state_attr(color.source, "rgb_color")[1] * brightness)|int(default=0) -%}
    {%- set blue=(state_attr(color.source, "rgb_color")[2] * brightness)|int(default=0) -%}
    {{ (red|bitwise_and(248)*256) + (green|bitwise_and(252)*8) + (blue|bitwise_and(248)/8)|int }}
  unselectedfg: >-
    {%- set color = namespace() -%}
    {%- for entity in device_entities(haspdevice) -%}
      {%- if entity|regex_search("^light\..*_unselected_foreground_color(?:_\d+|)$") -%}
        {%- set color.source=entity -%}
      {%- endif -%}
    {%- endfor -%}
    {%- set brightness = state_attr(color.source, "brightness")|int(default=255) / 255 -%}
    {%- set red=(state_attr(color.source, "rgb_color")[0] * brightness)|int(default=0) -%}
    {%- set green=(state_attr(color.source, "rgb_color")[1] * brightness)|int(default=0) -%}
    {%- set blue=(state_attr(color.source, "rgb_color")[2] * brightness)|int(default=0) -%}
    {{ (red|bitwise_and(248)*256) + (green|bitwise_and(252)*8) + (blue|bitwise_and(248)/8)|int }}
  unselectedbg: >-
    {%- set color = namespace() -%}
    {%- for entity in device_entities(haspdevice) -%}
      {%- if entity|regex_search("^light\..*_unselected_background_color(?:_\d+|)$") -%}
        {%- set color.source=entity -%}
      {%- endif -%}
    {%- endfor -%}
    {%- set brightness = state_attr(color.source, "brightness")|int(default=255) / 255 -%}
    {%- set red=(state_attr(color.source, "rgb_color")[0] * brightness)|int(default=0) -%}
    {%- set green=(state_attr(color.source, "rgb_color")[1] * brightness)|int(default=0) -%}
    {%- set blue=(state_attr(color.source, "rgb_color")[2] * brightness)|int(default=0) -%}
    {{ (red|bitwise_and(248)*256) + (green|bitwise_and(252)*8) + (blue|bitwise_and(248)/8)|int }}
  tempcolor: >-
    {%- set temp = temperature|int -%}
    {%- if temp <= thermometer_quarter_threshold|int -%}
      {%- set color = thermometer_empty_color -%}
    {%- elif temp < thermometer_half_threshold|int -%}
      {%- set color = thermometer_quarter_color -%}
    {%- elif temp < thermometer_three_quarter_threshold|int -%}
      {%- set color = thermometer_half_color -%}
    {%- elif temp < thermometer_full_threshold|int -%}
      {%- set color = thermometer_three_quarter_color -%}
    {%- else -%}
      {%- set color = thermometer_full_color -%}
    {%- endif -%}
    {%- if color|int < 0 -%}
      {{- selectedfg -}}
    {%- else -%}
      {{- color -}}
    {%- endif -%}

trigger_variables:
  haspdevice: !input haspdevice
  haspname: >-
    {%- for entity in device_entities(haspdevice) -%}
      {%- if entity|regex_search("^sensor\..+_sensor(?:_\d+|)$") -%}
        {{- entity|regex_replace(find="^sensor\.", replace="", ignorecase=true)|regex_replace(find="_sensor(?:_\d+|)$", replace="", ignorecase=true) -}}
      {%- endif -%}
    {%- endfor -%}
  haspsensor: >-
    {%- for entity in device_entities(haspdevice) -%}
      {%- if entity|regex_search("^sensor\..+_sensor(?:_\d+|)$") -%}
        {{ entity }}
      {%- endif -%}
    {%- endfor -%}
  selectedfgtopic: '{{ "hasp/" ~ haspname ~ "/light/selectedforegroundcolor/rgb" }}'
  selectedbgtopic: '{{ "hasp/" ~ haspname ~ "/light/selectedbackgroundcolor/rgb" }}'
  unselectedfgtopic: '{{ "hasp/" ~ haspname ~ "/light/unselectedforegroundcolor/rgb" }}'
  unselectedbgtopic: '{{ "hasp/" ~ haspname ~ "/light/unselectedbackgroundcolor/rgb" }}'

trigger:
  - platform: state
    entity_id: !input weather_provider
  - platform: template
    value_template: "{{ is_state(haspsensor, 'ON') }}"
  - platform: homeassistant
    event: start
  - platform: mqtt
    topic: "{{selectedfgtopic}}"
  - platform: mqtt
    topic: "{{selectedbgtopic}}"
  - platform: mqtt
    topic: "{{unselectedfgtopic}}"
  - platform: mqtt
    topic: "{{unselectedbgtopic}}"

condition:
  - condition: template
    value_template: "{{ is_state(haspsensor, 'ON') }}"

action:
  - choose:
      #########################################################################
      # RUN ACTIONS or Home Assistant Startup or HASPone Connect
      # Apply styles, place text, and then place icon if our target page is currently active
      - conditions:
          - condition: template
            value_template: >-
              {{-
                (trigger is not defined)
              or
                (trigger.platform is none)
              or
                ((trigger.platform == 'homeassistant') and (trigger.event == 'start'))
              or
                ((trigger.platform == 'template') and (trigger.entity_id == haspsensor) and (trigger.to_state.state == 'ON'))
              -}}
        sequence:
          - service: mqtt.publish
            data:
              topic: "{{jsoncommandtopic}}"
              payload: >-
                ["{{haspobject}}.font={{font}}",
                "{{haspobject}}.xcen={{xcen}}",
                "{{haspobject}}.ycen={{ycen}}",
                "{{haspobject}}.pco={{tempcolor}}",
                "{{haspobject}}.bco={{selectedbg}}",
                "{{haspobject}}.pco2={{unselectedfg}}",
                "{{haspobject}}.bco2={{unselectedbg}}",
                "{{haspobject}}.txt=\"{{icon}}\""]
      #########################################################################
      # Update temperature if our weather provider changed state
      - conditions:
          - condition: template
            value_template: '{{ (trigger.platform == "state") and (trigger.entity_id == weather_provider) }}'
        sequence:
          - service: mqtt.publish
            data:
              topic: "{{jsoncommandtopic}}"
              payload: >-
                ["{{haspobject}}.pco={{tempcolor}}",
                "{{haspobject}}.txt=\"{{icon}}\""]
      #########################################################################
      # Catch triggers fired by incoming MQTT messages
      - conditions:
          - condition: template
            value_template: '{{ trigger.platform == "mqtt" }}'
        sequence:
          - choose:
              #########################################################################
              # Theme: Apply selected foreground color when it changes.
              # Any change to the button will remove the overlaid icon.
              - conditions:
                  - condition: template
                    value_template: "{{ trigger.topic == selectedfgtopic }}"
                sequence:
                  - service: mqtt.publish
                    data:
                      topic: "{{commandtopic}}.pco"
                      payload: "{{trigger.payload}}"
              #########################################################################
              # Theme: Apply selected background color on change
              - conditions:
                  - condition: template
                    value_template: "{{ trigger.topic == selectedbgtopic }}"
                sequence:
                  - service: mqtt.publish
                    data:
                      topic: "{{commandtopic}}.bco"
                      payload: "{{trigger.payload}}"
              #########################################################################
              # Theme: Apply unselected foreground color on change
              - conditions:
                  - condition: template
                    value_template: "{{ trigger.topic == unselectedfgtopic }}"
                sequence:
                  - service: mqtt.publish
                    data:
                      topic: "{{commandtopic}}.pco2"
                      payload: "{{trigger.payload}}"
              #########################################################################
              # Theme: Apply unselected background color on change
              - conditions:
                  - condition: template
                    value_template: "{{ trigger.topic == unselectedbgtopic }}"
                sequence:
                  - service: mqtt.publish
                    data:
                      topic: "{{commandtopic}}.bco2"
                      payload: "{{trigger.payload}}"
