46 changed files with 604 additions and 6308 deletions
+1 -1
View File
@@ -1 +1 @@
2026.11.1
2026.7.1
+189 -322
View File
@@ -28,18 +28,18 @@
alias: TV Anti-Reflexion
description: Schaltet Wohnzimmer hinten Ambient Light aus, um Reflexionen im TV
zu verhindern.
triggers:
- entity_id: media_player.lg_webos_smart_tv
trigger:
- platform: state
entity_id: media_player.lg_webos_smart_tv
from: 'off'
to: 'on'
trigger: state
conditions: []
actions:
- target:
device_id: 5a0caeab0be8e10747c74dcf5dd9ced1
condition: []
action:
- service: light.turn_off
target:
device_id: 6dcbd87b459412144bddc42af3ae8b83
data:
transition: 2
action: light.turn_off
mode: single
- id: '1623526683767'
alias: Licht bei Sonnenaufgang ausschalten
@@ -56,23 +56,22 @@
area_id:
- schlafzimmer
device_id:
- f39e4bf25a3bee97f237b0d7ddd64493
- ca8b65e4a22153f953a88d7bb1efb36b
- 2b27a605524f6617ed1f71f98e0eb74d
- 2a5b866b0062c298950cb0bd03ec14eb
- 5a0caeab0be8e10747c74dcf5dd9ced1
- 23aeb31cedaf3ff0bf14d4a05fc779da
- fb581090b15a027cf071b99d0ea00874
- a7c56c0e328765addc33be2f375778bc
- 53a27edf581fcf40f3bc8b253b1ee369
- 4e8211f6c1ad515c79d7a26f3d7c9a27
- c64e7c3dcda7f1c23e456959f2c60f39
- 4edd9b9df7d1f6f2fe7dcc2e5c0eb968
- 6dcbd87b459412144bddc42af3ae8b83
- 98a9eef603f8c8ae6200c4834a3dbf4f
- 32d15eec63fe68d5770813d47da53657
- 9f42805af5b7e423023595390342b9ac
entity_id: light.kajplats_e14_cws_globe_806lm
data:
transition: 2
action: light.turn_off
mode: single
- id: '1623673821789'
alias: Schlafen gehen
description: Schalte alles (außer Schlafzimmer) aus und schließ die Wohnungstür,
sobald das Schlaftracking startet.
alias: Gute Nacht!
description: Schalte alles (außer Schlafzimmer) aus, sobald das Schlaftracking startet.
triggers:
- trigger: state
entity_id:
@@ -85,44 +84,17 @@
area_id:
- wohnzimmer
- kuche
- schlafzimmer
- kinderzimmer
entity_id:
- light.awtrix_528bd4_matrix
- light.awtrix_b8658c_matrix
- light.schlafzimmer_bett
- light.schlafzimmer_deckenlicht
data: {}
action: light.turn_off
- type: turn_off
device_id: 40ea5b499584568460396dc9b920beca
device_id: 6d1be741876624a70ab5b01b54c6fd6f
entity_id: switch.kuche_musik
domain: switch
- action: light.turn_on
metadata: {}
target:
entity_id: light.schlafzimmeruhr_display
data:
rgb_color:
- 224
- 27
- 36
brightness_pct: 5
- action: button.press
metadata: {}
target:
entity_id: button.schlafzimmeruhr_clear_digit_colors
data: {}
- action: select.select_option
metadata: {}
target:
entity_id: select.schlafzimmeruhr_effect
data:
option: None
- action: lock.lock
metadata: {}
target:
entity_id: lock.flur_wohnungstur
data: {}
- data:
message: Gute Nacht!
action: notify.mobile_app_le2123
@@ -167,6 +139,10 @@
trigger: time
conditions: []
actions:
- action: notify.mobile_app_apollo
data:
message: Lodere es, Lustknabe.
title: 420!
- data:
title: 420!
message: Lodere es, Lustknabe.
@@ -207,32 +183,28 @@
topic: awtrix_desk/notify
payload: '{"text": "420, lodere es, Lustknabe!"}'
action: mqtt.publish
- action: notify.mobile_app_apollo
data:
message: Lodere es, Lustknabe.
title: 420!
mode: single
- id: '1623911524804'
alias: TV Anti-Reflexion (undo)
description: Schaltet Wohnzimmer hinten Ambient Light wieder ein, wenn vorne auch
(noch) eingeschaltet ist.
triggers:
- entity_id: media_player.lg_webos_smart_tv
trigger:
- platform: state
entity_id: media_player.lg_webos_smart_tv
to: 'off'
from: 'on'
trigger: state
conditions:
condition:
- condition: device
type: is_on
device_id: 2a5b866b0062c298950cb0bd03ec14eb
device_id: 4edd9b9df7d1f6f2fe7dcc2e5c0eb968
entity_id: light.wohnzimmer_vorne
domain: light
actions:
- data:
action:
- service: light.turn_on
data:
transition: 2
target:
device_id: 5a0caeab0be8e10747c74dcf5dd9ced1
action: light.turn_on
device_id: 6dcbd87b459412144bddc42af3ae8b83
mode: single
- id: '1623941937228'
alias: Licht im Schlafzimmer zur Schlafenszeit einschalten
@@ -250,51 +222,36 @@
state: home
actions:
- target:
device_id: ddf95b1e837e69c677460491a2600cd4
device_id: 68868390eda35e969ec60a13020f2407
data: {}
action: light.turn_on
- action: select.select_option
metadata: {}
target:
entity_id: select.schlafzimmeruhr_effect
data:
option: None
- action: esphome.sleepingroom_clock_set_gradient
data:
red1: 255
green1: 40
blue1: 0
red2: 60
green2: 0
blue2: 120
angle: 0
- data:
cache: true
media_player_entity_id: media_player.home_assistant_voice_0a7c6b_media_player
media_player_entity_id: media_player.home_assistant_voice_0a7c6b
message: Ab ins Bett, Schlafenszeit.
target:
entity_id: tts.piper
enabled: true
action: tts.speak
enabled: true
- data:
cache: true
media_player_entity_id: media_player.home_assistant_voice_09c0e7_media_player
media_player_entity_id: media_player.home_assistant_voice_09c0e7_media_player_2
message: Ab ins Bett, Schlafenszeit.
target:
entity_id: tts.piper
enabled: true
action: tts.speak
enabled: true
- data:
cache: true
media_player_entity_id: media_player.m5stack_atom_echo
message: Ab ins Bett, Schlafenszeit.
target:
entity_id: tts.piper
enabled: true
action: tts.speak
enabled: true
mode: single
- id: '1623954512941'
alias: Aufwachen
alias: Licht im Schlafzimmer zum Aufwachen einschalten
description: Nach der Alarmquittierung
triggers:
- trigger: state
@@ -313,42 +270,16 @@
seconds: 0
milliseconds: 0
- target:
device_id: ddf95b1e837e69c677460491a2600cd4
device_id: 68868390eda35e969ec60a13020f2407
data: {}
action: light.turn_on
- action: lock.unlock
metadata: {}
target:
entity_id: lock.flur_wohnungstur
data: {}
- action: light.turn_on
metadata: {}
target:
entity_id: light.schlafzimmeruhr_display
data:
brightness_pct: 50
enabled: true
- action: select.select_option
metadata: {}
target:
entity_id: select.schlafzimmeruhr_effect
data:
option: Color Cycle
- action: select.select_option
metadata: {}
target:
entity_id: select.schlafzimmeruhr_effect_spread
data:
option: Per LED
mode: single
- id: '1624820688449'
alias: 'Anruf: Beim Klingeln grün blinken'
description: ''
triggers:
- entity_id:
- sensor.fritz_box_7690_anrufmonitor_dem_commander1024_seine_cloud
to:
- ringing
- entity_id: sensor.fritz_box_7490_call_monitor_dem_commander1024_seine_cloud
to: ringing
trigger: state
- entity_id:
- sensor.le2123_phone_state_2
@@ -370,8 +301,8 @@
- 0
target:
entity_id:
- light.awtrix_b8658c_indicator_1
- light.awtrix_528bd4_indicator_1
- light.awtrix_desk_indicator_1
- light.awtrix_kitchen_indicator_1
action: light.turn_on
- data:
scene_id: wled_last_state
@@ -404,18 +335,16 @@
- data: {}
target:
entity_id:
- light.awtrix_b8658c_indicator_1
- light.awtrix_528bd4_indicator_1
- light.awtrix_desk_indicator_1
- light.awtrix_kitchen_indicator_1
action: light.turn_off
mode: single
- id: '1625481640348'
alias: 'Anruf: Beim Telefonieren Musik pausieren'
description: ''
triggers:
- entity_id:
- sensor.fritz_box_7690_anrufmonitor_dem_commander1024_seine_cloud
to:
- talking
- entity_id: sensor.fritz_box_7490_call_monitor_telefonbuch
to: talking
trigger: state
- entity_id:
- sensor.le2123_phone_state_2
@@ -433,8 +362,9 @@
- data:
scene_id: media_last_state
snapshot_entities:
- media_player.wohnzimmer
- media_player.wohnzimmer_main
- media_player.lg_webos_smart_tv
- media_player.ccze
- media_player.spotify_marcus_scholz
- media_player.xboxonex
action: scene.create
@@ -455,16 +385,17 @@
trigger: state
- target:
entity_id:
- scene.wled_last_state
- scene.media_last_state
action: scene.turn_on
data: {}
mode: single
- id: '1628972104416'
alias: Raumduft nach einer Stunde wieder ausschalten
description: ''
triggers:
- type: turned_on
device_id: b29693c2517f4d6538da9fe7e5e5a262
trigger:
- platform: device
type: turned_on
device_id: 5a08ac4c3b3893b540a9934fa92dccfa
entity_id: switch.flur_raumduft
domain: switch
for:
@@ -472,11 +403,10 @@
minutes: 0
seconds: 0
milliseconds: 0
trigger: device
conditions: []
actions:
condition: []
action:
- type: turn_off
device_id: b29693c2517f4d6538da9fe7e5e5a262
device_id: 5a08ac4c3b3893b540a9934fa92dccfa
entity_id: switch.flur_raumduft
domain: switch
mode: single
@@ -495,7 +425,7 @@
state: home
actions:
- type: turn_on
device_id: b29693c2517f4d6538da9fe7e5e5a262
device_id: 5a08ac4c3b3893b540a9934fa92dccfa
entity_id: switch.flur_raumduft
domain: switch
- data: {}
@@ -506,7 +436,7 @@
action: light.turn_on
mode: single
- id: '1630914505161'
alias: Wohnung verlassen
alias: Beim Verlassen der Wohnung alles abschalten
description: ''
triggers:
- entity_id: person.marcus_scholz
@@ -528,25 +458,20 @@
data: {}
action: light.turn_off
- type: turn_off
device_id: 40ea5b499584568460396dc9b920beca
device_id: 6d1be741876624a70ab5b01b54c6fd6f
entity_id: switch.kuche_musik
domain: switch
- type: turn_off
device_id: b29693c2517f4d6538da9fe7e5e5a262
device_id: 5a08ac4c3b3893b540a9934fa92dccfa
entity_id: switch.flur_raumduft
domain: switch
- action: light.turn_off
metadata: {}
data: {}
target:
entity_id:
- light.awtrix_b8658c_matrix
- light.awtrix_528bd4_matrix
- action: lock.lock
metadata: {}
target:
entity_id: lock.flur_wohnungstur
data: {}
device_id:
- 231cd7ec37e32690faf126105b03ee02
- a6d24e7d93c114723bf525e9eac1c2df
- type: turn_off
device_id: c4ead7f6227e2ee4c43c4b0df829cd84
entity_id: 7f7284b11f2bf50ae2f0ebeeb35411c0
@@ -577,8 +502,8 @@
action: script.moodlight_orange_plasma
- target:
device_id:
- 53a27edf581fcf40f3bc8b253b1ee369
- 5abbb43e5d015ee75c7c900240b4329e
- f39e4bf25a3bee97f237b0d7ddd64493
data:
brightness_pct: 70
color_temp_kelvin: 2000
@@ -690,33 +615,12 @@
action: notify.mobile_app_le2123
- data:
cache: true
media_player_entity_id: media_player.home_assistant_voice_0a7c6b_media_player
media_player_entity_id: media_player.raspiaudio_muse_luxe
message: '{{message}}
'
target:
entity_id: tts.piper
enabled: true
action: tts.speak
- data:
cache: true
media_player_entity_id: media_player.home_assistant_voice_09c0e7_media_player
message: '{{message}}
'
target:
entity_id: tts.piper
enabled: true
action: tts.speak
- data:
cache: true
media_player_entity_id: media_player.m5stack_atom_echo
message: '{{message}}
'
target:
entity_id: tts.piper
enabled: true
action: tts.speak
variables:
message: 'Die Außentemperatur ist mit {{states(''sensor.aussentemperatur'')}}
@@ -761,33 +665,12 @@
action: notify.mobile_app_le2123
- data:
cache: true
media_player_entity_id: media_player.home_assistant_voice_0a7c6b_media_player
media_player_entity_id: media_player.raspiaudio_muse_luxe
message: '{{message}}
'
target:
entity_id: tts.piper
enabled: true
action: tts.speak
- data:
cache: true
media_player_entity_id: media_player.home_assistant_voice_09c0e7_media_player
message: '{{message}}
'
target:
entity_id: tts.piper
enabled: true
action: tts.speak
- data:
cache: true
media_player_entity_id: media_player.m5stack_atom_echo
message: '{{message}}
'
target:
entity_id: tts.piper
enabled: true
action: tts.speak
mode: single
variables:
@@ -941,7 +824,6 @@
entity_id:
- light.awtrix_b8658c_matrix
- light.awtrix_528bd4_matrix
- light.schlafzimmeruhr_display
action: light.turn_on
mode: single
- id: '1700482951854'
@@ -962,8 +844,8 @@
action: script.moodlight_xmas
- target:
device_id:
- 53a27edf581fcf40f3bc8b253b1ee369
- 5abbb43e5d015ee75c7c900240b4329e
- f39e4bf25a3bee97f237b0d7ddd64493
data:
brightness_pct: 70
color_temp_kelvin: 2000
@@ -990,15 +872,15 @@
area_id:
- schlafzimmer
device_id:
- 53a27edf581fcf40f3bc8b253b1ee369
- 4e8211f6c1ad515c79d7a26f3d7c9a27
- c64e7c3dcda7f1c23e456959f2c60f39
- 4edd9b9df7d1f6f2fe7dcc2e5c0eb968
- 6dcbd87b459412144bddc42af3ae8b83
- 98a9eef603f8c8ae6200c4834a3dbf4f
- 32d15eec63fe68d5770813d47da53657
- 9f42805af5b7e423023595390342b9ac
- 5abbb43e5d015ee75c7c900240b4329e
- f39e4bf25a3bee97f237b0d7ddd64493
- ca8b65e4a22153f953a88d7bb1efb36b
- 2b27a605524f6617ed1f71f98e0eb74d
- 2a5b866b0062c298950cb0bd03ec14eb
- 5a0caeab0be8e10747c74dcf5dd9ced1
- 23aeb31cedaf3ff0bf14d4a05fc779da
- fb581090b15a027cf071b99d0ea00874
- a7c56c0e328765addc33be2f375778bc
data:
transition: 2
action: light.turn_off
@@ -1022,15 +904,15 @@
- data: {}
target:
device_id:
- 2a5b866b0062c298950cb0bd03ec14eb
- 5a0caeab0be8e10747c74dcf5dd9ced1
- 4edd9b9df7d1f6f2fe7dcc2e5c0eb968
- 6dcbd87b459412144bddc42af3ae8b83
action: light.turn_on
action_button_down_short:
- data: {}
target:
device_id:
- 5a0caeab0be8e10747c74dcf5dd9ced1
- 2a5b866b0062c298950cb0bd03ec14eb
- 6dcbd87b459412144bddc42af3ae8b83
- 4edd9b9df7d1f6f2fe7dcc2e5c0eb968
action: light.turn_off
action_button_left_short:
- data: {}
@@ -1046,14 +928,14 @@
data: {}
action_button_down_double:
- target:
device_id: a7c56c0e328765addc33be2f375778bc
device_id: 9f42805af5b7e423023595390342b9ac
data: {}
action: light.turn_off
action_button_up_double:
- metadata: {}
data: {}
target:
device_id: a7c56c0e328765addc33be2f375778bc
device_id: 9f42805af5b7e423023595390342b9ac
action: light.turn_on
button_up_double_press: true
button_down_double_press: true
@@ -1078,38 +960,39 @@
remote: bd97db2ae9b0104d50dc6a343315608b
double_dot_single_press:
- target:
device_id: ddf95b1e837e69c677460491a2600cd4
device_id:
- 68868390eda35e969ec60a13020f2407
data: {}
action: light.turn_off
double_dot_double_press:
- metadata: {}
data: {}
target:
device_id: 824bb838dd09391e75dd7c366a571c4c
device_id: 3c86ddd39979139f29645308815c0271
action: light.turn_off
single_dot_single_press:
- metadata: {}
data: {}
target:
device_id: ddf95b1e837e69c677460491a2600cd4
device_id: 68868390eda35e969ec60a13020f2407
action: light.turn_on
single_dot_double_press:
- metadata: {}
data: {}
target:
device_id: 824bb838dd09391e75dd7c366a571c4c
device_id: 3c86ddd39979139f29645308815c0271
action: light.turn_on
double_dot_long_press:
- metadata: {}
data: {}
target:
device_id: 64daf8ee59e890acd2930fa91bcdeb9c
device_id: b7c1c80b21406c5608e38aa0c7e7e439
action: switch.turn_off
single_dot_long_press:
- metadata: {}
data: {}
target:
device_id: 64daf8ee59e890acd2930fa91bcdeb9c
device_id: b7c1c80b21406c5608e38aa0c7e7e439
action: switch.turn_on
- id: '1705488817426'
alias: Let's Encrypt
@@ -1127,17 +1010,17 @@
- id: '1705787842132'
alias: 'Luftbefeuchter: Zielwert'
description: Leicht oberhalb des Wohnungsdurchschnitts
triggers:
- minutes: /10
trigger: time_pattern
conditions: []
actions:
- metadata: {}
trigger:
- platform: time_pattern
minutes: /10
condition: []
action:
- service: humidifier.set_humidity
metadata: {}
data:
humidity: '{{ int(states(''sensor.wohnungsluftfeuchtigkeit'')) + 20 }}'
target:
entity_id: humidifier.badezimmer_badezimmer_ventilator_absaugung
action: humidifier.set_humidity
entity_id: humidifier.badezimmer
mode: single
- id: '1708188056710'
alias: IKEA STYRBAR - Moodlight Wohnzimmer
@@ -1168,14 +1051,14 @@
domain: switch
action_button_up_double:
- type: turn_on
device_id: 23aeb31cedaf3ff0bf14d4a05fc779da
device_id: 98a9eef603f8c8ae6200c4834a3dbf4f
entity_id: fdcff3852ecc17099c953da17eb4b8a3
domain: light
button_up_double_press: true
button_down_double_press: true
action_button_down_double:
- type: turn_off
device_id: 23aeb31cedaf3ff0bf14d4a05fc779da
device_id: 98a9eef603f8c8ae6200c4834a3dbf4f
entity_id: fdcff3852ecc17099c953da17eb4b8a3
domain: light
action_button_up_long: []
@@ -1446,7 +1329,7 @@
data:
volume_level: 0.47
- type: turn_off
device_id: f11b54371dd442568f1642fabf649116
device_id: 81d56cc472abaec2a02702def5f9cf66
entity_id: a57a56132635ff48a6d2ae8df322b385
domain: switch
mode: single
@@ -1459,7 +1342,7 @@
conditions: []
actions:
- type: turn_on
device_id: f11b54371dd442568f1642fabf649116
device_id: 81d56cc472abaec2a02702def5f9cf66
entity_id: a57a56132635ff48a6d2ae8df322b385
domain: switch
mode: single
@@ -1510,107 +1393,91 @@
device_id: 6d1be741876624a70ab5b01b54c6fd6f
entity_id: 621e4377a089b7f5d92c7c9f2cc171a1
domain: switch
- id: epaper_daily_demotivational_quote
alias: Epaper tägliches Demotivationszitat
description: Wählt täglich ein festes Zitat aus der lokalen Zitatbibliothek aus.
- id: '1773000000001'
alias: epaperframe - Kalender Events laden
description: Ruft alle Events von calendar.privat und calendar.tkrz_kalender für heute und morgen ab und schreibt sie in input_text-Helfer.
triggers:
- trigger: homeassistant
event: start
- trigger: time
at: 00:00:00
conditions: []
# Täglich um 00:01 neu holen
- trigger: time
at: '00:01:00'
id: daily
actions:
- action: input_select.select_option
target:
entity_id: input_select.epaper_demotivationszitat
data:
option: '{% set quotes = state_attr(''input_select.epaper_demotivationszitat'',
''options'') %} {{ quotes[(now().strftime(''%j'') | int - 1) % (quotes | count)]
}}'
mode: single
- id: '1785863986502'
alias: SmartMirror neu laden
description: ''
triggers:
- trigger: time
at: 00:00:10
conditions: []
actions:
- action: button.press
metadata: {}
target:
entity_id: button.touchkio_smartmirror_refresh
data: {}
- action: button.press
metadata: {}
target:
entity_id: button.touchkio_raspberrypi_refresh
data: {}
mode: single
- id: '1791126911003'
alias: 'Schlafzimmeruhr: Außentemperatur anzeigen'
description: ''
triggers:
- trigger: state
entity_id:
- binary_sensor.schlafzimmeruhr_button_2
to:
- 'on'
conditions: []
actions:
- action: esphome.sleepingroom_clock_show_number
data:
value: '{{ states(''sensor.aussentemperatur'') | round(0) | int }}'
unit: C
duration: 10000
mode: single
- id: '1791127515667'
alias: 'Schlafzimmeruhr: Sekunden anzeigen'
description: ''
triggers:
- trigger: state
entity_id:
- binary_sensor.schlafzimmeruhr_button_1
to:
- 'on'
conditions: []
actions:
- action: button.press
metadata: {}
target:
entity_id: button.schlafzimmeruhr_show_seconds
data: {}
mode: single
- id: energymonitor_backlight_workplace_presence
alias: 'Energy Monitor: Display nach Arbeitsplatz-Anwesenheit schalten'
description: Schaltet die Displaybeleuchtung beim Verlassen des Arbeitsplatzes aus
und bei der Rückkehr wieder ein.
triggers:
- trigger: zone
entity_id: person.marcus_scholz
zone: zone.arbeitsplatz_handwerker_gewerbepark
event: leave
id: leave
- trigger: zone
entity_id: person.marcus_scholz
zone: zone.arbeitsplatz_handwerker_gewerbepark
event: enter
id: enter
conditions: []
actions:
- choose:
- conditions:
- condition: trigger
id: leave
sequence:
- action: light.turn_off
target:
entity_id: light.energy_monitor_display_backlight
- conditions:
- condition: trigger
id: enter
sequence:
- action: light.turn_on
target:
entity_id: light.energy_monitor_display_backlight
mode: restart
# ── Events für heute (00:00 bis 23:59) holen ──
- action: calendar.get_events
target:
entity_id:
- calendar.privat
- calendar.tkrz_kalender
data:
start_date_time: "{{ now().replace(hour=0, minute=0, second=0) }}"
end_date_time: "{{ (now().replace(hour=0, minute=0, second=0) + timedelta(days=1)) }}"
response_variable: today_evts
# ── Events für morgen (00:00 bis 23:59) holen ──
- action: calendar.get_events
target:
entity_id:
- calendar.privat
- calendar.tkrz_kalender
data:
start_date_time: "{{ (now() + timedelta(days=1)).replace(hour=0, minute=0, second=0) }}"
end_date_time: "{{ (now() + timedelta(days=1)).replace(hour=0, minute=0, second=0) + timedelta(days=1) }}"
response_variable: tomorrow_evts
# ── input_text Helfer schreiben ──
- action: input_text.set_value
target:
entity_id: input_text.kalender_heute_privat
data:
value: >-
{%- set evts = today_evts['calendar.privat']['events'] if 'calendar.privat' in today_evts else [] -%}
{%- set items = [] -%}
{%- for e in evts[:5] -%}
{%- set s = (e['summary'] | default('', true) | string)[:40] if e is mapping and 'summary' in e else '-' -%}
{%- set st = e['start'] if e is mapping and 'start' in e else '' -%}
{%- set hhmm = st[11:16] if st|length >= 16 else '??' -%}
{%- set items = items + [hhmm ~ ' - ' ~ s] -%}
{%- endfor -%}
{{ items | join('│') if items else '-' }}
- action: input_text.set_value
target:
entity_id: input_text.kalender_heute_arbeit
data:
value: >-
{%- set evts = today_evts['calendar.tkrz_kalender']['events'] if 'calendar.tkrz_kalender' in today_evts else [] -%}
{%- set items = [] -%}
{%- for e in evts[:5] -%}
{%- set s = (e['summary'] | default('', true) | string)[:40] if e is mapping and 'summary' in e else '-' -%}
{%- set st = e['start'] if e is mapping and 'start' in e else '' -%}
{%- set hhmm = st[11:16] if st|length >= 16 else '??' -%}
{%- set items = items + [hhmm ~ ' - ' ~ s] -%}
{%- endfor -%}
{{ items | join('│') if items else '-' }}
- action: input_text.set_value
target:
entity_id: input_text.kalender_morgen_privat
data:
value: >-
{%- set evts = tomorrow_evts['calendar.privat']['events'] if 'calendar.privat' in tomorrow_evts else [] -%}
{%- set items = [] -%}
{%- for e in evts[:5] -%}
{%- set s = (e['summary'] | default('', true) | string)[:40] if e is mapping and 'summary' in e else '-' -%}
{%- set st = e['start'] if e is mapping and 'start' in e else '' -%}
{%- set hhmm = st[11:16] if st|length >= 16 else '??' -%}
{%- set items = items + [hhmm ~ ' - ' ~ s] -%}
{%- endfor -%}
{{ items | join('│') if items else '-' }}
- action: input_text.set_value
target:
entity_id: input_text.kalender_morgen_arbeit
data:
value: >-
{%- set evts = tomorrow_evts['calendar.tkrz_kalender']['events'] if 'calendar.tkrz_kalender' in tomorrow_evts else [] -%}
{%- set items = [] -%}
{%- for e in evts[:5] -%}
{%- set s = (e['summary'] | default('', true) | string)[:40] if e is mapping and 'summary' in e else '-' -%}
{%- set st = e['start'] if e is mapping and 'start' in e else '' -%}
{%- set hhmm = st[11:16] if st|length >= 16 else '??' -%}
{%- set items = items + [hhmm ~ ' - ' ~ s] -%}
{%- endfor -%}
{{ items | join('│') if items else '-' }}
+11 -6
View File
@@ -1,6 +1,12 @@
# Configure a default setup of Home Assistant (frontend, api, etc)
default_config:
# Enable SSL/TLS
http:
server_port: 443
ssl_certificate: /ssl/fullchain.pem
ssl_key: /ssl/privkey.pem
# Text to speech
tts:
- platform: picotts_remote
@@ -29,12 +35,6 @@ utility_meter: !include utility_meters.yaml
mqtt: !include mqtt.yaml
mqtt_statestream: !include mqtt_statestream.yaml
# Calendar data is normalised in a sandboxed script before ESPHome receives it.
python_script:
# Home Assistant-managed e-paper quote library
input_select: !include input_select.yaml
# Template sensors
template: !include template.yaml
@@ -49,6 +49,9 @@ sql:
# calendar integration
calendar: !include calendars.yaml
# Helpers for epaperframe calendar display
input_text: !include text_helpers.yaml
# DB-recorder configuration
recorder: !include recorder.yaml
@@ -85,3 +88,5 @@ frontend:
freedns:
url: !secret freedns6_url
# - name: IPv4
# url: !secret freedns4_url
+2 -2
View File
@@ -4,7 +4,7 @@ substitutions:
external_components_source: github://syssi/esphome-atorch-dl24@main
dl24_mac_address: !secret dl24_mac_address
project_version: 2.1.0
device_description: "ESP32-S3 BLE client to monitor and control an Atorch DL24 programmable DC load"
device_description: "Monitor and control a Atorch meter via bluetooth BLE"
esphome:
name: ${name}
@@ -36,7 +36,7 @@ api:
# Enable over-the-air updates
ota:
platform: esphome
encryption:
password: !secret ota
network:
enable_ipv6: true
+1 -3
View File
@@ -1,12 +1,10 @@
substitutions:
name: "aussensensor"
friendly_name: "Außensensor"
device_description: "NodeMCU-32S outdoor temperature and humidity sensor using a DHT22"
esphome:
name: ${name}
friendly_name: ${friendly_name}
comment: ${device_description}
name_add_mac_suffix: false
project:
name: sensor.outdoor
@@ -42,7 +40,7 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
# DHT22 sensor
sensor:
+1 -1
View File
@@ -31,7 +31,7 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
wifi:
ssid: "Voltage-legacy"
+1 -1
View File
@@ -46,7 +46,7 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
wifi:
ssid: "Voltage-legacy"
+1 -3
View File
@@ -3,7 +3,6 @@
substitutions:
name: "raspiaudio-muse-luxe"
friendly_name: "RaspiAudio Muse Luxe"
device_description: "RaspiAudio Muse Luxe ESP32 voice assistant and media player with local wake-word detection, ES8388 audio codec and battery monitoring"
#States
P_starting: "0"
P_waiting: "1"
@@ -19,7 +18,7 @@ api:
ota:
- platform: esphome
id: ota_esphome
encryption:
password: !secret ota
external_components:
- source: github://RASPIAUDIO/esphomeLuxe@main
@@ -44,7 +43,6 @@ wifi:
esphome:
name: ${name}
friendly_name: ${friendly_name}
comment: ${device_description}
min_version: 2025.2.0
name_add_mac_suffix: false
platformio_options:
+1 -3
View File
@@ -1,12 +1,10 @@
substitutions:
name: "sleepingroom"
friendly_name: "Luftqualität Schlafzimmer"
device_description: "NodeMCU-32S bedroom air-quality monitor with SCD30 CO2, temperature and humidity, PM1006 particulate sensing, RGB status LED and IR receiver/transmitter"
esphome:
name: ${name}
friendly_name: ${friendly_name}
comment: ${device_description}
name_add_mac_suffix: false
project:
name: sensor.${name}
@@ -82,7 +80,7 @@ api:
# Enable over-the-air updates
ota:
platform: esphome
encryption:
password: !secret ota
# Initialize I²C
i2c:
+1 -3
View File
@@ -1,10 +1,8 @@
substitutions:
device_description: "ESP32-C3 bathroom temperature and humidity monitor with DHT22 and SHT3x sensors"
name: "bathroom"
friendly_name: "Bad"
esphome:
comment: ${device_description}
name: ${name}
friendly_name: ${friendly_name}
name_add_mac_suffix: false
@@ -46,7 +44,7 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
# Initialize I²C
i2c:
-86
View File
@@ -1,86 +0,0 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins
from esphome.components import time as time_
from esphome.components.esp32 import include_builtin_idf_component
from esphome.const import CONF_ID, CONF_NUMBER, PLATFORM_ESP32
CODEOWNERS = ["@misterblack1"]
ESP_PLATFORMS = [PLATFORM_ESP32]
aip33628_ns = cg.esphome_ns.namespace("aip33628")
Aip33628Panel = aip33628_ns.class_("Aip33628Panel", cg.Component)
CONF_CLK_PIN = "clk_pin"
CONF_DATA_PIN = "data_pin"
CONF_CLK2_PIN = "clk2_pin"
CONF_DATA2_PIN = "data2_pin"
CONF_TIME_ID = "time_id"
CONF_MAX_CURRENT = "max_current"
CONF_TWELVE_HOUR = "twelve_hour"
CONF_BLINK_COLON = "blink_colon"
def _low_bank_pin(value):
"""Both buses are clocked from one write to the low GPIO output register.
That register only reaches GPIO0 to GPIO31. A pin above that would need a
second register and a second store per edge, which is most of the reason
the frame send is fast enough to subdivide a COM slot at all.
"""
pin = value[CONF_NUMBER]
if pin >= 32:
raise cv.Invalid(
f"GPIO{pin} is above GPIO31, and the display scan drives all four "
"lines from the low output register. Pick a pin below GPIO32."
)
return value
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(Aip33628Panel),
cv.Required(CONF_CLK_PIN): cv.All(
pins.internal_gpio_output_pin_schema, _low_bank_pin
),
cv.Required(CONF_DATA_PIN): cv.All(
pins.internal_gpio_output_pin_schema, _low_bank_pin
),
cv.Required(CONF_CLK2_PIN): cv.All(
pins.internal_gpio_output_pin_schema, _low_bank_pin
),
cv.Required(CONF_DATA2_PIN): cv.All(
pins.internal_gpio_output_pin_schema, _low_bank_pin
),
cv.Optional(CONF_TIME_ID): cv.use_id(time_.RealTimeClock),
# A fixed ceiling on IS[3:0]. It must not depend on what is on screen,
# or the whole panel changes brightness whenever the colon blinks.
cv.Optional(CONF_MAX_CURRENT, default=15): cv.int_range(min=0, max=15),
# Power on defaults only. Home Assistant owns both at run time
# through the template switches in clock.yaml.
cv.Optional(CONF_TWELVE_HOUR, default=True): cv.boolean,
cv.Optional(CONF_BLINK_COLON, default=True): cv.boolean,
}
).extend(cv.COMPONENT_SCHEMA)
async def to_code(config):
# The display scan uses GPTimer, which ESPHome excludes by default.
include_builtin_idf_component("esp_driver_gptimer")
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
clk = await cg.gpio_pin_expression(config[CONF_CLK_PIN])
data = await cg.gpio_pin_expression(config[CONF_DATA_PIN])
clk2 = await cg.gpio_pin_expression(config[CONF_CLK2_PIN])
data2 = await cg.gpio_pin_expression(config[CONF_DATA2_PIN])
cg.add(var.set_pins(clk, data, clk2, data2))
if CONF_TIME_ID in config:
rtc = await cg.get_variable(config[CONF_TIME_ID])
cg.add(var.set_time(rtc))
cg.add(var.set_max_current(config[CONF_MAX_CURRENT]))
cg.add(var.set_twelve_hour(config[CONF_TWELVE_HOUR]))
cg.add(var.set_blink_colon(config[CONF_BLINK_COLON]))
-917
View File
@@ -1,917 +0,0 @@
#include "aip33628.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <cmath>
#include <driver/gptimer.h>
#include <soc/gpio_struct.h>
namespace esphome {
namespace aip33628 {
static const char *const TAG = "aip33628";
// Each digit is one driver plus one pair of COM pairs, ten LED positions.
// Driver 1 carries the hours, driver 2 the minutes.
struct Block {
uint8_t drv;
uint8_t com_lo;
uint8_t com_hi;
};
static const Block BLOCKS[4] = {
{0, 0x30, 0xC0}, // hour tens, annunciator AM
{0, 0x03, 0x0C}, // hour ones, annunciator colon
{1, 0x30, 0xC0}, // minute tens, annunciator date dash
{1, 0x03, 0x0C}, // minute ones, annunciator degree mark
};
// Segment position within a block. Side 0 is COM low, side 1 is COM high.
struct SegPos {
uint8_t side;
uint8_t led;
};
static const SegPos SEGMAP[9] = {
{1, 5}, // A top
{1, 4}, // B top right
{1, 3}, // C bottom right
{1, 2}, // D bottom
{0, 5}, // E bottom left
{0, 4}, // F top left
{0, 3}, // G middle
{1, 1}, // annunciator
{0, 1}, // second annunciator, block 1 colon only
};
enum { SEG_ANNUN = 7, SEG_ANNUN2 = 8 };
// Physical position of every LED, extracted in docs/led-layout.md. The ids
// are the ones on the board layout map. Order matches SEGMAP.
const PosGeom GEOM[4][9] = {
{ // block 0, hour tens
{ 1, 19, 8}, // A top
{ 7, 41, 66}, // B top right
{ 6, 40, 194}, // C bottom right
{ 5, 19, 255}, // D bottom
{ 4, 0, 188}, // E bottom left
{ 2, 0, 66}, // F top left
{ 3, 20, 130}, // G middle
{ 8, 20, 65}, // AM mark
{0, 0, 0}, // unwired
},
{ // block 1, hour ones
{ 9, 93, 0}, // A top
{15, 112, 61}, // B top right
{14, 111, 198}, // C bottom right
{13, 90, 246}, // D bottom
{12, 72, 184}, // E bottom left
{10, 73, 65}, // F top left
{11, 92, 124}, // G middle
{16, 128, 68}, // colon upper
{18, 129, 189}, // colon lower
},
{ // block 2, minute tens
{19, 163, 5}, // A top
{25, 185, 67}, // B top right
{24, 185, 195}, // C bottom right
{23, 165, 247}, // D bottom
{22, 145, 188}, // E bottom left
{20, 143, 70}, // F top left
{21, 164, 122}, // G middle
{17, 128, 128}, // date dash
{0, 0, 0}, // unwired
},
{ // block 3, minute ones
{27, 233, 11}, // A top
{33, 255, 60}, // B top right
{32, 255, 190}, // C bottom right
{31, 234, 249}, // D bottom
{30, 216, 194}, // E bottom left
{28, 216, 68}, // F top left
{29, 235, 128}, // G middle
{26, 204, 18}, // degree mark
{0, 0, 0}, // unwired
},
};
// Seven segment font, bit 0 = A through bit 6 = G. The letters are the subset
// that reads unambiguously on seven segments, so a caller can put a unit or a
// short label in the rightmost position.
static uint8_t glyph(char c) {
switch (c) {
case 'A': return 0b1110111;
case 'b': return 0b1111100;
case 'C': return 0b0111001;
case 'c': return 0b1011000;
case 'd': return 0b1011110;
case 'E': return 0b1111001;
case 'F': return 0b1110001;
case 'H': return 0b1110110;
case 'h': return 0b1110100;
case 'L': return 0b0111000;
case 'n': return 0b1010100;
case 'o': return 0b1011100;
case 'P': return 0b1110011;
case 'r': return 0b1010000;
case 't': return 0b1111000;
case 'U': return 0b0111110;
case 'u': return 0b0011100;
case 'y': return 0b1101110;
case '0': return 0b0111111;
case '1': return 0b0000110;
case '2': return 0b1011011;
case '3': return 0b1001111;
case '4': return 0b1100110;
case '5': return 0b1101101;
case '6': return 0b1111101;
case '7': return 0b0000111;
case '8': return 0b1111111;
case '9': return 0b1101111;
case '-': return 0b1000000;
default: return 0;
}
}
// Home Assistant sends gamma encoded values and the panel is linear in
// current and in duty, so both have to be linearized here. 2.8 is the same
// exponent ESPHome uses by default, which is why gamma_correct is set to 1.0
// on the light itself. Applying it in both places would square it.
static const float PANEL_GAMMA = 2.8f;
// Slider position to a current step. A plain gamma curve assumes the output
// can reach zero. This panel bottoms out at IS_MA[0], so a third of the
// slider ends up clamped against that floor with nothing to show for it.
// Interpolating perceived output between the floor and full instead puts all
// sixteen steps across the whole slider.
static uint8_t current_for(float brightness) {
const float p_min = powf((float) IS_MA[0] / (float) IS_MA[15], 1.0f / PANEL_GAMMA);
float p = p_min + clamp(brightness, 0.0f, 1.0f) * (1.0f - p_min);
float want = powf(p, PANEL_GAMMA) * (float) IS_MA[15];
uint8_t best = 0;
for (uint8_t i = 1; i < 16; i++) {
if (fabsf((float) IS_MA[i] - want) < fabsf((float) IS_MA[best] - want))
best = i;
}
return best;
}
// Half brightness keeps the all-white hardware check brief and predictable.
static const float LAMP_BRIGHTNESS = 0.5f;
// Color component to a duty level. Duty is linear light, so the component
// has to be linearized before it is rounded, or every pastel rounds up to a
// saturated color. Pink is the clearest case, and rounds all the way to
// white.
static uint8_t duty_level(float c) {
return (uint8_t) lroundf(powf(clamp(c, 0.0f, 1.0f), PANEL_GAMMA) * (COLOR_LEVELS - 1));
}
static int com_index(uint8_t cs) {
for (int i = 0; i < 4; i++) {
if (COM_SEQ[i] == cs) return i;
}
return 0;
}
void Aip33628Panel::setup() {
for (auto *p : {clk_, data_, clk2_, data2_}) {
p->setup();
p->digital_write(false);
}
clk_mask_ = 1u << clk_->get_pin();
data_mask_ = 1u << data_->get_pin();
clk2_mask_ = 1u << clk2_->get_pin();
data2_mask_ = 1u << data2_->get_pin();
render_();
// A general purpose timer, not esp_timer. The esp_timer task dispatch path
// runs at task priority on core 0 alongside the WiFi task, which preempts
// it and stretches whichever COM slot happens to be lit. A 40us sub-frame
// does not ride that out, so this runs from the interrupt instead.
gptimer_config_t tcfg = {};
tcfg.clk_src = GPTIMER_CLK_SRC_DEFAULT;
tcfg.direction = GPTIMER_COUNT_UP;
tcfg.resolution_hz = 1000000; // one tick per microsecond
gptimer_alarm_config_t acfg = {};
acfg.alarm_count = UNIT_US; // fixed, one tick per binary weight unit
acfg.reload_count = 0;
acfg.flags.auto_reload_on_alarm = true;
gptimer_event_callbacks_t cbs = {};
cbs.on_alarm = &Aip33628Panel::scan_tick_;
gptimer_handle_t timer = nullptr;
if (gptimer_new_timer(&tcfg, &timer) != ESP_OK ||
gptimer_register_event_callbacks(timer, &cbs, this) != ESP_OK ||
gptimer_set_alarm_action(timer, &acfg) != ESP_OK ||
gptimer_enable(timer) != ESP_OK || gptimer_start(timer) != ESP_OK) {
ESP_LOGE(TAG, "could not start the scan timer");
this->mark_failed();
}
}
void Aip33628Panel::dump_config() {
ESP_LOGCONFIG(TAG, "AiP33628 panel:");
LOG_PIN(" CLK: ", clk_);
LOG_PIN(" DATA: ", data_);
LOG_PIN(" CLK_1: ", clk2_);
LOG_PIN(" DATA_1: ", data2_);
ESP_LOGCONFIG(TAG, " Max current: IS 0x%X, %u.%umA per lit sink", max_current_,
IS_MA[max_current_] / 10, IS_MA[max_current_] % 10);
ESP_LOGCONFIG(TAG, " Hour format: %s", twelve_hour_ ? "12 hour" : "24 hour");
ESP_LOGCONFIG(TAG, " Colon: %s", blink_colon_ ? "blinking" : "steady");
ESP_LOGCONFIG(TAG, " Network: %s", online_ ? "up" : "down");
const char *fx = effect_ == Effect::CYCLE ? "color cycle"
: effect_ == Effect::FLASH ? "flash" : "none";
const char *sp = spread_ == Spread::DIGIT ? "per digit"
: spread_ == Spread::LED ? "per LED" : "whole panel";
// INFO rather than LOGCONFIG on purpose. The rest of this block is wiring
// that cannot change, but the effect is live state worth being able to read
// back, and CONFIG level messages need a DEBUG logger to be visible at all.
ESP_LOGI(TAG, " Effect: %s, %s, %.1fs, axis %.0f deg, hue span %.0f deg, flash fade %.2fs",
fx, sp, effect_speed_, effect_angle_, hue_span_, flash_fade_);
}
// Emit one 30-bit frame to each driver and latch both. Bits are LSB first:
// SS[15:0], CS[7:0], IS[3:0], then two reserved zeros. Data only changes
// while CLK is low. The latch is a DATA rising edge while CLK is held high
// after the last bit, which is the sequence the stock 8051 produces.
//
// CS and IS are common to the two drivers and only SS differs, so one pass
// down the bits clocks both buses. That halves the work outright, and going
// straight to the port registers rather than through ISRInternalGPIOPin took
// the pair from 28.0us to 6.4us. The AiP33628 accepts 30MHz and asks for
// 16ns of CLK high and low, and a store to the GPIO port costs more than
// that on its own, so the loop needs no padding.
void IRAM_ATTR Aip33628Panel::send_pair_(uint16_t ss1, uint16_t ss2, uint8_t cs, uint8_t is) {
const uint32_t wire = (uint32_t) IS_WIRE[is & 0xF] << 24;
uint32_t f1 = (uint32_t) ss1 | ((uint32_t) cs << 16) | wire;
uint32_t f2 = (uint32_t) ss2 | ((uint32_t) cs << 16) | wire;
const uint32_t clks = clk_mask_ | clk2_mask_;
const uint32_t dats = data_mask_ | data2_mask_;
// Chip differentiation for the initial register reset
#if defined(CONFIG_IDF_TARGET_ESP32C3)
GPIO.out_w1tc.val = clks | dats;
#else
GPIO.out_w1tc = clks | dats;
#endif
for (int i = 0; i < 30; i++) {
uint32_t set = 0;
if (f1 & 1)
set |= data_mask_;
if (f2 & 1)
set |= data2_mask_;
f1 >>= 1;
f2 >>= 1;
// Data transmission loop
#if defined(CONFIG_IDF_TARGET_ESP32C3)
GPIO.out_w1tc.val = dats & ~set;
GPIO.out_w1ts.val = set;
GPIO.out_w1ts.val = clks;
if (i < 29)
GPIO.out_w1tc.val = clks;
#else
GPIO.out_w1tc = dats & ~set;
GPIO.out_w1ts = set;
GPIO.out_w1ts = clks;
if (i < 29)
GPIO.out_w1tc = clks;
#endif
}
// Final latch sequence
#if defined(CONFIG_IDF_TARGET_ESP32C3)
GPIO.out_w1tc.val = dats;
GPIO.out_w1ts.val = dats;
GPIO.out_w1tc.val = dats;
GPIO.out_w1tc.val = clks;
#else
GPIO.out_w1tc = dats;
GPIO.out_w1ts = dats;
GPIO.out_w1tc = dats;
GPIO.out_w1tc = clks;
#endif
}
// Walk the schedule the renderer built. The timer runs at a fixed UNIT_US
// and this counts ticks, rather than reprogramming the alarm per step.
// Reprogramming would be fewer interrupts, but an alarm set shorter than the
// counter has already reached never matches, and a single late interrupt
// would then freeze the panel until reboot. A fixed auto-reload alarm cannot
// do that: a late interrupt costs one wobbly sub-frame and nothing more.
//
// Most ticks do nothing. A saturated color collapses to one step per COM
// pair, so fourteen of every fifteen calls are a decrement and a return.
bool IRAM_ATTR Aip33628Panel::scan_tick_(gptimer_handle_t timer,
const gptimer_alarm_event_data_t *edata, void *arg) {
auto *self = static_cast<Aip33628Panel *>(arg);
if (self->wait_ > 0) {
self->wait_--;
return false;
}
const ScanBuf &b = self->buf_[self->front_];
// The renderer can flip the buffer between two steps, and the new schedule
// may be shorter than the old one, so the index is clamped rather than
// trusted. Worst case is one odd frame while a slider is moving.
uint8_t i = self->step_;
if (i >= b.n)
i = 0;
const ScanStep &st = b.step[i];
self->send_pair_(st.ss[0], st.ss[1], st.cs, b.is);
self->wait_ = (uint8_t) (st.units - 1); // this tick is the first of the step
uint8_t next = (uint8_t) (i + 1);
self->step_ = next >= b.n ? 0 : next;
return false; // no task woken, so no yield needed
}
void Aip33628Panel::write_pos_(uint8_t block, uint8_t seg, bool on) {
on_[block][seg] = on;
}
void Aip33628Panel::write_digit_(uint8_t block, char c) {
uint8_t bits = glyph(c);
for (int s = 0; s < 7; s++) {
on_[block][s] = (bits >> s) & 1;
}
}
// brightness is linear and carries the transition state, so it falls to zero
// on its own during a fade to off. The color components are the normalized
// ratio and do not scale with it. ESPHome guarantees the largest of the three
// is 1, so at least one channel always survives duty_level and a color can
// never round away to nothing.
void Aip33628Panel::set_light(bool on, float r, float g, float b, float brightness) {
enabled_ = on && brightness > 0.0f;
// Picking a new color on the master light means the whole panel, so it
// drops the digit and position tiers. Moving only the brightness slider
// leaves them alone, which matters because a transition calls this on
// every step and would otherwise wipe a gradient mid fade.
bool color_moved = fabsf(r - base_rgb_[0]) > 0.002f || fabsf(g - base_rgb_[1]) > 0.002f ||
fabsf(b - base_rgb_[2]) > 0.002f;
if (color_moved && effect_ == Effect::NONE) {
for (bool &v : digit_set_)
v = false;
clear_positions_();
}
base_rgb_[0] = r;
base_rgb_[1] = g;
base_rgb_[2] = b;
requested_current_ = current_for(brightness);
apply_colors_();
}
// Quantize whatever color each block is currently supposed to be. Everything
// that changes a color goes through here, so there is one place that decides
// what a block ends up at and one place that marks the panel dirty.
void Aip33628Panel::apply_colors_() {
// The lamp test outranks every color tier, including a running effect.
if (mode_ == Mode::LAMP) {
for (auto &blk : level_)
for (auto &seg : blk)
for (uint8_t &ch : seg)
ch = COLOR_LEVELS - 1;
dirty_ = true;
return;
}
for (int blk = 0; blk < 4; blk++) {
for (int seg = 0; seg < 9; seg++) {
const float *c = pos_set_[blk][seg] ? pos_rgb_[blk][seg]
: digit_set_[blk] ? digit_rgb_[blk]
: base_rgb_;
level_[blk][seg][CH_RED] = duty_level(c[0] * envelope_);
level_[blk][seg][CH_GREEN] = duty_level(c[1] * envelope_);
level_[blk][seg][CH_BLUE] = duty_level(c[2] * envelope_);
}
}
dirty_ = true;
}
// A digit of -1 sets all four at once, which is what a whole display effect
// wants. Components are taken as given and not normalized: the master light
// arrives already normalized with its magnitude in the current setting, but a
// caller here is asking for one digit to look a particular way next to the
// others, and scaling that back up would throw away the difference.
void Aip33628Panel::set_digit_color(int digit, float r, float g, float b) {
if (digit < -1 || digit > 3)
return;
for (int blk = 0; blk < 4; blk++) {
if (digit != -1 && digit != blk)
continue;
digit_rgb_[blk][0] = clamp(r, 0.0f, 1.0f);
digit_rgb_[blk][1] = clamp(g, 0.0f, 1.0f);
digit_rgb_[blk][2] = clamp(b, 0.0f, 1.0f);
digit_set_[blk] = true;
// Setting a whole digit drops any per position color inside it. Without
// this a gradient would sit on top and the digit color would do nothing
// visible, which reads as the call being ignored.
for (bool &v : pos_set_[blk])
v = false;
}
apply_colors_();
}
// Hand the whole panel back to the master light, per position overrides
// included. Anything else would leave a gradient stuck on with no obvious way
// to clear it.
void Aip33628Panel::clear_digit_colors() {
for (bool &v : digit_set_)
v = false;
clear_positions_();
apply_colors_();
}
void Aip33628Panel::clear_positions_() {
for (auto &blk : pos_set_)
for (bool &v : blk)
v = false;
}
// One LED, addressed by the id on the board layout map rather than by block
// and segment, so the numbering here is the same one written on the map.
void Aip33628Panel::set_position_color(int id, float r, float g, float b) {
for (int blk = 0; blk < 4; blk++) {
for (int seg = 0; seg < 9; seg++) {
if (GEOM[blk][seg].id != id)
continue;
pos_rgb_[blk][seg][0] = clamp(r, 0.0f, 1.0f);
pos_rgb_[blk][seg][1] = clamp(g, 0.0f, 1.0f);
pos_rgb_[blk][seg][2] = clamp(b, 0.0f, 1.0f);
pos_set_[blk][seg] = true;
apply_colors_();
return;
}
}
}
// A linear ramp across the panel between two colors. Angle is in degrees, 0
// running left to right and 90 top to bottom, so -45 runs from the bottom
// left corner to the top right.
//
// The ramp is normalized against the LEDs themselves rather than the panel
// outline, so the two colors asked for land exactly on the outermost LEDs
// whichever way the ramp points. Normalizing against the corners instead
// leaves both ends short, because no LED sits in a corner.
void Aip33628Panel::set_gradient(float r0, float g0, float b0, float r1, float g1, float b1,
float angle_deg) {
const float a = angle_deg * 3.14159265f / 180.0f;
const float ca = cosf(a), sa = sinf(a);
float lo = 1e9f, hi = -1e9f;
for (int blk = 0; blk < 4; blk++) {
for (int seg = 0; seg < 9; seg++) {
const PosGeom &g = GEOM[blk][seg];
if (g.id == 0)
continue;
float t = (g.nx / 255.0f) * ca + (g.ny / 255.0f) * sa;
if (t < lo)
lo = t;
if (t > hi)
hi = t;
}
}
float span = hi - lo;
if (span < 1e-6f)
span = 1.0f;
for (int blk = 0; blk < 4; blk++) {
for (int seg = 0; seg < 9; seg++) {
const PosGeom &g = GEOM[blk][seg];
if (g.id == 0)
continue; // nothing wired here
float t = ((g.nx / 255.0f) * ca + (g.ny / 255.0f) * sa - lo) / span;
t = clamp(t, 0.0f, 1.0f);
pos_rgb_[blk][seg][0] = clamp(r0 + (r1 - r0) * t, 0.0f, 1.0f);
pos_rgb_[blk][seg][1] = clamp(g0 + (g1 - g0) * t, 0.0f, 1.0f);
pos_rgb_[blk][seg][2] = clamp(b0 + (b1 - b0) * t, 0.0f, 1.0f);
pos_set_[blk][seg] = true;
}
}
apply_colors_();
}
// A temporary mode is capped rather than trusted. Ten minutes is far longer
// than any of these are useful for, and it means a bad automation cannot park
// the panel on a stale number forever.
static uint32_t mode_lifetime(int ms) {
if (ms < 100) return 100;
if (ms > 600000) return 600000;
return (uint32_t) ms;
}
void Aip33628Panel::show_seconds(int ms) {
mode_ = Mode::SECONDS;
mode_until_ = millis() + mode_lifetime(ms);
dirty_ = true;
}
void Aip33628Panel::show_number(int value, const std::string &unit, int ms) {
number_ = value;
// First character only. An empty unit gives the number the whole panel.
unit_ = unit.empty() ? '\0' : unit[0];
mode_ = Mode::NUMBER;
mode_until_ = millis() + mode_lifetime(ms);
dirty_ = true;
}
// Every populated position, white, at a fixed brightness, for a few seconds.
// This is a hardware check, so user color and brightness settings do not
// change the result.
void Aip33628Panel::lamp_test(int ms) {
mode_ = Mode::LAMP;
mode_until_ = millis() + mode_lifetime(ms);
lamp_current_ = current_for(LAMP_BRIGHTNESS);
apply_colors_();
}
// Right aligned, no colon. A unit takes the rightmost position and leaves
// three for the number, so 78F and -5C both fit. Without one the number gets
// all four. Out of range values are clamped rather than wrapped, because a
// wrapped temperature is a wrong reading and a clamped one is obviously
// pinned against the end.
//
// The widest values reach the hour tens position. With a unit that only
// happens at three digits or a signed two, and never for a temperature in F.
void Aip33628Panel::draw_number_(int value, char unit) {
int pos = 3;
if (unit != '\0' && glyph(unit) != 0) {
write_digit_(3, unit);
pos = 2;
// C and F are temperatures, so light the degree mark ahead of the unit.
if (unit == 'C' || unit == 'c' || unit == 'F')
write_pos_(3, SEG_ANNUN, true);
}
bool neg = value < 0;
if (neg) value = -value;
int room = pos + 1 - (neg ? 1 : 0); // positions left for digits
int limit = 1;
for (int i = 0; i < room; i++) limit *= 10;
if (value > limit - 1) value = limit - 1;
do {
write_digit_(pos--, (char) ('0' + value % 10));
value /= 10;
} while (value > 0 && pos >= 0);
if (neg && pos >= 0) write_digit_(pos, '-');
}
// Full saturation hue to RGB. Effects ride the color wheel rather than the
// master light's color, because a rainbow that keeps the user's tint is not
// a rainbow.
static void hue_rgb(float h, float *out) {
h -= floorf(h);
float x = h * 6.0f;
int i = (int) x;
float f = x - (float) i;
switch (i % 6) {
case 0: out[0] = 1.0f; out[1] = f; out[2] = 0.0f; break;
case 1: out[0] = 1.0f - f; out[1] = 1.0f; out[2] = 0.0f; break;
case 2: out[0] = 0.0f; out[1] = 1.0f; out[2] = f; break;
case 3: out[0] = 0.0f; out[1] = 1.0f - f; out[2] = 1.0f; break;
case 4: out[0] = f; out[1] = 0.0f; out[2] = 1.0f; break;
default: out[0] = 1.0f; out[1] = 0.0f; out[2] = 1.0f - f; break;
}
}
// Where every position sits along the effect axis, 0 at the trailing edge
// and 1 at the leading one. Same projection the gradient uses, normalized
// against the LEDs rather than the panel outline for the same reason. Only
// recomputed when the angle changes.
void Aip33628Panel::recompute_axis_() {
const float a = effect_angle_ * 3.14159265f / 180.0f;
const float ca = cosf(a), sa = sinf(a);
float lo = 1e9f, hi = -1e9f;
for (int blk = 0; blk < 4; blk++) {
for (int seg = 0; seg < 9; seg++) {
if (GEOM[blk][seg].id == 0)
continue;
float t = (GEOM[blk][seg].nx / 255.0f) * ca + (GEOM[blk][seg].ny / 255.0f) * sa;
if (t < lo) lo = t;
if (t > hi) hi = t;
}
}
float span = hi - lo;
if (span < 1e-6f)
span = 1.0f;
float blo = 1e9f, bhi = -1e9f;
for (int blk = 0; blk < 4; blk++) {
float sum = 0.0f;
int n = 0;
for (int seg = 0; seg < 9; seg++) {
if (GEOM[blk][seg].id == 0)
continue;
float t = ((GEOM[blk][seg].nx / 255.0f) * ca + (GEOM[blk][seg].ny / 255.0f) * sa - lo) / span;
axis_pos_[blk][seg] = t;
sum += t;
n++;
}
axis_blk_[blk] = n ? sum / (float) n : 0.0f;
if (axis_blk_[blk] < blo) blo = axis_blk_[blk];
if (axis_blk_[blk] > bhi) bhi = axis_blk_[blk];
}
// Normalized end to end, same as the per position axis. How much of the
// wheel that covers is the hue span setting's job, not this one's.
float bspan = bhi - blo;
if (bspan < 1e-6f)
bspan = 1.0f;
for (int blk = 0; blk < 4; blk++)
axis_blk_[blk] = (axis_blk_[blk] - blo) / bspan;
}
void Aip33628Panel::set_effect(int mode) {
Effect want = mode == 1 ? Effect::CYCLE : mode == 2 ? Effect::FLASH : Effect::NONE;
if (want == effect_)
return;
effect_ = want;
effect_t0_ = millis();
effect_at_ = 0;
// Leaving an effect hands the panel back rather than freezing on whatever
// frame it happened to stop at.
envelope_ = 1.0f;
if (want == Effect::NONE)
clear_positions_();
if (want == Effect::CYCLE)
recompute_axis_();
apply_colors_();
}
void Aip33628Panel::set_effect_speed(float seconds) {
effect_speed_ = seconds < 0.1f ? 0.1f : (seconds > 600.0f ? 600.0f : seconds);
}
void Aip33628Panel::set_effect_spread(int mode) {
spread_ = mode == 1 ? Spread::DIGIT : mode == 2 ? Spread::LED : Spread::PANEL;
}
void Aip33628Panel::set_effect_angle(float deg) {
effect_angle_ = deg;
recompute_axis_();
}
void Aip33628Panel::set_effect_hue_span(float deg) {
hue_span_ = deg < 0.0f ? 0.0f : (deg > 360.0f ? 360.0f : deg);
}
void Aip33628Panel::set_flash_fade(float seconds) {
flash_fade_ = seconds < 0.0f ? 0.0f : (seconds > 300.0f ? 300.0f : seconds);
}
// Advance whichever effect is running. Called from loop() at a fixed cadence
// rather than every pass, since the scan is what the eye sees and a redraw
// faster than about 25Hz buys nothing.
void Aip33628Panel::update_effect_(uint32_t now_ms) {
float period = effect_speed_;
float phase = fmodf((float) (now_ms - effect_t0_) / 1000.0f / period, 1.0f);
if (effect_ == Effect::FLASH) {
// A trapezoid. Rate and transition time are separate, so 1Hz with a 100ms
// ramp and 1Hz snapping hard are both reachable. The on and off halves
// stay even and the ramps eat into them rather than stretching the
// period, so changing the fade never changes the flash rate.
const float half = period * 0.5f;
const float f = flash_fade_ > half ? half : flash_fade_;
const float t = phase * period;
float e;
if (f <= 0.0f) {
e = t < half ? 1.0f : 0.0f; // square
} else if (t < f) {
e = t / f;
} else if (t < half) {
e = 1.0f;
} else if (t < half + f) {
e = 1.0f - (t - half) / f;
} else {
e = 0.0f;
}
envelope_ = e;
apply_colors_();
return;
}
// How much of the wheel the panel covers end to end. A full turn across
// four digits packs the whole spectrum into a hand span and reads as noise.
const float span = hue_span_ / 360.0f;
for (int blk = 0; blk < 4; blk++) {
for (int seg = 0; seg < 9; seg++) {
if (GEOM[blk][seg].id == 0)
continue;
float t = spread_ == Spread::PANEL ? 0.0f
: spread_ == Spread::DIGIT ? axis_blk_[blk]
: axis_pos_[blk][seg];
hue_rgb(phase + t * span, pos_rgb_[blk][seg]);
pos_set_[blk][seg] = true;
}
}
apply_colors_();
}
void Aip33628Panel::loop() {
uint32_t now_ms = millis();
if (effect_ != Effect::NONE && (int32_t) (now_ms - effect_at_) >= 0) {
effect_at_ = now_ms + 40; // 25Hz, smooth enough for a fade to glide
update_effect_(now_ms);
}
// A temporary mode expires here rather than anywhere else, so there is one
// place that can put the panel back to being a clock.
if (mode_ != Mode::TIME && (int32_t) (now_ms - mode_until_) >= 0) {
bool was_lamp = mode_ == Mode::LAMP;
mode_ = Mode::TIME;
dirty_ = true;
if (was_lamp)
apply_colors_();
}
ESPTime now{};
bool valid = false;
if (time_ != nullptr) {
now = time_->now();
valid = now.is_valid();
}
// Whatever is on the panel, reduced to one number, so an unchanged display
// costs nothing. Time uses hour and minute together rather than the minute
// alone, because Home Assistant can push a new timezone at any point and
// every shift is a whole number of hours. A mode change sets dirty_ itself,
// so the key never has to encode which mode produced it.
int key = -1;
if (mode_ == Mode::NUMBER) {
key = number_;
} else if (valid) {
key = mode_ == Mode::SECONDS ? now.second : now.hour * 60 + now.minute;
}
// The colon blinks once a second, so the content changes more often than
// the time does. Blinking off means a steady colon, not a dark one.
bool colon = blink_colon_ ? ((now_ms / 1000) % 2 == 0) : true;
if (!dirty_ && key == last_key_ && colon == last_colon_) return;
last_key_ = key;
last_colon_ = colon;
dirty_ = false;
for (auto &blk : on_) {
for (bool &v : blk) v = false;
}
// A hardware check also works while the normal display light is off.
if (mode_ == Mode::LAMP) {
for (int blk = 0; blk < 4; blk++) {
for (int seg = 0; seg < 9; seg++)
on_[blk][seg] = GEOM[blk][seg].id != 0;
}
render_();
return;
}
if (!enabled_) {
render_();
return;
}
// A pushed number does not need the clock to be set, so it comes first.
if (mode_ == Mode::NUMBER) {
draw_number_(number_, unit_);
render_();
return;
}
if (!valid) {
// No time yet. Four dashes says so without pretending to know the hour.
for (int i = 0; i < 4; i++) write_digit_(i, '-');
render_();
return;
}
if (mode_ == Mode::SECONDS) {
// Seconds sit where the minutes normally do, behind a colon that stays
// steady, so the panel reads as :SS rather than as a bare two digit
// number that could be anything. The upper dot still follows the network.
write_digit_(2, (char) ('0' + now.second / 10));
write_digit_(3, (char) ('0' + now.second % 10));
if (online_) write_pos_(1, SEG_ANNUN, true);
write_pos_(1, SEG_ANNUN2, true);
render_();
return;
}
int hour = now.hour;
bool pm = hour >= 12;
if (twelve_hour_) {
hour = hour % 12;
if (hour == 0) hour = 12;
}
// Leading zero stays suppressed in 24 hour mode as well.
if (hour >= 10) {
write_digit_(0, (char) ('0' + hour / 10));
}
write_digit_(1, (char) ('0' + hour % 10));
write_digit_(2, (char) ('0' + now.minute / 10));
write_digit_(3, (char) ('0' + now.minute % 10));
if (colon) {
// Both dots when the network is up, the lower one alone when it is not.
// Block 2 COM low LED1 is the lower dot, see docs/display-map.md.
if (online_) write_pos_(1, SEG_ANNUN, true);
write_pos_(1, SEG_ANNUN2, true);
}
if (twelve_hour_ && !pm) {
write_pos_(0, SEG_ANNUN, true); // AM indicator, lit through the morning
}
render_();
}
// Collapse the panel state into a scan schedule. Each COM pair is split into
// COLOR_BITS binary weighted sub-frames, and a channel at duty level L is lit
// in sub-frame k whenever bit k of L is set. Any level from 0 to
// COLOR_LEVELS - 1 is reachable that way, with no constraint that a dimmer
// channel be a subset of a brighter one.
//
// Per digit color costs nothing here. Each driver and COM pair together
// belong to exactly one block, since the two blocks on a driver sit on
// different COM pairs, so a slot only ever holds one block's color per
// driver and the two drivers carry their own SS word anyway. Four different
// colors reach sixteen steps, which is exactly MAX_STEPS.
void Aip33628Panel::render_() {
uint16_t sub[2][4][COLOR_BITS] = {};
for (int blk = 0; blk < 4; blk++) {
const Block &b = BLOCKS[blk];
for (int seg = 0; seg < 9; seg++) {
if (!on_[blk][seg])
continue;
const SegPos &sp = SEGMAP[seg];
int ci = com_index(sp.side ? b.com_hi : b.com_lo);
int base = 3 * sp.led - 2; // LED1 is SEG1..SEG3, LED5 is SEG13..SEG15
for (int ch = 0; ch < 3; ch++) {
uint8_t lv = level_[blk][seg][ch];
if (lv == 0)
continue;
uint16_t bit = (uint16_t) (1u << (base + ch));
for (int k = 0; k < COLOR_BITS; k++) {
if (lv & (1u << k))
sub[b.drv][ci][k] |= bit;
}
}
}
}
// IS is set by the brightness alone and never by what is on screen. Making
// it depend on the lit sink count changes the brightness of the whole panel
// every time the colon blinks. The stock firmware held IS fixed across
// colon on and colon off, and ran 0xF with a white digit lit.
// The lamp test brings its own current, while max_current_ remains the
// thermal ceiling for every mode.
uint8_t want = mode_ == Mode::LAMP ? lamp_current_ : requested_current_;
uint8_t is = want < max_current_ ? want : max_current_;
ScanBuf &b = buf_[front_ ^ 1];
b.n = 0;
for (int ci = 0; ci < 4; ci++) {
for (int k = 0; k < COLOR_BITS; k++) {
uint16_t s0 = sub[0][ci][k];
uint16_t s1 = sub[1][ci][k];
uint8_t units = (uint8_t) (1u << k);
// Identical neighbors inside one COM pair merge, so a saturated color,
// where every sub-frame carries the same data, ends up as one step of
// the full 600us. Merging never crosses a COM boundary, because CS
// changes there and the drivers have to be re-sent regardless.
if (k > 0 && b.n > 0 && b.step[b.n - 1].ss[0] == s0 && b.step[b.n - 1].ss[1] == s1) {
b.step[b.n - 1].units = (uint8_t) (b.step[b.n - 1].units + units);
continue;
}
ScanStep &st = b.step[b.n++];
st.units = units;
st.ss[0] = s0;
st.ss[1] = s1;
st.cs = COM_SEQ[ci];
}
}
b.is = is;
// Publish. The barrier keeps the writes above from being reordered past the
// flip, which is what stops the scan callback seeing a torn pattern while a
// Home Assistant slider is being dragged.
__sync_synchronize();
front_ ^= 1;
}
} // namespace aip33628
} // namespace esphome
-272
View File
@@ -1,272 +0,0 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "esphome/components/light/light_output.h"
#include "esphome/components/time/real_time_clock.h"
#include <driver/gptimer.h>
namespace esphome {
namespace aip33628 {
// Two AiP33628 drivers behind the HU-058D panel, one per two-wire bus.
// Mapping, scan timing and the current budget are documented in
// docs/display-map.md.
static const uint8_t DRAM_ATTR COM_SEQ[4] = {0x30, 0x0C, 0x03, 0xC0};
// Each COM pair holds the bus for 600us, so a full four pair cycle is 2400us
// and the panel refreshes at 416.7Hz, within a hertz of what the stock
// firmware ran.
//
// That 600us is subdivided into binary weighted sub-frames, 40, 80, 160 and
// 320us. A channel wanting duty level L is lit in the sub-frames whose weight
// bits are set in L, so four sub-frames buy sixteen levels rather than the
// five that four equal ones would. The shortest sub-frame is 40us against a
// 6.4us frame send, so there is room to spare.
static const uint8_t COLOR_BITS = 4;
static const uint8_t COLOR_LEVELS = 1 << COLOR_BITS; // 0 to 15 inclusive
static const uint32_t UNIT_US = 40;
static const uint8_t MAX_STEPS = 4 * COLOR_BITS;
// Current step to mA, from the datasheet. Tenths of a mA.
static const uint16_t IS_MA[16] = {25, 51, 76, 101, 126, 152, 177, 202,
227, 253, 278, 303, 328, 354, 379, 404};
// Current step to the nibble that goes on the wire. The frame carries IS[0]
// at bit 27 and IS[3] at bit 24, so the field is bit reversed against the
// rest of the frame. Steps 0 and 15 are palindromes, which is why getting
// this wrong looks correct at both ends of the brightness range and scrambles
// the order everywhere in between. The table is its own inverse.
static const uint8_t DRAM_ATTR IS_WIRE[16] = {0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE,
0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF};
enum Channel : uint8_t { CH_BLUE = 0, CH_GREEN = 1, CH_RED = 2 };
// Where each LED physically sits, from docs/led-layout.md. id is the number
// used by the board layout map and by set_position_color, 1 to 33, and 0
// marks a position the panel can address but nothing is wired to. nx runs 0
// at the left edge of the first digit to 255 at the right edge of the last,
// ny 0 at the top of a digit to 255 at the bottom.
struct PosGeom {
uint8_t id;
uint8_t nx;
uint8_t ny;
};
extern const PosGeom GEOM[4][9];
// Running effects. Each owns the panel while it is selected, and selecting
// NONE hands it back to whatever the colors were before.
enum class Effect : uint8_t { NONE = 0, CYCLE = 1, FLASH = 2 };
// How far apart an effect spreads its phase across the panel. PANEL moves
// everything together, DIGIT gives each digit its own phase, LED gives every
// position its own. The direction the spread runs is the effect angle.
enum class Spread : uint8_t { PANEL = 0, DIGIT = 1, LED = 2 };
// What the panel is showing. Everything except TIME is temporary and expires
// on its own, so no caller can leave the clock stuck not being a clock.
enum class Mode : uint8_t { TIME, SECONDS, NUMBER, LAMP };
// One step of the scan schedule: latch this pattern on both drivers, then
// hold it for this long. Adjacent sub-frames with identical data collapse
// into a single longer step, so a saturated color costs one send per COM
// pair, exactly what the two level scan cost before.
struct ScanStep {
uint8_t units; // dwell, in UNIT_US ticks, 1 to 15
uint8_t cs;
uint16_t ss[2];
};
// One complete scan pattern. render_() fills the back buffer and then flips
// front_, so the scan callback can never read a half written pattern.
struct ScanBuf {
ScanStep step[MAX_STEPS];
uint8_t n;
uint8_t is;
};
class Aip33628Panel : public Component {
public:
void set_pins(InternalGPIOPin *clk, InternalGPIOPin *data, InternalGPIOPin *clk2,
InternalGPIOPin *data2) {
clk_ = clk;
data_ = data;
clk2_ = clk2;
data2_ = data2;
}
void set_time(time::RealTimeClock *rtc) { time_ = rtc; }
void set_max_current(uint8_t is) { max_current_ = is; }
// Both of these are live. Home Assistant drives them through template
// switches, so each has to force a redraw rather than wait for the next
// rollover.
void set_twelve_hour(bool v) {
twelve_hour_ = v;
dirty_ = true;
}
void set_blink_colon(bool v) {
blink_colon_ = v;
dirty_ = true;
}
// Offline drops the upper colon dot, so a glance at the panel says whether
// the time is still being kept honest. Driven from the wifi triggers in
// clock.yaml rather than by including the wifi component here.
void set_online(bool v) {
online_ = v;
dirty_ = true;
}
void setup() override;
void loop() override;
void dump_config() override;
float get_setup_priority() const override { return setup_priority::HARDWARE; }
// Called by the light platform. Color components and brightness are 0 to 1.
void set_light(bool on, float r, float g, float b, float brightness);
// Temporary displays, driven from the api actions in clock.yaml. Each takes
// a lifetime in milliseconds and falls back to the time when it runs out.
void show_seconds(int ms);
void show_number(int value, const std::string &unit, int ms);
// Every populated position, white, at a fixed brightness. Ignores the
// color tiers, any running effect, and the light being off.
void lamp_test(int ms);
// Per digit color. Blocks are 0 to 3, left to right, and each carries its
// own annunciator: block 0 the AM mark, block 1 the colon, block 2 the date
// dash. Components run 0 to 1 and are used as given rather than normalized,
// so a digit can be dimmer than its neighbors as well as a different hue,
// which is what a per digit fade needs. A digit with no color of its own
// follows the master light.
void set_digit_color(int digit, float r, float g, float b);
void clear_digit_colors();
// One LED, by the id in docs/led-layout.md. Overrides the digit color,
// which in turn overrides the master light.
void set_position_color(int id, float r, float g, float b);
// A linear ramp between two colors across the panel. The angle is in
// degrees, 0 running left to right and 90 top to bottom, and the ramp is
// always stretched to cover the whole panel whatever the angle.
void set_gradient(float r0, float g0, float b0, float r1, float g1, float b1,
float angle_deg);
// Effects. Everything here is live and takes hold on the next update.
void set_effect(int mode);
void set_effect_speed(float seconds);
void set_effect_spread(int mode);
void set_effect_angle(float deg);
void set_effect_hue_span(float deg);
void set_flash_fade(float seconds);
protected:
void render_();
void apply_colors_();
void update_effect_(uint32_t now_ms);
void recompute_axis_();
void clear_positions_();
void write_digit_(uint8_t block, char c);
void write_pos_(uint8_t block, uint8_t seg, bool on);
void draw_number_(int value, char unit);
static bool scan_tick_(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata,
void *arg);
void send_pair_(uint16_t ss1, uint16_t ss2, uint8_t cs, uint8_t is);
InternalGPIOPin *clk_{nullptr};
InternalGPIOPin *data_{nullptr};
InternalGPIOPin *clk2_{nullptr};
InternalGPIOPin *data2_{nullptr};
time::RealTimeClock *time_{nullptr};
// Port bit masks for the four pins. A frame goes out as direct register
// stores with both buses clocked together, which takes 6.4us against 28.0us
// for two passes through ISRInternalGPIOPin. All four pins have to live
// below GPIO32 for this, which __init__.py enforces at config time.
uint32_t clk_mask_{0}, data_mask_{0}, clk2_mask_{0}, data2_mask_{0};
uint8_t max_current_{15};
bool twelve_hour_{true};
bool blink_colon_{true};
bool online_{false};
// Which positions are lit, before color is applied.
bool on_[4][9]{}; // [block][segment], segments A..G then annunciator, annunciator 2
bool enabled_{false};
// [block][segment][channel], 0 to COLOR_LEVELS - 1, index by Channel.
uint8_t level_[4][9][3]{};
uint8_t requested_current_{15};
// Color before it is quantized, in three tiers. A position with pos_set_
// wins, then a block with digit_set_, then the master light's base_rgb_.
float base_rgb_[3]{1.0f, 1.0f, 1.0f};
float digit_rgb_[4][3]{};
bool digit_set_[4]{};
float pos_rgb_[4][9][3]{};
bool pos_set_[4][9]{};
// Scales every color on its way to a duty level. The flash effect drives
// it and nothing else touches it, so it stays at 1 the rest of the time.
float envelope_{1.0f};
Effect effect_{Effect::NONE};
Spread spread_{Spread::PANEL};
float effect_speed_{10.0f}; // seconds for one full cycle
float effect_angle_{0.0f};
// How much of the color wheel the panel covers end to end. A full turn on
// four digits packs the whole spectrum into a hand span and reads as
// noise, so the useful settings are narrow, a slice rather than the lot.
float hue_span_{90.0f};
// Seconds each flash transition takes. Zero snaps.
float flash_fade_{0.0f};
uint32_t effect_t0_{0};
uint32_t effect_at_{0};
// Where each position sits along the effect axis, 0 to 1, recomputed only
// when the angle changes rather than every frame.
float axis_pos_[4][9]{};
float axis_blk_[4]{};
ScanBuf buf_[2]{};
volatile uint8_t front_{0};
volatile uint8_t step_{0};
volatile uint8_t wait_{0}; // ticks left before the next step is latched
Mode mode_{Mode::TIME};
uint32_t mode_until_{0};
uint8_t lamp_current_{0};
int number_{0};
char unit_{'\0'};
int last_key_{-1}; // whatever the current mode reduces its content to
bool last_colon_{false};
bool dirty_{true};
};
class Aip33628Light : public light::LightOutput {
public:
void set_panel(Aip33628Panel *panel) { panel_ = panel; }
light::LightTraits get_traits() override {
auto traits = light::LightTraits();
traits.set_supported_color_modes({light::ColorMode::RGB});
return traits;
}
void write_state(light::LightState *state) override {
auto v = state->current_values;
// Color ratio comes from the raw components, which ESPHome has already
// normalized so the largest is 1. Magnitude comes through the helper
// rather than v.get_brightness(), because only the helper carries the
// transition state, without which a fade never moves. Both arrive linear,
// since gamma lives in the component.
float bright;
state->current_values_as_brightness(&bright);
panel_->set_light(v.is_on(), v.get_red(), v.get_green(), v.get_blue(), bright);
}
protected:
Aip33628Panel *panel_{nullptr};
};
} // namespace aip33628
} // namespace esphome
-27
View File
@@ -1,27 +0,0 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import light
from esphome.const import CONF_OUTPUT_ID
from . import Aip33628Panel, aip33628_ns
DEPENDENCIES = ["aip33628"]
Aip33628Light = aip33628_ns.class_("Aip33628Light", light.LightOutput)
CONF_AIP33628_ID = "aip33628_id"
CONFIG_SCHEMA = light.RGB_LIGHT_SCHEMA.extend(
{
cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(Aip33628Light),
cv.GenerateID(CONF_AIP33628_ID): cv.use_id(Aip33628Panel),
}
).extend(cv.COMPONENT_SCHEMA)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_OUTPUT_ID])
await light.register_light(var, config)
panel = await cg.get_variable(config[CONF_AIP33628_ID])
cg.add(var.set_panel(panel))
@@ -1,162 +0,0 @@
# Office air quality web page
Local external component for **ESPHome 2026.10.2, ESP32 with ESP-IDF**. No remote
libraries, standard `web_server`, entity enumeration, SSE, OTA, configuration,
or authentication. Only the three explicitly referenced sensor states and their
10-hour air-quality history are published. Other device services are not secured by this component. The
optional mDNS hostname override affects the device-wide mDNS responder.
## Integration (in the parent configuration)
For a YAML file located in `esphome/`:
```yaml
external_components:
- source:
type: local
path: components
components: [air_quality_web]
mdns:
disabled: false
services:
- service: _http
protocol: _tcp
port: 8080
air_quality_web:
port: 8080
mdns_hostname: office3 # Optional device-wide mDNS hostname override
co2: scd30_co2
temperature: scd30_temperature
humidity: scd30_humidity
```
Merge with existing `external_components` if present. All three sensor references
are required; their units should be ppm, °C, and % respectively. The default port
is 8080. Port 0, port 80 (fallback captive portal), and port 32768 (the standard
IDF server's control port) are rejected. Avoid conflicts with other TCP/UDP
services. Merge the explicit `mdns: disabled: false` and `_http._tcp` service on
port 8080 into the parent YAML; the component does not register that service.
### Optional mDNS hostname override
`mdns_hostname` is validated with ESPHome's `cv.hostname`. When omitted, this
component does not change the mDNS hostname. When set to `office3`, it calls the
native `mdns_hostname_set` after ESPHome's mDNS setup, using setup priority
`AFTER_CONNECTION - 1`, so the page is reachable at `http://office3.local:8080/`.
Failures are logged with the requested hostname and native error; the HTTP
listener still starts and can be reached by IP.
This is a **hostname override, not an alias**: it replaces the device-wide mDNS
hostname, including the hostname targeted by other advertised services. The old
`.local` hostname is not retained as an additional name. Only the mDNS hostname
changes: `App`/ESPHome device name, entity identity, and mDNS service instance
names are unchanged. The component requires ESPHome's `mdns` dependency and
uses its native mDNS library; it does not initialize a second responder.
## Public interface
* Exact `GET /`: self-contained German page; no external assets or requests.
* Exact `GET /api/air-quality`: JSON with **exactly** `co2`, `temperature`,
`humidity`, each a finite number or `null`. Example:
`{"co2":850,"temperature":22.5,"humidity":46}`.
* Exact `GET /api/air-quality/history`: JSON containing `duration_seconds: 36000`
and `samples`, ordered oldest first. Each sample is
`[age_seconds, co2, temperature, humidity]`, with nonnegative ages relative to
the response snapshot and finite values or `null`. Only samples within the
last 10 hours are returned; there are at most 601 samples.
* Non-GET methods on those paths: 405 with `Allow: GET`.
* All other paths: 404, including `/events`, `/update`, `/config`, general sensor
APIs, trailing slashes, encoded aliases, and query-string variants. No body
parsing or upload handlers. HTTP parser errors can still be rejected by IDF
before application routing.
The browser refreshes live readings approximately every five seconds and history
approximately every minute, using one sequential request loop and a separate
4-second timeout for each request. Missing live measurements show dashes. A live
request failure clears the live cards; a history failure retains previously
loaded history with a stale/unavailable warning, without clearing healthy live
cards. CO₂ is orange **only above** 1200 ppm and red **only above** 1600 ppm;
text accompanies the colors.
Three separate responsive charts show CO₂ (ppm), temperature (°C), and relative
humidity (%) on a fixed −10 h to now axis, with independent automatic Y scales.
Missing values and timestamp gaps over 90 seconds break the traces. Partial
history is not stretched across the time axis or extrapolated to the present.
CO₂ guides at 1200 and 1600 ppm appear when within the chart's value range.
The device records one sample every 60 seconds, independently of browser, VPN,
or Home Assistant connections. History is kept only in RAM and starts empty
following reboot; firmware updates therefore also clear it. There are no flash
writes for history. Delayed sampling is represented by actual timestamps, not
fabricated catch-up samples.
## Isolation, security, and resource use
This is intentionally public, unauthenticated **HTTP**, not HTTPS. Anyone who can
reach this port can read the three measurements. Restrict network exposure as
appropriate; do not forward the device's other ports alongside it. There is no
CORS permission, no credentials in fetches, and no general entity API.
Responses include `Cache-Control: no-store, max-age=0`, `Pragma: no-cache`,
`nosniff`, frame denial, no-referrer, a restrictive Permissions Policy and CSP.
CSP permits the fixed inline script/style needed for this single-file page and
same-origin fetches only. It denies forms, framing, and other resource types.
These headers apply to application errors too; they do not alter portal headers.
A standalone `AsyncWebServer` subclass uses the ESPHome `web_server_base` header
and its automatically loaded `web_server_idf` dependency. It never accesses
`global_web_server_base`, registers shared handlers, or changes `DefaultHeaders`.
Its small startup override is needed because stock `AsyncWebServer::begin()`
uses a fixed UDP control port (incompatible with a second server) and generic
POST parsing. The new listener uses UDP control on its own port number and a
single all-method dispatcher, rejecting unsupported requests before body reads.
The fallback captive portal remains independently on port 80.
Socket accounting registers one TCP listener, three TCP clients, and two UDP
sockets (IDF 5.5.6's `ctrl_fd` and `msg_fd`): six sockets total, using ESPHome's
`socket.consume_sockets` validators. IDF allows at most three client connections,
with LRU eviction. Its HTTP task stack is 4512 bytes. The page lives as a constant
in flash and is sent directly, not copied into a per-request string. IDF task,
control/session structures and socket buffers require additional RAM; exact use
depends on the parent build. This is a modest LAN status page, not a hardened
high-concurrency Internet server.
Every application response, including HTML, JSON, 404 and 405, sends
`Connection: close`. A shared helper sends the response, then calls
`shutdown(fd, SHUT_RD)` to terminate further receives, then queues
`httpd_sess_trigger_close`. Queued closure alone is insufficient: IDF first
synchronously drains unread `Content-Length` during request cleanup. Receive
shutdown prevents that cleanup from waiting for a slow or incomplete body;
already-buffered bytes are finite, and the component performs no body receive
loop. Shutdown leaves the send direction intact. Normal responses return
`ESP_OK`, avoiding IDF's per-poll "uri handler execution failed" warning. Actual
send, receive-shutdown, or close-queue failures return an error so IDF discards
the session; shutdown and queue failures are logged. This does not eliminate
IDF's own timeouts for receiving headers or sending responses.
A fixed 1-second `PollingComponent` serializes only the three configured sensors
on the main loop. A mutex protects replacement and copying of the cached JSON;
HTTP sends happen after releasing it. The HTTP task never reads live sensors or
the entity registry. The history ring uses 601 compact 16-byte samples (9,616
bytes), plus small bookkeeping fields. Each history request allocates a bounded
heap snapshot of approximately the same size, then streams JSON in chunks of at
most 512 bytes; the ring is not copied onto the small HTTP task stack and no
whole-response JSON string is allocated. Allocation failure returns 503, and
send failures close the connection. Sample ages use rollover-safe uptime
arithmetic and old samples are pruned on the main loop. Uninitialized, missing, NaN and infinite states become
`null`. Sensor expiry stays with the parent configuration's existing filters
(e.g. `timeout: 30s`); this component adds no independent sample-age policy.
## Validation
APIs were inspected against installed ESPHome 2026.10.2 and local ESP-IDF headers.
Host checks cover schema/socket registration and codegen, C++ routing/serialization
with API stand-ins (including send/shutdown/close ordering and close-queue
failures, history retention/wraparound, uptime rollover, allocation failures, and
chunked-send failures), and the embedded JavaScript (threshold boundaries,
missing and offline states, chart bounds/gaps, timeout and sequential polling).
These are not a firmware or
on-device integration test. The parent integration must build and check both
listeners on hardware, including captive portal operation while Wi-Fi is down.
@@ -1,49 +0,0 @@
"""Isolated, public, read-only office air quality server (ESP32 ESP-IDF)."""
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor, socket
from esphome.const import CONF_ID, CONF_PORT, Framework
DEPENDENCIES = ["esp32", "network", "mdns"]
AUTO_LOAD = ["web_server_base", "socket"]
ns = cg.esphome_ns.namespace("air_quality_web")
AirQualityWeb = ns.class_("AirQualityWeb", cg.PollingComponent)
def validate_port(value):
value = cv.port(value)
if value in (0, 80, 32768):
raise cv.Invalid("Choose a nonzero port other than 80 or 32768 (captive portal/control socket)")
return value
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(AirQualityWeb),
cv.Optional(CONF_PORT, default=8080): validate_port,
cv.Optional("mdns_hostname"): cv.hostname,
cv.Required("co2"): cv.use_id(sensor.Sensor),
cv.Required("temperature"): cv.use_id(sensor.Sensor),
cv.Required("humidity"): cv.use_id(sensor.Sensor),
}
).extend(cv.COMPONENT_SCHEMA),
cv.only_on_esp32,
cv.only_with_framework(Framework.ESP_IDF),
socket.consume_sockets(1, "air_quality_web", socket.SocketType.TCP_LISTEN),
socket.consume_sockets(3, "air_quality_web", socket.SocketType.TCP),
socket.consume_sockets(2, "air_quality_web", socket.SocketType.UDP),
)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
cg.add(var.set_port(config[CONF_PORT]))
if "mdns_hostname" in config:
cg.add(var.set_mdns_hostname(config["mdns_hostname"]))
for key in ("co2", "temperature", "humidity"):
ref = await cg.get_variable(config[key])
cg.add(getattr(var, f"set_{key}_sensor")(ref))
@@ -1,232 +0,0 @@
#include "air_quality_web.h"
#include "page.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#include <mdns.h>
#include <lwip/sockets.h>
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <utility>
#include <memory>
#include <new>
namespace esphome::air_quality_web {
static const char *const TAG = "air_quality_web";
static esp_err_t close_response(httpd_req_t *request, esp_err_t send_err) {
const int fd = httpd_req_to_sockfd(request);
// IDF drains unread Content-Length synchronously before processing queued work.
// Stop receive first so cleanup cannot wait for a slow/incomplete request body.
const int shutdown_result = shutdown(fd, SHUT_RD);
if (shutdown_result != 0)
ESP_LOGW(TAG, "Cannot shut down HTTP receive on socket %d: errno %d", fd, errno);
const esp_err_t close_err = httpd_sess_trigger_close(request->handle, fd);
if (close_err != ESP_OK)
ESP_LOGW(TAG, "Cannot queue HTTP session closure on socket %d: %s", fd, esp_err_to_name(close_err));
if (send_err != ESP_OK)
return send_err;
// Normal polls must succeed; failures make IDF discard the session directly.
return shutdown_result == 0 && close_err == ESP_OK ? ESP_OK : ESP_FAIL;
}
static esp_err_t send_and_close(httpd_req_t *request, const char *content, ssize_t length) {
return close_response(request, httpd_resp_send(request, content, length));
}
esp_err_t AirQualityServer::start(esp_err_t (*handler)(httpd_req_t *), void *context) {
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.stack_size = 4512;
config.server_port = this->port_;
// UDP and TCP may share a port number. Avoid the portal's default UDP 32768.
config.ctrl_port = this->port_;
config.max_open_sockets = 3;
config.max_uri_handlers = 1;
config.max_resp_headers = 12;
config.lru_purge_enable = true;
config.close_fn = AsyncWebServer::safe_close_with_shutdown;
config.uri_match_fn = [](const char *, const char *, size_t) { return true; };
esp_err_t err = httpd_start(&this->server_, &config);
if (err != ESP_OK)
return err;
httpd_uri_t route{};
route.uri = "*";
route.method = static_cast<httpd_method_t>(HTTP_ANY);
route.handler = handler;
route.user_ctx = context;
err = httpd_register_uri_handler(this->server_, &route);
if (err != ESP_OK)
this->end();
return err;
}
void AirQualityWeb::setup() {
// ESPHome mDNS initializes at AFTER_CONNECTION, before this component.
if (!this->mdns_hostname_.empty()) {
const esp_err_t err = mdns_hostname_set(this->mdns_hostname_.c_str());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Cannot override mDNS hostname to '%s': %s; ensure mDNS is enabled and initialized",
this->mdns_hostname_.c_str(), esp_err_to_name(err));
} else {
ESP_LOGI(TAG, "mDNS hostname overridden to '%s.local'", this->mdns_hostname_.c_str());
}
}
this->update();
const esp_err_t err = this->server_.start(handle_request_, this);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Cannot start air quality listener: %s", esp_err_to_name(err));
this->mark_failed();
}
}
// Only called on the main loop; never dereference a Sensor in the HTTP task.
static float sensor_value(sensor::Sensor *sensor) {
if (sensor == nullptr || !sensor->has_state() || !std::isfinite(sensor->state))
return NAN;
return sensor->state;
}
static void format_value(char *buffer, size_t size, float value) {
// Nine significant digits cover a float, even at its finite extrema.
if (std::isfinite(value))
snprintf(buffer, size, "%.9g", static_cast<double>(value));
else
snprintf(buffer, size, "null");
}
static std::string sensor_json(float value) {
char buffer[32];
format_value(buffer, sizeof(buffer), value);
return buffer;
}
void AirQualityWeb::update() {
const float co2 = sensor_value(this->co2_);
const float temperature = sensor_value(this->temperature_);
const float humidity = sensor_value(this->humidity_);
std::string next = "{\"co2\":" + sensor_json(co2) +
",\"temperature\":" + sensor_json(temperature) +
",\"humidity\":" + sensor_json(humidity) + "}";
LockGuard lock(this->snapshot_mutex_);
const uint32_t now = millis();
this->json_ = std::move(next);
// Prune on the main loop too, so old entries cannot reappear after millis wraps.
while (this->history_count_ != 0 &&
uint32_t(now - this->history_[this->history_head_].timestamp) > HISTORY_DURATION_MS) {
this->history_head_ = (this->history_head_ + 1) % HISTORY_CAPACITY;
--this->history_count_;
}
if (!this->has_sample_ || uint32_t(now - this->last_sample_ms_) >= HISTORY_INTERVAL_MS) {
// Delayed updates produce a gap, never fabricated catch-up samples.
if (this->history_count_ == HISTORY_CAPACITY) {
this->history_head_ = (this->history_head_ + 1) % HISTORY_CAPACITY;
--this->history_count_;
}
const size_t index = (this->history_head_ + this->history_count_) % HISTORY_CAPACITY;
this->history_[index] = {now, co2, temperature, humidity};
++this->history_count_;
this->last_sample_ms_ = now;
this->has_sample_ = true;
}
}
std::string AirQualityWeb::snapshot_() {
LockGuard lock(this->snapshot_mutex_);
return this->json_;
}
esp_err_t AirQualityWeb::send_history_(httpd_req_t *request) {
// The HTTP task has only 4512 bytes of stack; keep the bounded copy on the heap.
std::unique_ptr<HistorySnapshot> snapshot(new (std::nothrow) HistorySnapshot);
if (!snapshot) {
httpd_resp_set_status(request, "503 Service Unavailable");
httpd_resp_set_type(request, "text/plain; charset=utf-8");
return send_and_close(request, "Service Unavailable\n", HTTPD_RESP_USE_STRLEN);
}
{
LockGuard lock(this->snapshot_mutex_);
snapshot->timestamp = millis();
snapshot->count = 0;
for (size_t i = 0; i < this->history_count_; ++i) {
const auto &sample = this->history_[(this->history_head_ + i) % HISTORY_CAPACITY];
if (uint32_t(snapshot->timestamp - sample.timestamp) <= HISTORY_DURATION_MS)
snapshot->samples[snapshot->count++] = sample;
}
}
char chunk[512];
size_t used = snprintf(chunk, sizeof(chunk), "{\"duration_seconds\":36000,\"samples\":[");
for (size_t i = 0; i < snapshot->count; ++i) {
const auto &sample = snapshot->samples[i];
char co2[32], temperature[32], humidity[32], row[128];
format_value(co2, sizeof(co2), sample.co2);
format_value(temperature, sizeof(temperature), sample.temperature);
format_value(humidity, sizeof(humidity), sample.humidity);
const size_t length = snprintf(row, sizeof(row), "%s[%lu,%s,%s,%s]", i == 0 ? "" : ",",
static_cast<unsigned long>(uint32_t(snapshot->timestamp - sample.timestamp) / 1000),
co2, temperature, humidity);
if (used + length > sizeof(chunk)) {
const esp_err_t err = httpd_resp_send_chunk(request, chunk, used);
if (err != ESP_OK)
return close_response(request, err);
used = 0;
}
memcpy(chunk + used, row, length);
used += length;
}
if (used + 2 > sizeof(chunk)) {
const esp_err_t err = httpd_resp_send_chunk(request, chunk, used);
if (err != ESP_OK)
return close_response(request, err);
used = 0;
}
memcpy(chunk + used, "]}", 2);
const esp_err_t err = httpd_resp_send_chunk(request, chunk, used + 2);
if (err != ESP_OK)
return close_response(request, err);
return close_response(request, httpd_resp_send_chunk(request, nullptr, 0));
}
esp_err_t AirQualityWeb::handle_request_(httpd_req_t *request) {
// Raw exact paths: no decoding, prefix matching or redirects into other APIs.
const bool page = strcmp(request->uri, "/") == 0;
const bool api = strcmp(request->uri, "/api/air-quality") == 0;
const bool history = strcmp(request->uri, "/api/air-quality/history") == 0;
const bool known = page || api || history;
const bool allowed = request->method == HTTP_GET;
httpd_resp_set_hdr(request, "Cache-Control", "no-store, max-age=0");
httpd_resp_set_hdr(request, "Pragma", "no-cache");
httpd_resp_set_hdr(request, "X-Content-Type-Options", "nosniff");
httpd_resp_set_hdr(request, "X-Frame-Options", "DENY");
httpd_resp_set_hdr(request, "Referrer-Policy", "no-referrer");
httpd_resp_set_hdr(request, "Permissions-Policy", "camera=(), microphone=(), geolocation=()");
httpd_resp_set_hdr(request, "Content-Security-Policy",
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
"connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'");
// Receive shutdown and queued session closure below enforce this server-side.
httpd_resp_set_hdr(request, "Connection", "close");
if (!known || !allowed) {
httpd_resp_set_status(request, known ? "405 Method Not Allowed" : "404 Not Found");
if (known)
httpd_resp_set_hdr(request, "Allow", "GET");
httpd_resp_set_type(request, "text/plain; charset=utf-8");
return send_and_close(request, known ? "Method Not Allowed\n" : "Not Found\n", HTTPD_RESP_USE_STRLEN);
}
if (page) {
httpd_resp_set_type(request, "text/html; charset=utf-8");
return send_and_close(request, PAGE, sizeof(PAGE) - 1);
}
httpd_resp_set_type(request, "application/json");
auto *component = static_cast<AirQualityWeb *>(request->user_ctx);
if (history)
return component->send_history_(request);
// Release the mutex before the potentially blocking network send.
const std::string json = component->snapshot_();
return send_and_close(request, json.data(), json.size());
}
} // namespace esphome::air_quality_web
@@ -1,71 +0,0 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/web_server_base/web_server_base.h"
#include <cstddef>
#include <cstdint>
#include <string>
namespace esphome::air_quality_web {
// Separate IDF listener: do not use WebServerBase or its global instance/headers.
// The stock begin() has a shared control port and generic POST body processing.
class AirQualityServer : public AsyncWebServer {
public:
AirQualityServer() : AsyncWebServer(8080) {}
void set_port(uint16_t port) { this->port_ = port; }
esp_err_t start(esp_err_t (*handler)(httpd_req_t *), void *context);
};
class AirQualityWeb : public PollingComponent {
public:
AirQualityWeb() : PollingComponent(1000) {}
void set_port(uint16_t port) { this->server_.set_port(port); }
void set_mdns_hostname(const std::string &hostname) { this->mdns_hostname_ = hostname; }
void set_co2_sensor(sensor::Sensor *value) { this->co2_ = value; }
void set_temperature_sensor(sensor::Sensor *value) { this->temperature_ = value; }
void set_humidity_sensor(sensor::Sensor *value) { this->humidity_ = value; }
void setup() override;
void update() override;
void on_shutdown() override { this->server_.end(); }
float get_setup_priority() const override { return setup_priority::AFTER_CONNECTION - 1.0f; }
protected:
static esp_err_t handle_request_(httpd_req_t *request);
std::string snapshot_();
esp_err_t send_history_(httpd_req_t *request);
static constexpr uint32_t HISTORY_DURATION_MS = 36000000;
static constexpr uint32_t HISTORY_INTERVAL_MS = 60000;
static constexpr size_t HISTORY_CAPACITY = 601;
struct HistorySample {
uint32_t timestamp;
float co2;
float temperature;
float humidity;
};
static_assert(sizeof(HistorySample) == 16, "History samples must remain compact");
struct HistorySnapshot {
uint32_t timestamp;
size_t count;
HistorySample samples[HISTORY_CAPACITY];
};
AirQualityServer server_;
std::string mdns_hostname_;
sensor::Sensor *co2_{nullptr};
sensor::Sensor *temperature_{nullptr};
sensor::Sensor *humidity_{nullptr};
Mutex snapshot_mutex_;
HistorySample history_[HISTORY_CAPACITY]{};
size_t history_head_{0};
size_t history_count_{0};
uint32_t last_sample_ms_{0};
bool has_sample_{false};
std::string json_{"{\"co2\":null,\"temperature\":null,\"humidity\":null}"};
};
} // namespace esphome::air_quality_web
-236
View File
@@ -1,236 +0,0 @@
#pragma once
namespace esphome::air_quality_web {
static constexpr char PAGE[] = R"AQPAGE(<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Luftqualität im Büro</title>
<style>
:root{font-family:system-ui,sans-serif;color-scheme:light dark;background:#f1f5f9;color:#17212f}
*{box-sizing:border-box}body{margin:0;padding:clamp(1rem,5vw,3rem)}main{max-width:58rem;margin:auto}
h1{font-size:clamp(1.7rem,5vw,2.6rem);margin-bottom:.5rem}.intro,footer{color:#526173}
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(14rem,1fr));gap:1rem;margin:2rem 0}
article{background:#fff;border:2px solid #b4c2d1;border-radius:1rem;padding:1.5rem;min-width:0}
h2{font-size:1.1rem;margin:0 0 1rem}.value{font-size:clamp(2.2rem,6vw,3.6rem);font-weight:700;font-variant-numeric:tabular-nums}
.unit{font-size:1.1rem;font-weight:400}.hint{min-height:1.5em;margin-bottom:0}
article.good{border-color:#15803d}article.orange{border-color:#c05a00;background:#fff4df}article.red{border-color:#c52b2b;background:#ffeded}
#status{font-weight:600}footer{font-size:.9rem;line-height:1.6}
.history{display:grid;gap:1rem;margin:1rem 0 2rem}.history article{padding:1rem}
.history h3{font-size:1.1rem;margin:0 0 .5rem}.legend{font-size:.9rem;color:#526173;margin:0 0 .5rem}
canvas{display:block;width:100%;height:15rem}#history-status{line-height:1.5}
@media(prefers-color-scheme:dark){.legend{color:#b1c0d1}}
@media(prefers-color-scheme:dark){:root{background:#101923;color:#eef3fa}article{background:#1b2837}.intro,footer{color:#b1c0d1}article.orange{background:#402a13;border-color:#ffae4a}article.red{background:#401b21;border-color:#ff7979}}
</style>
</head>
<body><main>
<h1>Luftqualität im Büro</h1>
<p class="intro">Aktuelle Messwerte · Aktualisierung alle 5 Sekunden</p>
<p id="status" role="status" aria-live="polite">Verbindung wird hergestellt …</p>
<div class="grid">
<article id="co2-card"><h2>CO₂</h2><div class="value"><span id="co2">—</span> <span class="unit">ppm</span></div><p class="hint" id="co2-hint">Keine Messdaten</p></article>
<article><h2>Temperatur</h2><div class="value"><span id="temperature">—</span> <span class="unit">°C</span></div><p class="hint" id="temperature-hint">Keine Messdaten</p></article>
<article><h2>Feuchtigkeit</h2><div class="value"><span id="humidity">—</span> <span class="unit">%</span></div><p class="hint" id="humidity-hint">Keine Messdaten</p></article>
</div>
<section aria-labelledby="history-title">
<h2 id="history-title">Verlauf · letzte 10 Stunden</h2>
<p id="history-status" role="status" aria-live="polite">Verlauf wird geladen …</p>
<div class="history">
<article><h3>CO₂</h3><p class="legend">CO₂ in ppm · Hilfslinien bei 1200 / 1600 ppm, sofern im Wertebereich</p><canvas id="co2-chart" role="img" aria-label="CO₂ in ppm über die letzten 10 Stunden">CO₂-Verlauf in ppm</canvas></article>
<article><h3>Temperatur</h3><p class="legend">Temperatur in °C</p><canvas id="temperature-chart" role="img" aria-label="Temperatur in Grad Celsius über die letzten 10 Stunden">Temperaturverlauf in °C</canvas></article>
<article><h3>Feuchtigkeit</h3><p class="legend">Relative Feuchtigkeit in %</p><canvas id="humidity-chart" role="img" aria-label="Relative Feuchtigkeit in Prozent über die letzten 10 Stunden">Feuchtigkeitsverlauf in %</canvas></article>
</div>
</section>
<footer>CO₂: Orange bei mehr als 1200 ppm, Rot bei mehr als 1600 ppm.<br>Verlauf: eine Messung pro Minute, maximal 10 Stunden. Speicherung nur im RAM des Geräts; bei einem Neustart geht der Verlauf verloren. Lücken bedeuten fehlende Messdaten. Aktualisierung etwa jede Minute.</footer>
<noscript>Bitte JavaScript aktivieren, um die Messwerte und den Verlauf anzuzeigen.</noscript>
</main>
<script>
'use strict';
const keys = ['co2', 'temperature', 'humidity'];
const status = document.getElementById('status');
const card = document.getElementById('co2-card');
const formats = [0, 1, 1].map(d => new Intl.NumberFormat('de-DE', {minimumFractionDigits:d, maximumFractionDigits:d}));
function render(data) {
let available = 0;
keys.forEach((key, i) => {
const value = data[key];
const valid = typeof value === 'number' && Number.isFinite(value);
document.getElementById(key).textContent = valid ? formats[i].format(value) : '—';
document.getElementById(key + '-hint').textContent = valid ? 'Aktueller Messwert' : 'Keine Messdaten';
if (valid) available++;
});
const co2 = data.co2;
const valid = typeof co2 === 'number' && Number.isFinite(co2);
card.className = valid ? (co2 > 1600 ? 'red' : co2 > 1200 ? 'orange' : 'good') : '';
if (valid) document.getElementById('co2-hint').textContent = co2 > 1600 ? 'Bitte lüften – CO₂ sehr hoch' : co2 > 1200 ? 'Lüften empfohlen – CO₂ erhöht' : 'CO₂ im grünen Bereich';
return available;
}
const duration = 36000;
const historyStatus = document.getElementById('history-status');
const canvases = keys.map(key => document.getElementById(key + '-chart'));
const units = ['ppm', '°C', '%'];
let history = null;
let historyFailed = false;
let nextHistory = 0;
function drawHistory() {
const elapsed = history ? Math.max(0, (performance.now() - history.loadedAt) / 1000) : 0;
if (history) {
const last = 'Zuletzt aktualisiert: ' + history.loadedLabel;
historyStatus.textContent = historyFailed || elapsed > 90
? 'Verlauf derzeit nicht aktuell / nicht verfügbar · ' + last + ' · zwischengespeicherte Daten'
: last + ' · ' + (history.samples.length ? 'Zeitfenster: −10 h bis Jetzt' : 'Noch keine Messdaten seit Gerätestart');
} else {
historyStatus.textContent = historyFailed ? 'Verlauf nicht verfügbar · erneuter Versuch in etwa 15 Sekunden' : 'Verlauf wird geladen …';
}
const dark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const ink = dark ? '#b1c0d1' : '#526173';
const grid = dark ? '#415267' : '#d8e0e9';
const colors = dark ? ['#77c9ff', '#ffbd74', '#7edcc5'] : ['#0369a1', '#a64b00', '#087f6b'];
canvases.forEach((canvas, index) => {
const width = canvas.getBoundingClientRect().width;
const height = canvas.getBoundingClientRect().height;
if (!width || !height) return;
const ratio = window.devicePixelRatio || 1;
canvas.width = Math.round(width * ratio);
canvas.height = Math.round(height * ratio);
const ctx = canvas.getContext('2d');
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
ctx.clearRect(0, 0, width, height);
ctx.font = '12px system-ui, sans-serif';
const samples = history ? history.samples.filter(s => s[0] + elapsed <= duration) : [];
const values = samples.map(s => s[index + 1]).filter(Number.isFinite);
let low = values.length ? Math.min(...values) : 0;
let high = values.length ? Math.max(...values) : 1;
const padding = Math.max((high - low) * .1, Math.abs(low) * .02, [20, .5, 1][index]);
low -= padding;
high += padding;
const ticks = Array.from({length:5}, (_, n) => high - (high - low) * n / 4);
const left = Math.max(48, ...ticks.map(v => ctx.measureText(formats[index].format(v)).width + 12));
const right = width - 20, top = 20, bottom = height - 34;
const x = age => left + (1 - (age + elapsed) / duration) * (right - left);
const y = value => bottom - (value - low) / (high - low) * (bottom - top);
ctx.lineWidth = 1;
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
ticks.forEach(value => {
ctx.strokeStyle = grid;
ctx.beginPath(); ctx.moveTo(left, y(value)); ctx.lineTo(right, y(value)); ctx.stroke();
ctx.fillStyle = ink;
ctx.fillText(formats[index].format(value), left - 8, y(value));
});
ctx.textBaseline = 'top';
for (let hour = 0; hour <= 10; hour += 2) {
const px = left + hour / 10 * (right - left);
ctx.strokeStyle = grid;
ctx.beginPath(); ctx.moveTo(px, top); ctx.lineTo(px, bottom); ctx.stroke();
ctx.fillStyle = ink;
ctx.textAlign = hour === 0 ? 'left' : hour === 10 ? 'right' : 'center';
ctx.fillText(hour === 10 ? 'Jetzt' : '−' + (10 - hour) + ' h', px, bottom + 10);
}
ctx.textAlign = 'left';
ctx.fillStyle = ink;
ctx.fillText(units[index], left, 0);
if (index === 0) {
[1200, 1600].forEach((limit, i) => {
if (limit < low || limit > high) return;
ctx.strokeStyle = i ? '#c52b2b' : '#c05a00';
ctx.setLineDash([5, 4]);
ctx.beginPath(); ctx.moveTo(left, y(limit)); ctx.lineTo(right, y(limit)); ctx.stroke();
});
ctx.setLineDash([]);
}
ctx.strokeStyle = colors[index];
ctx.fillStyle = colors[index];
ctx.lineWidth = 2;
ctx.beginPath();
let previous = null;
samples.forEach(sample => {
const value = sample[index + 1];
if (!Number.isFinite(value)) { previous = null; return; }
if (previous && previous[0] - sample[0] <= 90) ctx.lineTo(x(sample[0]), y(value));
else ctx.moveTo(x(sample[0]), y(value));
previous = sample;
});
ctx.stroke();
// Dots also make isolated samples visible without inventing a line to "now".
ctx.beginPath();
samples.forEach(sample => {
if (!Number.isFinite(sample[index + 1])) return;
const px = x(sample[0]), py = y(sample[index + 1]);
ctx.moveTo(px + 1.8, py); ctx.arc(px, py, 1.8, 0, Math.PI * 2);
});
ctx.fill();
if (!values.length) {
ctx.fillStyle = ink;
ctx.textAlign = 'center';
ctx.fillText(history ? 'Keine Messdaten im Zeitfenster' : 'Verlauf nicht verfügbar', (left + right) / 2, (top + bottom) / 2);
}
});
}
async function getJSON(path) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 4000);
try {
const response = await fetch(path, {cache:'no-store', credentials:'omit', redirect:'error', signal:controller.signal});
if (!response.ok) throw new Error('HTTP');
return await response.json();
} finally {
clearTimeout(timeout);
}
}
async function loadLive() {
try {
const data = await getJSON('/api/air-quality');
if (!data || Object.keys(data).length !== 3 || !keys.every(k => Object.hasOwn(data,k) && (data[k] === null || (typeof data[k] === 'number' && Number.isFinite(data[k]))))) throw new Error('Datenformat');
const count = render(data);
status.textContent = count === 3 ? 'Online · Messwerte aktuell' : count === 0 ? 'Online · Noch keine Messdaten' : 'Online · Einzelne Messwerte fehlen';
} catch (_) {
render({co2:null, temperature:null, humidity:null});
status.textContent = 'Offline · Keine Verbindung – erneuter Versuch in 5 Sekunden';
}
}
async function loadHistory() {
try {
const data = await getJSON('/api/air-quality/history');
if (!data || data.duration_seconds !== duration || !Array.isArray(data.samples) || data.samples.length > 601) throw new Error('Datenformat');
let previousAge = duration;
const samples = data.samples.map(sample => {
if (!Array.isArray(sample) || sample.length !== 4 || !Number.isFinite(sample[0]) || sample[0] < 0 || sample[0] > previousAge ||
!sample.slice(1).every(v => v === null || typeof v === 'number')) throw new Error('Datenformat');
previousAge = sample[0];
return [sample[0], ...sample.slice(1).map(v => Number.isFinite(v) ? v : null)];
});
history = {samples, loadedAt:performance.now(), loadedLabel:new Date().toLocaleTimeString('de-DE')};
historyFailed = false;
nextHistory = performance.now() + 60000;
} catch (_) {
// Keep previous samples, but never describe a failed refresh as current.
historyFailed = true;
nextHistory = performance.now() + 15000;
}
}
async function poll() {
await loadLive();
const nextLive = performance.now() + 5000;
// One shared loop serializes both endpoints, each with its own abort timer.
if (performance.now() >= nextHistory) await loadHistory();
drawHistory();
setTimeout(poll, Math.max(0, nextLive - performance.now()));
}
window.addEventListener('resize', drawHistory);
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', drawHistory);
poll();
</script>
</body>
</html>)AQPAGE";
} // namespace esphome::air_quality_web
@@ -1,50 +0,0 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import binary_sensor, i2c, sensor
from esphome.const import CONF_ID, ENTITY_CATEGORY_DIAGNOSTIC
DEPENDENCIES = ["i2c"]
AUTO_LOAD = ["sensor", "binary_sensor"]
ns = cg.esphome_ns.namespace("luxe_ip5306")
LuxeIP5306 = ns.class_("LuxeIP5306", cg.PollingComponent, i2c.I2CDevice)
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(LuxeIP5306),
cv.Required("available"): binary_sensor.binary_sensor_schema(
device_class="connectivity", entity_category=ENTITY_CATEGORY_DIAGNOSTIC
),
cv.Required("charging"): binary_sensor.binary_sensor_schema(
device_class="battery_charging"
),
cv.Required("full"): binary_sensor.binary_sensor_schema(),
cv.Required("charge_allowed"): binary_sensor.binary_sensor_schema(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC
),
cv.Required("level"): sensor.sensor_schema(
unit_of_measurement="%", accuracy_decimals=0, device_class="battery",
state_class="measurement", entity_category=ENTITY_CATEGORY_DIAGNOSTIC
),
cv.Required("current_limit"): sensor.sensor_schema(
unit_of_measurement="mA", accuracy_decimals=0,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC
),
}
)
.extend(cv.polling_component_schema("10s"))
.extend(i2c.i2c_device_schema(0x75))
)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await i2c.register_i2c_device(var, config)
for key in ("available", "charging", "full", "charge_allowed"):
entity = await binary_sensor.new_binary_sensor(config[key])
cg.add(getattr(var, f"set_{key}")(entity))
for key in ("level", "current_limit"):
entity = await sensor.new_sensor(config[key])
cg.add(getattr(var, f"set_{key}")(entity))
@@ -1,108 +0,0 @@
#pragma once
#include <cmath>
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/components/i2c/i2c.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#include "esphome/components/sensor/sensor.h"
namespace esphome::luxe_ip5306 {
// Optional IP5306-I2C on recent Luxe boards. Never changes power settings at boot.
class LuxeIP5306 : public PollingComponent, public i2c::I2CDevice {
public:
void set_available(binary_sensor::BinarySensor *s) { available_ = s; }
void set_charging(binary_sensor::BinarySensor *s) { charging_ = s; }
void set_full(binary_sensor::BinarySensor *s) { full_ = s; }
void set_charge_allowed(binary_sensor::BinarySensor *s) { charge_allowed_ = s; }
void set_level(sensor::Sensor *s) { level_ = s; }
void set_current_limit(sensor::Sensor *s) { current_limit_ = s; }
float get_setup_priority() const override { return setup_priority::DATA; }
void setup() override { update(); }
void update() override {
uint8_t control, charge, full, limit, gauge;
// Address-only ACK probe, then individual register reads. No assumption
// that the chip supports register auto-increment.
if (write(nullptr, 0) != i2c::ERROR_OK ||
!read_byte(0x00, &control) || !read_byte(0x70, &charge) ||
!read_byte(0x71, &full) || !read_byte(0x24, &limit)) {
unavailable_();
return;
}
valid_ = true;
charge_enabled_ = (control & 0x10) != 0;
available_->publish_state(true);
charge_allowed_->publish_state(charge_enabled_);
const bool full_flag = (full & 0x08) != 0;
full_->publish_state(full_flag);
charging_->publish_state(charge_enabled_ && (charge & 0x08) && !full_flag);
// Configured current, NOT measured current. Keep it separate from the
// charging state: 0x70 alone cannot establish USB presence in every mode.
current_limit_->publish_state(50 + 100 * (limit & 0x1F));
// Gauge is optional: undocumented on some revisions. Failure/unknown
// codes must never be presented as an empty battery.
float percent = NAN;
if (read_byte(0x78, &gauge)) {
switch (gauge >> 4) {
case 0x0: percent = 100; break;
case 0x8: percent = 75; break;
case 0xC: percent = 50; break;
case 0xE: percent = 25; break;
case 0xF: percent = 0; break;
}
}
level_->publish_state(percent);
}
optional<bool> charge_enabled() const {
if (!valid_) return {};
return charge_enabled_;
}
void set_charge_enabled(bool enabled) {
uint8_t before;
// Read afresh even if the last poll succeeded. Modify only bit 4, leaving
// boost, key behaviour and all reserved bits untouched.
if (write(nullptr, 0) != i2c::ERROR_OK || !read_byte(0x00, &before)) {
unavailable_();
ESP_LOGW("luxe_ip5306", "Recharge command rejected: circuit unavailable");
return;
}
const uint8_t after = enabled ? (before | 0x10) : (before & ~0x10);
if (after != before && !write_byte(0x00, after)) {
unavailable_();
ESP_LOGW("luxe_ip5306", "Recharge command failed");
return;
}
update(); // Read-back is authoritative; the switch is not optimistic.
if (valid_ && charge_enabled_ != enabled)
ESP_LOGW("luxe_ip5306", "Recharge command not confirmed by circuit");
}
protected:
void unavailable_() {
valid_ = false;
available_->publish_state(false);
charging_->invalidate_state();
full_->invalidate_state();
charge_allowed_->invalidate_state();
level_->publish_state(NAN);
current_limit_->publish_state(NAN);
// No mark_failed(): an older board must still play audio, and a device
// temporarily asleep or disconnected must be detected on the next poll.
}
binary_sensor::BinarySensor *available_{nullptr};
binary_sensor::BinarySensor *charging_{nullptr};
binary_sensor::BinarySensor *full_{nullptr};
binary_sensor::BinarySensor *charge_allowed_{nullptr};
sensor::Sensor *level_{nullptr};
sensor::Sensor *current_limit_{nullptr};
bool valid_{false};
bool charge_enabled_{false};
};
} // namespace esphome::luxe_ip5306
-119
View File
@@ -1,119 +0,0 @@
#pragma once
#include <cmath>
#include <cstdint>
class EnergyDayHistory {
public:
void observe(int channel, float cumulative_kwh, uint32_t day_key, int hour,
int seconds_into_hour, uint32_t timestamp) {
if (!valid_channel(channel) || !valid_day(day_key) || hour < 0 || hour >= 24 ||
seconds_into_hour < 0 || seconds_into_hour >= 3600)
return;
if (day_key != day_) {
day_ = day_key;
for (int c = 0; c < 3; ++c) {
for (int h = 0; h < 24; ++h) {
values_[c][h] = 0.0f;
coverage_[c][h] = 0;
}
}
}
Sample &sample = samples_[channel];
if (!std::isfinite(cumulative_kwh) || cumulative_kwh < 0.0f) {
invalidate(channel);
return;
}
const Sample previous = sample;
sample.valid = true;
sample.total = cumulative_kwh;
sample.day = day_key;
sample.hour = hour;
sample.seconds = seconds_into_hour;
sample.timestamp = timestamp;
if (!previous.valid || timestamp <= previous.timestamp ||
cumulative_kwh < previous.total)
return;
const uint32_t elapsed = timestamp - previous.timestamp;
if (elapsed > 300)
return;
const int end_seconds = previous.seconds + static_cast<int>(elapsed);
const bool crossed_hour = end_seconds >= 3600;
// Local seconds must agree with elapsed time, even across a DST transition.
if (seconds_into_hour != end_seconds % 3600 ||
(!crossed_hour && (previous.day != day_key || previous.hour != hour)))
return;
const float delta = cumulative_kwh - previous.total;
if (!crossed_hour) {
add(channel, hour, delta, elapsed);
return;
}
const uint32_t before = static_cast<uint32_t>(3600 - previous.seconds);
const float before_delta = delta * (static_cast<float>(before) / elapsed);
// The previous day's part is deliberately discarded after the daily reset.
if (previous.day == day_)
add(channel, previous.hour, before_delta, before);
if (elapsed > before)
add(channel, hour, delta - before_delta, elapsed - before);
}
void invalidate(int channel) {
if (valid_channel(channel))
samples_[channel].valid = false;
}
uint32_t day() const { return day_; }
// Repeated DST hours share a slot, so coverage can exceed 3600 seconds.
uint32_t coverage_seconds(int channel, int hour) const {
return valid_channel(channel) && hour >= 0 && hour < 24 ? coverage_[channel][hour] : 0;
}
bool has_data(int channel, int hour) const {
return coverage_seconds(channel, hour) != 0;
}
float value(int channel, int hour) const {
return has_data(channel, hour) ? values_[channel][hour] : 0.0f;
}
private:
struct Sample {
bool valid = false;
float total = 0.0f;
uint32_t day = 0;
int hour = 0;
int seconds = 0;
uint32_t timestamp = 0;
};
static bool valid_channel(int channel) { return channel >= 0 && channel < 3; }
static bool valid_day(uint32_t key) {
const uint32_t year = key / 10000;
const uint32_t month = key / 100 % 100;
const uint32_t day = key % 100;
if (year == 0 || year > 9999 || month == 0 || month > 12 || day == 0)
return false;
const int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const bool leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
return day <= static_cast<uint32_t>(days[month - 1] + (month == 2 && leap ? 1 : 0));
}
void add(int channel, int hour, float delta, uint32_t seconds) {
values_[channel][hour] += delta;
coverage_[channel][hour] += seconds;
}
uint32_t day_ = 0;
float values_[3][24] = {};
uint32_t coverage_[3][24] = {};
Sample samples_[3] = {};
};
File diff suppressed because it is too large Load Diff
+240 -254
View File
@@ -1,13 +1,8 @@
# Device identity shared by ESPHome and Home Assistant.
substitutions:
device_description: "ESP32 e-paper Home Assistant dashboard for indoor climate, energy and calendar events, with button-controlled pages"
name: epaperframe
friendly_name: "Info-Dashboard"
# Startup selects the default page only after Home Assistant has had time to
# provide the sensor states needed by its display lambda.
esphome:
comment: ${device_description}
name: ${name}
friendly_name: ${friendly_name}
name_add_mac_suffix: false
@@ -23,19 +18,18 @@ esphome:
- display.page.show: calendar # temporary for power page dev
- component.update: epaper
# ESP32 target and ESP-IDF build settings for the hardware revision in use.
esp32:
board: nodemcu-32s
framework:
type: esp-idf
advanced:
minimum_chip_revision: "3.0"
# Network access is required for Home Assistant state delivery and OTA updates.
network:
enable_ipv6: true
wifi:
ssid: "Voltage-legacy"
password: !secret voltage_legacy_psk
use_address: epaperframe.home
# use_address: epaperframe.home
power_save_mode: high
fast_connect: on
min_auth_mode: WPA2
@@ -55,19 +49,9 @@ api:
encryption:
key: !secret apikey
# Include ArduinoJson support for the compact calendar event feed.
json:
# Prevent refreshes when Home Assistant republishes unchanged calendar data.
globals:
- id: last_rendered_calendar_entries
type: std::string
restore_value: no
initial_value: '""'
ota:
platform: esphome
encryption:
password: !secret ota
# Power key of li-ion charger
output:
@@ -131,7 +115,6 @@ button:
- display.page.show_next: epaper
- component.update: epaper
# Numeric telemetry received from Home Assistant for the environment dashboard.
sensor:
# WiFi signal strength
- platform: wifi_signal
@@ -203,13 +186,34 @@ sensor:
entity_id: sensor.serverroom_serveraum_temperatur
id: temp_serverroom
- platform: homeassistant
entity_id: sensor.netzleistung
id: power_total
- platform: homeassistant
entity_id: sensor.serverraum_power
id: power_serverroom
- platform: homeassistant
entity_id: sensor.schreibtisch_power
id: desk_livingroom
- platform: homeassistant
entity_id: sensor.wohnzimmer_heimkino_power
id: media_livingroom
- platform: homeassistant
entity_id: sensor.schlafzimmer_bett_power
id: bedlight_sleepingroom
- platform: homeassistant
entity_id: sensor.schlafzimmer_heimkino_power
id: media_sleepingroom
- platform: homeassistant
entity_id: sensor.radioaktive_strahlungsleistung
id: radiation
# Textual Home Assistant state, including the compact calendar payload and quote.
text_sensor:
- platform: homeassistant
name: "Sun Rising ESP"
@@ -233,34 +237,34 @@ text_sensor:
entity_id: weather.zuhause
id: weather
# Display-ready JSON produced by the Home Assistant calendar template sensor.
# ── Kalender-Ereignisse (from HA input_text helpers) ──
- platform: homeassistant
entity_id: sensor.epaper_kalenderdaten
attribute: entries
id: calendar_entries
# Refresh the e-paper only for changed agenda data while the calendar page
# is visible; Home Assistant may otherwise republish identical JSON.
on_value:
then:
- if:
condition:
and:
- display.is_displaying_page: calendar
- lambda: return x != id(last_rendered_calendar_entries);
then:
- lambda: id(last_rendered_calendar_entries) = x;
- component.update: epaper
entity_id: sensor.kalender_heute_privat
id: kalender_heute_privat
internal: true
# Home Assistant selects one quote per day from its local quote library.
- platform: homeassistant
entity_id: sensor.epaper_demotivationszitat
id: demotivational_quote
entity_id: sensor.kalender_heute_arbeit
id: kalender_heute_arbeit
internal: true
- platform: homeassistant
entity_id: sensor.kalender_morgen_privat
id: kalender_morgen_privat
internal: true
- platform: homeassistant
entity_id: sensor.kalender_morgen_arbeit
id: kalender_morgen_arbeit
internal: true
graph:
- id: line_power_graph
sensor: power_total
duration: 2h
width: 235
height: 100
# Time drives panel power maintenance, the environment refresh cadence, and the
# midnight redraw that advances the calendar and daily quote.
time:
- platform: homeassistant
id: homeassistant_time
@@ -274,41 +278,21 @@ time:
- output.turn_on: power_key
- delay: 0.5s
- output.turn_off: power_key
# Environmental readings need their regular refresh. Calendar updates are
# instead triggered by changed event data while that page is active.
# Every 10 minutes
- seconds: 0
minutes: /10
then:
- if:
condition:
display.is_displaying_page: environment
then:
- logger.log:
level: INFO
format: "Timer based environment screen refresh"
- component.update: epaper
- seconds: 10
minutes: 0
hours: 0
then:
- logger.log:
level: INFO
format: "Update screen on new day"
format: "Timer based screen refresh"
- component.update: epaper
# Visual assets used by both 1-bit e-paper pages.
# Font definitions
font:
- file: "fonts/Roboto-Medium.ttf"
id: roboto_med_30
size: 30
# Small, digits-only font used to emphasize the current date in the month grid.
- file: "fonts/Roboto-Bold.ttf"
id: calendar_day_bold
size: 15
glyphs: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
- file: "fonts/Roboto-Regular.ttf"
id: footer_font
size: 15
@@ -757,21 +741,17 @@ font:
"󰀦", # mdi-alert
]
# Binary logo stored in firmware for rendering without network access.
image:
- platform: file
file: "epaperframe/C1024_logo_flat_bw.png"
- file: "epaperframe/C1024_logo_flat_bw.png"
id: c1024_logo
type: binary
resize: 77x40
invert_alpha: true
invert_alpha: True
# Shared SPI bus for the Waveshare e-paper panel.
spi:
clk_pin: 23
mosi_pin: 22
# The two pages draw directly onto the 640x384 1-bit Waveshare e-paper panel.
display:
- platform: waveshare_epaper
id: epaper
@@ -783,11 +763,8 @@ display:
# full_update_every: 30 # not supported on this display
update_interval: never
pages:
# Environmental telemetry dashboard, refreshed on the 10-minute timer.
- id: environment
lambda: |-
// Snapshot all Home Assistant values once per render so each panel uses
// a consistent set of readings throughout this e-paper refresh.
/* Outdoor */
float outdoor_temp = id(temp_outdoor).state;
int outdoor_humid = int(id(humid_outdoor).state);
@@ -811,11 +788,10 @@ display:
float childrensroom_co2 = id(co2_childrensroom).state;
int childrensroom_pm25 = int(id(pm25_childrensroom).state);
// Reuse one room widget layout by moving its origin across the two-column grid.
int offsetX = 0;
int offsetY = 0;
/* OUTSIDE: logo, headline, and outdoor sensor summary */
/* OUTSIDE */
it.print(10, 10, id(sensor_unit), "Umwelt");
/*
Draw the outline of a rectangle with the top left at [86,21],
@@ -1158,203 +1134,213 @@ display:
ESP_LOGI("WiFi", "Unlikely");
}
}
# Calendar agenda, month grid, and daily quote; redraws when event JSON changes.
- id: calendar
lambda: |-
// Use Home Assistant time for all date labels, month calculations, and
// the footer, avoiding locale-dependent formatting on the ESP32.
/* Fetch today and tomorrow dates */
auto now = id(homeassistant_time).now();
const char *months[] = {"Januar", "Februar", "März", "April", "Mai", "Juni",
"Juli", "August", "September", "Oktober", "November", "Dezember"};
const char *weekdays[] = {"Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"};
int today_day = now.day_of_month;
int today_month = now.month;
int today_wday = now.day_of_week; // 0=Sunday .. 6=Saturday
const char* weekdays[] = {"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"};
const char* today_weekday_str = weekdays[today_wday];
int today_year = now.year;
const int year = now.year;
const int month = now.month;
const int today = now.day_of_month;
/* Tomorrow's date */
int tomorrow_day = today_day + 1;
int tomorrow_month = today_month;
int tomorrow_wday = (today_wday + 1) % 7;
const char* tomorrow_weekday_str = weekdays[tomorrow_wday];
int tomorrow_year = today_year;
// Date helpers build a Monday-first month grid and ISO-8601 week numbers
// without relying on platform-specific C library time functions.
auto days_in_month = [](int calendar_year, int calendar_month) {
const int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (calendar_month == 2) {
return (calendar_year % 4 == 0 && (calendar_year % 100 != 0 || calendar_year % 400 == 0)) ? 29 : 28;
}
return days[calendar_month - 1];
};
auto weekday_monday = [](int calendar_year, int calendar_month, int day) {
const int offsets[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
calendar_year -= calendar_month < 3;
const int sunday_first = (calendar_year + calendar_year / 4 - calendar_year / 100 +
calendar_year / 400 + offsets[calendar_month - 1] + day) % 7;
return (sunday_first + 6) % 7;
};
auto iso_weeks_in_year = [&weekday_monday](int calendar_year) {
// 28 December is always in the final ISO week of its year.
const int day_of_year = 362 + ((calendar_year % 4 == 0 &&
(calendar_year % 100 != 0 || calendar_year % 400 == 0)) ? 1 : 0);
const int weekday = weekday_monday(calendar_year, 12, 28) + 1;
return (day_of_year - weekday + 10) / 7;
};
auto iso_week = [&weekday_monday, &days_in_month, &iso_weeks_in_year](int calendar_year, int calendar_month, int day) {
int day_of_year = day;
for (int current_month = 1; current_month < calendar_month; current_month++) {
day_of_year += days_in_month(calendar_year, current_month);
}
const int weekday = weekday_monday(calendar_year, calendar_month, day) + 1;
int week = (day_of_year - weekday + 10) / 7;
if (week < 1) return iso_weeks_in_year(calendar_year - 1);
if (week > iso_weeks_in_year(calendar_year)) return 1;
return week;
};
/* C1024 logo */
it.image(10, 37, id(c1024_logo));
/* LEFT PANE: agenda */
it.image(10, 10, id(c1024_logo));
it.print(226, 38, id(roboto_med_30), TextAlign::BASELINE_CENTER, "TERMINE");
it.line(10, 55, 355, 55);
it.line(365, 10, 365, 352);
/* ── LEFT PANE: Today ── */
int leftX = 10;
int leftY = 70; // start below header row
// Parse the compact JSON attribute produced by Home Assistant. The empty
// and error states below ensure a useful screen while data is unavailable.
JsonDocument calendar_doc;
const DeserializationError calendar_error = deserializeJson(calendar_doc, id(calendar_entries).state.c_str());
JsonArray calendar_days = calendar_doc.as<JsonArray>();
int agenda_y = 72;
bool has_events = false;
bool has_hidden_events = false;
it.print(15 + leftX, 10 + leftY, id(sensor_unit), "Heute");
it.filled_rectangle(80 + leftX, 21 + leftY, 240, 3);
if (calendar_error || calendar_days.isNull()) {
it.print(18, agenda_y, id(sensor_unit), TextAlign::TOP_LEFT, "Kalenderdaten werden geladen ...");
} else if (calendar_days.size() == 0) {
it.print(18, agenda_y, id(sensor_unit), TextAlign::TOP_LEFT, "Keine Termine in den nächsten Tagen.");
/* Today's date strip */
it.printf(50 + leftX, 50 + leftY, id(big_sensor_font), "%d", today_day);
it.printf(145 + leftX, 45 + leftY, id(sub_sensor_font), "%s.", today_weekday_str);
it.printf(205 + leftX, 45 + leftY, id(sensor_unit), "%02d.%04d.", today_month, today_year);
/* Event lines (Privat / Arbeit) */
int eventOffsetY = 90;
// Helper lambda: draw one event line at given Y offset with the given text sensor id
// Privat today
if (id(kalender_heute_privat).has_state() && !id(kalender_heute_privat).state.empty()) {
it.print(10 + leftX, 50 + leftY + eventOffsetY, id(mdi_med), TextAlign::BASELINE_LEFT, "\U0001f32e" );
// Split by │ separator and display first line of events
auto parts = id(kalender_heute_privat).state.c_str();
it.printf(40 + leftX, 50 + leftY + eventOffsetY, id(sub_sensor_font), "%s",
id(kalender_heute_privat).state.substr(0, 60).c_str());
} else {
for (JsonVariant day_variant : calendar_days) {
JsonObject day = day_variant.as<JsonObject>();
JsonArray events = day["events"].as<JsonArray>();
if (events.isNull() || events.size() == 0) continue;
if (agenda_y + 38 > 345) {
has_hidden_events = true;
break;
}
// A date rail occupies the left edge; event rows start alongside it
// and stop before the footer rather than overflowing the panel.
const int group_y = agenda_y;
int event_y = group_y;
const int day_number = day["day"] | 0;
const char *weekday = day["weekday"] | "";
it.printf(30, group_y, id(sub_sensor_font), TextAlign::TOP_CENTER, "%d", day_number);
it.printf(30, group_y + 28, id(footer_font), TextAlign::TOP_CENTER, "%s", weekday);
for (JsonVariant event_variant : events) {
if (event_y + 33 > 345) {
has_hidden_events = true;
break;
}
JsonObject event = event_variant.as<JsonObject>();
const char *title = event["title"] | "Ohne Titel";
const char *time = event["time"] | "";
const char *end_time = event["end"] | "";
const char *meta = event["meta"] | "";
it.printf(72, event_y, id(sensor_unit), TextAlign::TOP_LEFT, "%s", title);
it.printf(350, event_y, id(sensor_unit), TextAlign::TOP_RIGHT, "%s", time);
it.printf(72, event_y + 20, id(footer_font), TextAlign::TOP_LEFT, "%s", meta);
if (end_time[0] != '\0') {
it.printf(350, event_y + 20, id(footer_font), TextAlign::TOP_RIGHT, "%s", end_time);
}
event_y += 35;
has_events = true;
}
int group_bottom = event_y;
if (group_bottom < group_y + 36) group_bottom = group_y + 36;
it.line(58, group_y, 58, group_bottom);
agenda_y = group_bottom + 5;
if (has_hidden_events) break;
}
it.print(10 + leftX, 50 + leftY + eventOffsetY, id(mdi_med), TextAlign::BASELINE_LEFT, "\U0001f32e" );
it.printf(40 + leftX, 50 + leftY + eventOffsetY, id(sub_sensor_font), "Kein Termin");
}
if (!has_events && !calendar_error && !calendar_days.isNull() && calendar_days.size() > 0) {
it.print(18, 72, id(sensor_unit), TextAlign::TOP_LEFT, "Keine Termine im sichtbaren Bereich.");
// Arbeit today
if (id(kalender_heute_arbeit).has_state() && !id(kalender_heute_arbeit).state.empty()) {
it.print(10 + leftX, 85 + leftY + eventOffsetY, id(mdi_med), TextAlign::BASELINE_LEFT, "\U0001f32e" );
it.printf(40 + leftX, 85 + leftY + eventOffsetY, id(sub_sensor_font), "%s",
id(kalender_heute_arbeit).state.substr(0, 60).c_str());
} else {
it.print(10 + leftX, 85 + leftY + eventOffsetY, id(mdi_med), TextAlign::BASELINE_LEFT, "\U0001f32e" );
it.printf(40 + leftX, 85 + leftY + eventOffsetY, id(sub_sensor_font), "Kein Termin");
}
/* ── RIGHT PANE: Tomorrow ── */
int rightX = 315;
int rightY = 70;
/* RIGHT TOP: month view, Monday-first with ISO week numbers */
// Draw only the five or six rows this month actually needs so no orphan
// week number is rendered beneath shorter months.
char month_title[24];
snprintf(month_title, sizeof(month_title), "%s %d", months[month - 1], year);
it.printf(502, 18, id(sensor_unit), TextAlign::TOP_CENTER, "%s", month_title);
it.print(384, 47, id(footer_font), TextAlign::TOP_CENTER, "KW");
for (int column = 0; column < 7; column++) {
it.printf(415 + column * 30, 47, id(footer_font), TextAlign::TOP_CENTER, "%s", weekdays[column]);
it.print(45 + rightX, 10 + rightY, id(sensor_unit), "Morgen");
it.filled_rectangle(130 + rightX, 21 + rightY, 200, 3);
/* Date strip */
it.printf(50 + rightX, 50 + rightY, id(big_sensor_font), "%d", tomorrow_day);
it.printf(145 + rightX, 45 + rightY, id(sub_sensor_font), "%s.", tomorrow_weekday_str);
it.printf(205 + rightX, 45 + rightY, id(sensor_unit), "%02d.%04d.", tomorrow_month, tomorrow_year);
/* Event lines (Privat / Arbeit) */
// Privat tomorrow
if (id(kalender_morgen_privat).has_state() && !id(kalender_morgen_privat).state.empty()) {
it.print(10 + rightX, 50 + rightY + eventOffsetY, id(mdi_med), TextAlign::BASELINE_LEFT, "\U0001f32e" );
it.printf(40 + rightX, 50 + rightY + eventOffsetY, id(sub_sensor_font), "%s",
id(kalender_morgen_privat).state.substr(0, 60).c_str());
} else {
it.print(10 + rightX, 50 + rightY + eventOffsetY, id(mdi_med), TextAlign::BASELINE_LEFT, "\U0001f32e" );
it.printf(40 + rightX, 50 + rightY + eventOffsetY, id(sub_sensor_font), "Kein Termin");
}
// Arbeit tomorrow
if (id(kalender_morgen_arbeit).has_state() && !id(kalender_morgen_arbeit).state.empty()) {
it.print(10 + rightX, 85 + rightY + eventOffsetY, id(mdi_med), TextAlign::BASELINE_LEFT, "\U0001f32e" );
it.printf(40 + rightX, 85 + rightY + eventOffsetY, id(sub_sensor_font), "%s",
id(kalender_morgen_arbeit).state.substr(0, 60).c_str());
} else {
it.print(10 + rightX, 85 + rightY + eventOffsetY, id(mdi_med), TextAlign::BASELINE_LEFT, "\U0001f32e" );
it.printf(40 + rightX, 85 + leftY + eventOffsetY, id(sub_sensor_font), "Kein Termin");
}
const int first_weekday = weekday_monday(year, month, 1);
const int month_days = days_in_month(year, month);
const int calendar_rows = (first_weekday + month_days + 6) / 7;
for (int row = 0; row < calendar_rows; row++) {
const int monday_day = 1 - first_weekday + row * 7;
int week_year = year;
int week_month = month;
int week_day = monday_day;
if (week_day < 1) {
week_month--;
if (week_month == 0) {
week_month = 12;
week_year--;
}
week_day += days_in_month(week_year, week_month);
} else if (week_day > month_days) {
week_day -= month_days;
week_month++;
if (week_month == 13) {
week_month = 1;
week_year++;
}
}
const int cell_y = 69 + row * 23;
it.printf(384, cell_y, id(footer_font), TextAlign::TOP_CENTER, "%02d", iso_week(week_year, week_month, week_day));
/* FOOTER */
it.strftime(614, 380, id(footer_font), TextAlign::BASELINE_RIGHT, "Aktualisiert um %d.%m.%Y %H:%M", id(homeassistant_time).now());
for (int column = 0; column < 7; column++) {
const int day = row * 7 + column - first_weekday + 1;
if (day < 1 || day > month_days) continue;
const int cell_x = 415 + column * 30;
if (day == today) {
it.filled_rectangle(cell_x - 12, cell_y - 2, 25, 18, COLOR_ON);
it.printf(cell_x, cell_y, id(calendar_day_bold), COLOR_OFF, TextAlign::TOP_CENTER, "%d", day);
} else {
it.printf(cell_x, cell_y, id(footer_font), TextAlign::TOP_CENTER, "%d", day);
}
}
}
/* RIGHT BOTTOM: daily quote selected by Home Assistant */
// Wrap on word boundaries into the fixed four-line, inverted quote panel.
it.filled_rectangle(375, 220, 255, 130, COLOR_ON);
std::string quote = "Zitat wird geladen.";
if (id(demotivational_quote).has_state() && !id(demotivational_quote).state.empty()) {
quote = id(demotivational_quote).state;
}
const size_t max_quote_characters = 27;
size_t quote_start = 0;
for (int line = 0; line < 4 && quote_start < quote.length(); line++) {
size_t quote_end = quote_start + max_quote_characters;
if (quote_end < quote.length()) {
const size_t word_break = quote.rfind(' ', quote_end);
if (word_break != std::string::npos && word_break > quote_start) quote_end = word_break;
/* WiFi Signal strength */
if(id(wifisignal).has_state()) {
int x = 630;
int y = 384;
if (id(wifisignal).state >= -50) {
it.print(x, y, id(mdi_wifi), TextAlign::BASELINE_CENTER, "󰤨");
} else if (id(wifisignal).state >= -60) {
it.print(x, y, id(mdi_wifi), TextAlign::BASELINE_CENTER, "󰤥");
} else if (id(wifisignal).state >= -75) {
it.print(x, y, id(mdi_wifi), TextAlign::BASELINE_CENTER, "󰤢");
} else if (id(wifisignal).state >= -100) {
it.print(x, y, id(mdi_wifi), TextAlign::BASELINE_CENTER, "󰤟");
} else {
quote_end = quote.length();
it.print(x, y, id(mdi_wifi), TextAlign::BASELINE_CENTER, "󰤫");
}
const std::string quote_line = quote.substr(quote_start, quote_end - quote_start);
it.printf(502, 234 + line * 24, id(sensor_unit), COLOR_OFF, TextAlign::TOP_CENTER, "%s", quote_line.c_str());
quote_start = quote_end;
while (quote_start < quote.length() && quote[quote_start] == ' ') quote_start++;
}
/* FOOTER: Footer is shared visual status: render timestamp plus a Wi-Fi-strength glyph. */
it.strftime(614, 380, id(footer_font), TextAlign::BASELINE_RIGHT,
"Aktualisiert um %d.%m.%Y %H:%M", now);
- id: power
lambda: |-
float total_power = id(power_total).state;
float serverroom_power = id(power_serverroom).state;
float livingroom_desk = id(desk_livingroom).state;
float livingroom_media = id(media_livingroom).state;
float sleepingroom = id(media_sleepingroom).state + id(bedlight_sleepingroom).state;
int offsetX = 0;
int offsetY = 0;
/* BASEMENT */
it.print(10, 10, id(sensor_unit), "Keller");
/*
Draw the outline of a rectangle with the top left at [86,21],
a width of 297 and a height of 3
*/
it.filled_rectangle(76, 21, 307, 3);
/* C1024 logo */
it.image(10 , 37, id(c1024_logo));
/* Livingroom */
offsetY = 127;
it.print(10, 10 + offsetY, id(sensor_unit), "Wohnzimmer");
it.filled_rectangle(136, 21 + offsetY, 247, 3);
it.print(375, 75 + offsetY, id(mdi_small), TextAlign::BASELINE_CENTER, "󰚥"); // power-plug
it.print(375, 115 + offsetY, id(mdi_small), TextAlign::BASELINE_CENTER, "󰚥"); // power-plug
it.print(20, 75 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_LEFT, "Schreibtisch");
if(livingroom_desk >= 0) {
it.printf(357, 75 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, "%2.1f W", livingroom_desk);
}
else {
it.print(357, 75 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, " - W");
}
it.print(20, 115 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_LEFT, "Heimkino");
if(livingroom_media >= 0) {
it.printf(357, 115 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, "%2.1f W", livingroom_media);
}
else {
it.print(357, 115 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, " - W");
}
/* Sleepingroom */
offsetY = 247;
it.print(10, 10 + offsetY, id(sensor_unit), "Schlafzimmer");
it.filled_rectangle(144, 21 + offsetY, 239, 3);
it.print(375, 115 + offsetY, id(mdi_small), TextAlign::BASELINE_CENTER, "󰚥"); // power-plug
// it.print(20, 115 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_LEFT, "Heimkino");
if(sleepingroom >= 0) {
it.printf(357, 115 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, "%2.1f W", sleepingroom);
}
else {
it.print(357, 115 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, " - W");
}
/* LINEPOWER */
offsetX = 390;
offsetY = 65;
it.print(10 + offsetX, 10, id(sensor_unit), "Gesamt");
it.filled_rectangle(90 + offsetX, 21, 155, 3);
it.print(227 + offsetX, 20 + offsetY, id(mdi_small), TextAlign::BASELINE_CENTER, "󰴾"); // transmission-tower
if(total_power >= 0) {
it.printf(207 + offsetX, 20 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, "W");
it.printf(170 + offsetX, 20 + offsetY, id(big_sensor_font), TextAlign::BASELINE_RIGHT, "%2.1f", total_power);
}
else {
it.print(207 + offsetX, 20 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, " - W");
}
it.graph(10 + offsetX, 30 + offsetY, id(line_power_graph));
/* Serverroom */
offsetY = 247;
it.print(10 + offsetX, 10 + offsetY, id(sensor_unit), "Serverraum");
it.filled_rectangle(125 + offsetX, 21 + offsetY, 110, 3);
it.print(227 + offsetX, 110 + offsetY, id(mdi_small), TextAlign::BASELINE_CENTER, "󰚥"); // power-plug
if(serverroom_power >= 0) {
it.printf(207 + offsetX, 110 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, "W");
it.printf(170 + offsetX, 110 + offsetY, id(big_sensor_font), TextAlign::BASELINE_RIGHT, "%2.1f", serverroom_power);
}
else {
it.print(207 + offsetX, 110 + offsetY, id(sub_sensor_font), TextAlign::BASELINE_RIGHT, " - W");
}
/* FOOTER */
it.strftime(614, 380, id(footer_font), TextAlign::BASELINE_RIGHT , "Aktualisiert um %d.%m.%Y %H:%M", id(homeassistant_time).now());
/* WiFi Signal strength */
if(id(wifisignal).has_state()) {
+1 -3
View File
@@ -1,10 +1,8 @@
substitutions:
device_description: "ESP32 Geiger counter with radiation dose rate, accumulated dose and MAX7219 seven-segment display"
name: "geigercounter"
friendly_name: "Geigerzähler"
esphome:
comment: ${device_description}
name: ${name}
friendly_name: ${friendly_name}
name_add_mac_suffix: false
@@ -46,7 +44,7 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
spi:
clk_pin: 18
+1 -5
View File
@@ -1,11 +1,9 @@
substitutions:
device_description: "Home Assistant Voice PE voice assistant with microphone and speaker."
name: home-assistant-voice-09c0e7
friendly_name: Home Assistant Voice Küche
packages:
Nabu Casa.Home Assistant Voice PE: github://esphome/home-assistant-voice-pe/home-assistant-voice.yaml
esphome:
comment: ${device_description}
name: ${name}
name_add_mac_suffix: false
friendly_name: ${friendly_name}
@@ -30,8 +28,6 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
http_request:
captive_portal:
+1 -5
View File
@@ -1,11 +1,9 @@
substitutions:
device_description: "Home Assistant Voice PE voice assistant with microphone and speaker."
name: home-assistant-voice-0a7c6b
friendly_name: Home Assistant Voice Wohnzimmer
packages:
Nabu Casa.Home Assistant Voice PE: github://esphome/home-assistant-voice-pe/home-assistant-voice.yaml
esphome:
comment: ${device_description}
name: ${name}
name_add_mac_suffix: false
friendly_name: ${friendly_name}
@@ -30,8 +28,6 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
http_request:
captive_portal:
+1 -3
View File
@@ -1,10 +1,8 @@
substitutions:
name: kamera-balkon
friendly_name: Kamera Balkon
device_description: "Balcony ESP32-CAM with HTTP stream and snapshots, flash LED, and SHT3x temperature and humidity sensing."
esphome:
comment: ${device_description}
name: ${name}
friendly_name: ${friendly_name}
name_add_mac_suffix: false
@@ -45,7 +43,7 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
# Initialize I²C
i2c:
+1 -3
View File
@@ -1,10 +1,8 @@
substitutions:
name: kamera-wohnzimmer
friendly_name: Kamera Wohnzimmer
device_description: "Living-room ESP32 camera with HTTP stream and snapshots and a controllable flash LED."
esphome:
comment: ${device_description}
name: ${name}
friendly_name: ${friendly_name}
name_add_mac_suffix: false
@@ -45,7 +43,7 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
# Initialize I²C
i2c:
+5 -11
View File
@@ -27,16 +27,10 @@ esphome:
includes:
- lab-ble-proxy.h
on_boot:
- priority: 850
then:
- lambda: |-
owon_b35t::core2_axp192_init(id(core2_i2c));
# Start the normal dimming/off cycle after a cold boot as well. The
# light component is initialized by this priority, while BLE callbacks
# and touch events can still restart the script through wake_backlight.
- priority: 600
then:
- script.execute: backlight_idle
priority: 850
then:
- lambda: |-
owon_b35t::core2_axp192_init(id(core2_i2c));
project:
name: "custom.lab-ble-proxy-m5stack-core2"
version: "1.0"
@@ -67,7 +61,7 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
network:
enable_ipv6: true
+2 -4
View File
@@ -1,10 +1,8 @@
substitutions:
device_description: "ESP32 living-room air quality monitor with SCD30 CO2, temperature and humidity, PM2.5 sensing and RGB status LED"
name: "livingroom"
friendly_name: "Luftqualität Wohnzimmer"
esphome:
comment: ${device_description}
name: ${name}
friendly_name: ${friendly_name}
name_add_mac_suffix: false
@@ -88,7 +86,7 @@ api:
# Enable over-the-air updates
ota:
platform: esphome
encryption:
password: !secret ota
# Initialize I²C
i2c:
@@ -209,12 +207,12 @@ sensor:
temperature:
name: "Wohnzimmer Temperatur"
accuracy_decimals: 2
# SCD30 temp sensor is a bit off
filters:
- offset: -2.5
humidity:
name: "Wohnzimmer Luftfeuchtigkeit"
accuracy_decimals: 1
# SCD30 temp sensor is a bit off
ambient_pressure_compensation: 1
automatic_self_calibration: True
address: 0x61
-487
View File
@@ -1,487 +0,0 @@
substitutions:
startup_sound_file: https://github.com/RASPIAUDIO/esphomeLuxe/raw/refs/heads/main/wav/sounds_timer_finished.wav
device_description: "Raspiaudio Muse Luxe Music player for Music Assistant using sendspin"
name: "muse-luxe-music"
friendly_name: "Raspiaudio Muse Luxe Music"
esphome:
comment: ${device_description}
name: ${name}
friendly_name: ${friendly_name}
min_version: 2026.8.2
name_add_mac_suffix: false
on_boot:
priority: -100
then:
# GPIO21 commande la mise en sourdine de l'amplificateur de la Luxe.
- output.turn_off: dac_mute
# Laisse le mixer terminer une annonce avant la reprise d'un flux MA.
- speaker_source.set_playlist_delay:
id: external_media_player
pipeline: announcement
delay: 500ms
- speaker_source.set_playlist_delay:
id: external_media_player
pipeline: media
delay: 1500ms
- script.execute: led_red
project:
name: raspiaudio.music-assistant
version: "2026.9.3"
esp32:
variant: esp32
framework:
type: esp-idf
advanced:
include_builtin_idf_components:
- esp_http_client
sram1_as_iram: true
logger:
level: warn
api:
encryption:
key: !secret apikey
# La lecture Sendspin doit continuer même sans client Home Assistant connecté.
reboot_timeout: 0s
on_client_connected:
- if:
condition:
lambda: return !id(boot_sound_played);
then:
- lambda: id(boot_sound_played) = true;
# Laisse MA restaurer son groupe avant de décider si l'annonce peut jouer.
- delay: 5s
- if:
condition:
lambda: |-
using media_player::MediaPlayerState;
return id(startup_sound_switch).state &&
id(external_media_player).state != MediaPlayerState::MEDIA_PLAYER_STATE_PLAYING &&
id(external_media_player).state != MediaPlayerState::MEDIA_PLAYER_STATE_ANNOUNCING;
then:
- script.execute:
id: play_sound
priority: true
sound_file: ready_sound
wifi:
ssid: "Voltage-legacy"
password: !secret voltage_legacy_psk
#use_address: ${name}.home
power_save_mode: high
fast_connect: on
min_auth_mode: WPA2
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Raspiaudio Fallback Hotspot"
password: !secret fallback_psk
psram:
mode: quad
speed: 80MHz
ota:
- platform: esphome
id: ota_esphome
encryption:
- platform: http_request
id: ota_http_request
http_request:
captive_portal:
improv_serial:
external_components:
- source:
type: local
path: components
components: [luxe_ip5306]
# Initialisation spécifique du codec de la museLuxe (sorties différentielles
# et horloge MCLK sur GPIO0). Sendspin et la chaîne audio sont désormais natifs.
- source:
type: git
url: https://github.com/RASPIAUDIO/esphomeLuxe
ref: 192372ff59b560a74aa547dc26af609918fcc9d6
components: [es8388]
i2c:
sda: GPIO18
scl: GPIO23
frequency: 100kHz
id: bus_a
es8388:
i2s_audio:
- id: i2s_audio_bus
i2s_lrclk_pin: GPIO25
i2s_bclk_pin: GPIO5
#####################
# Internal Components
output:
- platform: gpio
id: dac_mute
pin:
number: GPIO21
inverted: true
mode:
output: true
speaker:
- platform: i2s_audio
id: box_speaker
i2s_audio_id: i2s_audio_bus
i2s_dout_pin: GPIO26
dac_type: external
channel: stereo
sample_rate: 48000
bits_per_sample: 16bit
buffer_duration: 300ms
mclk_multiple: 384
- platform: mixer
id: mixing_speaker
output_speaker: box_speaker
num_channels: 2
source_speakers:
- id: announcement_mixer_input
- id: media_mixer_input
- platform: resampler
id: media_resampling_input
output_speaker: media_mixer_input
sample_rate: 48000
- platform: resampler
id: announcement_resampling_input
output_speaker: announcement_mixer_input
sample_rate: 48000
sendspin:
id: sendspin_hub
audio_file:
- id: ready_sound
file: ${startup_sound_file}
media_source:
- platform: sendspin
id: sendspin_source
buffer_size: 2000000
- platform: audio_file
id: file_source
media_player:
- platform: sendspin
id: sendspin_media_player
name: museLuxe
volume_increment: 2%
- platform: speaker_source
name: museLuxe Audio
id: external_media_player
internal: true
announcement_pipeline:
speaker: announcement_resampling_input
sources:
- file_source
format: FLAC
num_channels: 1
sample_rate: 48000
media_pipeline:
speaker: media_resampling_input
sources:
- sendspin_source
format: FLAC
num_channels: 2
sample_rate: 48000
volume_increment: 0.05
volume_min: 0.05
volume_max: 0.95
on_state:
then:
- lambda: |-
using media_player::MediaPlayerState;
auto state = id(external_media_player).state;
if (
state == MediaPlayerState::MEDIA_PLAYER_STATE_PLAYING ||
state == MediaPlayerState::MEDIA_PLAYER_STATE_ANNOUNCING
) {
id(led_green).execute();
} else {
id(led_red).execute();
}
script:
- id: update_battery_led
mode: queued
max_runs: 2
then:
- lambda: |-
const bool critical = id(battery_critical).state;
if (critical && (!id(led).remote_values.is_on() || id(led).get_effect_name() != "Battery alert")) {
auto call = id(led).turn_on();
call.set_effect("Battery alert");
call.set_brightness(1.0f);
call.perform();
} else if (!critical && id(led).get_effect_name() == "Battery alert") {
auto call = id(led).turn_on();
call.set_effect("None");
call.perform();
}
- id: play_sound
parameters:
priority: bool
sound_file: string
then:
- if:
condition:
lambda: return priority;
then:
- media_player.stop:
id: external_media_player
announcement: true
- lambda: |-
if ( (id(external_media_player).state != media_player::MediaPlayerState::MEDIA_PLAYER_STATE_ANNOUNCING ) || priority) {
id(external_media_player)
->make_call()
.set_media_url("audio-file://" + sound_file)
.set_announcement(true)
.perform();
}
- id: led_red
then:
- light.turn_on:
id: led
red: 100%
green: 0%
blue: 0%
brightness: 100%
- id: led_green
then:
- light.turn_on:
id: led
red: 0%
green: 100%
blue: 0%
brightness: 100%
switch:
- platform: template
id: ip5306_charge_switch
name: "Allow charging"
entity_category: config
icon: mdi:battery-charging
restore_mode: DISABLED
optimistic: false
lambda: return id(battery_manager).charge_enabled();
turn_on_action:
- lambda: id(battery_manager).set_charge_enabled(true);
turn_off_action:
- lambda: id(battery_manager).set_charge_enabled(false);
- platform: template
id: startup_sound_switch
name: Startup sound
icon: "mdi:card-text-outline"
entity_category: config
optimistic: true
restore_mode: RESTORE_DEFAULT_ON
globals:
- id: boot_sound_played
type: bool
restore_value: no
initial_value: "false"
binary_sensor:
- platform: template
id: battery_critical
name: Battery low
device_class: battery
entity_category: diagnostic
lambda: |-
if (!id(battery_percent).has_state() || !std::isfinite(id(battery_percent).state)) return {};
const float percent = id(battery_percent).state;
const float threshold = id(battery_alert_threshold).state;
if (percent < threshold) return true;
if (percent >= threshold + 5.0f) return false;
return {};
on_state:
- script.execute: update_battery_led
- platform: gpio
pin:
number: GPIO12
inverted: true
mode:
input: true
output: false
open_drain: false
pullup: true
pulldown: false
drive_strength: 20.0
name: Play or Pause
on_press:
then:
- media_player.toggle: sendspin_media_player
- platform: gpio
pin:
number: GPIO19
inverted: true
mode:
input: true
pullup: true
name: Volume Up
on_click:
- media_player.volume_up:
id: sendspin_media_player
- platform: gpio
pin:
number: GPIO32
inverted: true
mode:
input: true
pullup: true
name: Volume Down
on_click:
- media_player.volume_down:
id: sendspin_media_player
light:
- platform: esp32_rmt_led_strip
id: led
name: LED light
disabled_by_default: false
entity_category: config
pin: GPIO22
default_transition_length: 0s
chipset: WS2812
num_leds: 1
channel_colors: GRB
# Conserve l'alerte après une commande HA ou un changement lecture/arrêt.
on_state:
- script.execute: update_battery_led
effects:
- addressable_lambda:
name: "Battery alert"
update_interval: 500ms
lambda: |-
static bool lit = false;
if (initial_run) lit = false;
lit = !lit;
it.all() = lit ? current_color : Color::BLACK;
- pulse:
name: "Slow Pulse"
transition_length: 250ms
update_interval: 250ms
min_brightness: 50%
max_brightness: 100%
- pulse:
name: "Fast Pulse"
transition_length: 100ms
update_interval: 100ms
min_brightness: 50%
max_brightness: 100%
sensor:
- platform: adc
pin: GPIO33
id: battery_voltage
name: Battery voltage
icon: "mdi:battery-outline"
update_interval: 15s
accuracy_decimals: 3
attenuation: 12db
raw: true
filters:
- multiply: 0.00173913 # 2300 -> 4, for attenuation 11db, based on Olivier's code
- exponential_moving_average:
alpha: 0.2
send_every: 2
- delta: 0.002
on_value:
- sensor.template.publish:
id: battery_percent
state: !lambda return x;
- platform: template
id: battery_percent
name: Battery level
device_class: battery
unit_of_measurement: "%"
accuracy_decimals: 0
state_class: measurement
entity_category: diagnostic
update_interval: never
# Même estimation tension/charge que la Radio, après calibration Luxe.
filters:
- calibrate_polynomial:
degree: 3
datapoints:
- 4.20 -> 100.0
- 4.13 -> 97.1
- 4.10 -> 94.2
- 4.07 -> 88.4
- 4.05 -> 82.7
- 4.04 -> 76.9
- 4.04 -> 71.1
- 4.01 -> 65.3
- 3.99 -> 59.5
- 3.95 -> 53.8
- 3.93 -> 48.0
- 3.91 -> 42.2
- 3.88 -> 36.4
- 3.86 -> 30.6
- 3.84 -> 24.9
- 3.82 -> 19.1
- 3.76 -> 13.3
- 3.73 -> 10.4
- 3.70 -> 7.5
- 3.64 -> 4.6
- 3.50 -> 1.7
- 3.00 -> 0.0
- lambda: return clamp(x, 0.0f, 100.0f);
- platform: wifi_signal
name: "museLuxe WiFi signal"
update_interval: 10s
# Paramètre logiciel : conserve une hystérésis fixe de 5 points.
number:
- platform: template
id: battery_alert_threshold
name: "Low battery threshold"
entity_category: config
unit_of_measurement: "%"
min_value: 5
max_value: 50
step: 1
initial_value: 20
restore_value: true
optimistic: true
mode: box
luxe_ip5306:
id: battery_manager
i2c_id: bus_a
address: 0x75
update_interval: 10s
available:
name: "IP5306 available"
id: ip5306_available
charging:
name: "Charging"
full:
name: "Battery full"
charge_allowed:
name: "Charging enabled (hardware)"
level:
name: "IP5306 battery level"
current_limit:
name: "IP5306 charge current limit"
+47 -90
View File
@@ -3,25 +3,18 @@
substitutions:
name: m5stack-atom-echo
friendly_name: M5Stack Atom Echo
device_description: "M5Stack Atom Echo ESP32 voice assistant with on-device or Home Assistant wake-word detection and timer announcements."
micro_wake_word_model: okay_nabu # alexa, hey_jarvis, hey_mycroft are also supported
esphome:
comment: ${device_description}
name: ${name}
name_add_mac_suffix: false
name_add_mac_suffix: False
friendly_name: ${friendly_name}
min_version: 2026.10.2
min_version: 2025.2.0
esp32:
board: m5stack-atom
cpu_frequency: 240MHz
framework:
type: esp-idf
sdkconfig_options:
# Home Assistant's Modern TLS profile only accepts TLS 1.3.
CONFIG_MBEDTLS_SSL_PROTO_TLS1_3: "y"
advanced:
sram1_as_iram: true
# Enable Home Assistant API
api:
@@ -31,7 +24,7 @@ api:
ota:
- platform: esphome
id: ota_esphome
encryption:
password: !secret ota
network:
enable_ipv6: true
@@ -70,17 +63,14 @@ microphone:
i2s_din_pin: GPIO23
adc_type: external
pdm: true
sample_rate: 16000
correct_dc_offset: true
speaker:
- platform: i2s_audio
id: echo_speaker
i2s_dout_pin: GPIO22
dac_type: external
bits_per_sample: 16bit
sample_rate: 16000
channel: stereo # The Echo has poor playback audio quality when using mon audio
bits_per_sample: 32bit
channel: right
buffer_duration: 60ms
media_player:
@@ -90,6 +80,7 @@ media_player:
announcement_pipeline:
speaker: echo_speaker
format: WAV
codec_support_enabled: false
buffer_size: 6000
volume_min: 0.4
files:
@@ -100,7 +91,14 @@ media_player:
condition:
- microphone.is_capturing:
then:
- script.execute: stop_wake_word
- if:
condition:
lambda: return id(wake_word_engine_location).state == "On device";
then:
- micro_wake_word.stop:
else:
- voice_assistant.stop:
- script.execute: reset_led
- light.turn_on:
id: led
blue: 100%
@@ -110,18 +108,14 @@ media_player:
effect: none
on_idle:
- script.execute: start_wake_word
- script.execute: reset_led
voice_assistant:
id: va
micro_wake_word:
microphone:
microphone: echo_microphone
channels: 0
gain_factor: 4
microphone: echo_microphone
media_player: echo_media_player
noise_suppression_level: 2
auto_gain: 31dBFS
volume_multiplier: 2.0
on_listening:
- light.turn_on:
id: led
@@ -145,26 +139,8 @@ voice_assistant:
brightness: 100%
effect: none
on_end:
# Handle the "nevermind" case where there is no announcement
- wait_until:
condition:
- media_player.is_announcing:
timeout: 0.5s
# Restart only mWW if enabled; streaming wake words automatically restart
- if:
condition:
- lambda: |-
return id(wake_word_engine_location).current_option() == "On device";
then:
- wait_until:
- and:
- not:
voice_assistant.is_running:
- not:
speaker.is_playing:
- lambda: id(va).set_use_wake_word(false);
- micro_wake_word.start:
- script.execute: reset_led
- delay: 100ms
- script.execute: start_wake_word
on_error:
- light.turn_on:
id: led
@@ -179,9 +155,11 @@ voice_assistant:
- delay: 2s # Give the api server time to settle
- script.execute: start_wake_word
on_client_disconnected:
- script.execute: stop_wake_word
- voice_assistant.stop:
- micro_wake_word.stop:
on_timer_finished:
- script.execute: stop_wake_word
- voice_assistant.stop:
- micro_wake_word.stop:
- wait_until:
not:
microphone.is_capturing:
@@ -237,7 +215,7 @@ light:
default_transition_length: 0s
chipset: SK6812
num_leds: 1
channel_colors: GRB
rgb_order: grb
effects:
- pulse:
name: "Slow Pulse"
@@ -257,8 +235,7 @@ script:
then:
- if:
condition:
- lambda: |-
return id(wake_word_engine_location).current_option() == "On device";
- lambda: return id(wake_word_engine_location).state == "On device";
- switch.is_on: use_listen_light
then:
- light.turn_on:
@@ -271,8 +248,7 @@ script:
else:
- if:
condition:
- lambda: |-
return id(wake_word_engine_location).current_option() == "On device";
- lambda: return id(wake_word_engine_location).state != "On device";
- switch.is_on: use_listen_light
then:
- light.turn_on:
@@ -286,41 +262,27 @@ script:
- light.turn_off: led
- id: start_wake_word
then:
- wait_until:
and:
- media_player.is_idle:
- speaker.is_stopped:
- if:
condition:
and:
- not:
- voice_assistant.is_running:
- lambda: |-
return id(wake_word_engine_location).current_option() == "On device";
then:
- lambda: id(va).set_use_wake_word(false);
- micro_wake_word.start:
- if:
condition:
and:
- not:
- voice_assistant.is_running:
- lambda: |-
return id(wake_word_engine_location).current_option() == "In Home Assistant";
then:
- lambda: id(va).set_use_wake_word(true);
- voice_assistant.start_continuous:
- id: stop_wake_word
then:
- if:
condition:
lambda: |-
return id(wake_word_engine_location).current_option() == "In Home Assistant";
then:
- lambda: id(va).set_use_wake_word(false);
- voice_assistant.stop:
- if:
condition:
lambda: |-
return id(wake_word_engine_location).current_option() == "On device";
lambda: return id(wake_word_engine_location).state == "On device";
then:
- voice_assistant.stop
- micro_wake_word.stop:
- delay: 1s
- script.execute: reset_led
- script.wait: reset_led
- micro_wake_word.start:
else:
- if:
condition: voice_assistant.is_running
then:
- voice_assistant.stop:
- script.execute: reset_led
- voice_assistant.start_continuous:
switch:
- platform: template
@@ -380,7 +342,7 @@ select:
condition:
lambda: return x == "In Home Assistant";
then:
- micro_wake_word.stop:
- micro_wake_word.stop
- delay: 500ms
- lambda: id(va).set_use_wake_word(true);
- voice_assistant.start_continuous:
@@ -389,9 +351,9 @@ select:
lambda: return x == "On device";
then:
- lambda: id(va).set_use_wake_word(false);
- voice_assistant.stop:
- voice_assistant.stop
- delay: 500ms
- micro_wake_word.start:
- micro_wake_word.start
micro_wake_word:
on_wake_word_detected:
@@ -399,9 +361,4 @@ micro_wake_word:
wake_word: !lambda return wake_word;
vad:
models:
- model: okay_nabu
id: okay_nabu
- model: hey_mycroft
id: hey_mycroft
- model: hey_jarvis
id: hey_jarvis
- model: ${micro_wake_word_model}
+19 -30
View File
@@ -1,5 +1,3 @@
# Source: https://github.com/wildekek/rdtech-esphome
substitutions:
name: "riden-labornetzteil-18a"
friendly_name: "Riden Labornetzteil 18A"
@@ -10,7 +8,7 @@ substitutions:
device_friendly_name: "Riden RD6018"
device_description: "Monitor and control a RD6018 PSU via WiFi"
time_timezone: "Europe/Berlin"
# Model specific settings (Don't change these!)
RD6006_voltage_maximum: "60"
RD6006_voltage_accuracy: "2"
@@ -18,17 +16,13 @@ substitutions:
RD6006_current_maximum: "6"
RD6006_current_accuracy: "3"
RD6006_current_multiplier: "0.001"
RD6006_power_accuracy: "2"
RD6006_power_multiplier: "0.01"
RD6006P_voltage_maximum: "60"
RD6006P_voltage_accuracy: "3"
RD6006P_voltage_multiplier: "0.001"
RD6006P_current_maximum: "6"
RD6006P_current_accuracy: "4"
RD6006P_current_multiplier: "0.0001"
RD6006P_power_accuracy: "3"
RD6006P_power_multiplier: "0.001"
RD6012_voltage_maximum: "60"
RD6012_voltage_accuracy: "2"
@@ -36,8 +30,6 @@ substitutions:
RD6012_current_maximum: "12"
RD6012_current_accuracy: "2"
RD6012_current_multiplier: "0.01"
RD6012_power_accuracy: "2"
RD6012_power_multiplier: "0.01"
RD6018_voltage_maximum: "60"
RD6018_voltage_accuracy: "2"
@@ -45,8 +37,6 @@ substitutions:
RD6018_current_maximum: "18"
RD6018_current_accuracy: "2"
RD6018_current_multiplier: "0.01"
RD6018_power_accuracy: "2"
RD6018_power_multiplier: "0.01"
esphome:
name: $device_name
@@ -55,7 +45,7 @@ esphome:
name_add_mac_suffix: false
project:
name: "wildekek.rd6006-controller"
version: "1.5"
version: "1.4.1"
esp8266:
board: esp12e
@@ -66,7 +56,7 @@ network:
wifi:
ssid: "Voltage-legacy"
password: !secret voltage_legacy_psk
use_address: riden-labornetzteil-18a.home
#use_address: riden-labornetzteil-18a.home
power_save_mode: high
fast_connect: on
min_auth_mode: WPA2
@@ -86,12 +76,12 @@ logger:
# Enable Home Assistant API
api:
encryption:
encryption:
key: !secret apikey
ota:
platform: esphome
encryption:
password: !secret ota
# Enable status LED
status_led:
@@ -162,9 +152,7 @@ sensor:
on_value:
then:
- lambda: |-
id(model_name).publish_state(
std::to_string(static_cast<uint16_t>(x))
);
id(model_name).publish_state(value_accuracy_to_string(x, 0));
- platform: modbus_controller
name: "Serial Number"
@@ -176,7 +164,7 @@ sensor:
register_type: holding
value_type: U_DWORD
accuracy_decimals: 0
- platform: modbus_controller
modbus_controller_id: powersupply
address: 3
@@ -225,9 +213,9 @@ sensor:
unit_of_measurement: "W"
register_type: holding
value_type: U_DWORD
accuracy_decimals: ${${model}_power_accuracy}
accuracy_decimals: 2
filters:
- multiply: ${${model}_power_multiplier}
- multiply: 0.01
- platform: modbus_controller
modbus_controller_id: powersupply
@@ -238,9 +226,9 @@ sensor:
unit_of_measurement: "V"
register_type: holding
value_type: U_WORD
accuracy_decimals: 2
accuracy_decimals: ${${model}_voltage_accuracy}
filters:
- multiply: 0.01
- multiply: ${${model}_voltage_multiplier}
- platform: modbus_controller
modbus_controller_id: powersupply
@@ -278,10 +266,10 @@ sensor:
unit_of_measurement: "V"
register_type: holding
value_type: U_WORD
accuracy_decimals: 2
accuracy_decimals: ${${model}_voltage_accuracy}
filters:
- multiply: 0.01
- multiply: ${${model}_voltage_multiplier}
- platform: modbus_controller
name: "Temperature"
device_class: temperature
@@ -291,7 +279,7 @@ sensor:
address: 4
value_type: S_DWORD
unit_of_measurement: "°C"
- platform: modbus_controller
name: "Temperature external"
state_class: measurement
@@ -301,7 +289,7 @@ sensor:
value_type: S_DWORD
device_class: temperature
unit_of_measurement: "°C"
- platform: wifi_signal
name: "Wi-Fi Signal"
disabled_by_default: True
@@ -420,7 +408,7 @@ number:
step: ${${model}_voltage_multiplier}
lambda: !lambda return x * ${${model}_voltage_multiplier};
write_lambda: !lambda return x * (1/${${model}_voltage_multiplier});
- platform: modbus_controller
modbus_controller_id: powersupply
name: "Output current"
@@ -449,6 +437,7 @@ number:
lambda: !lambda return x * ${${model}_voltage_multiplier};
write_lambda: !lambda return x * (1/${${model}_voltage_multiplier});
- platform: modbus_controller
modbus_controller_id: powersupply
name: "Over Current Protection"
+18 -30
View File
@@ -1,5 +1,3 @@
# Source: https://github.com/wildekek/rdtech-esphome
substitutions:
name: "riden-labornetzteil-6a"
friendly_name: "Riden Labornetzteil 6A"
@@ -10,7 +8,7 @@ substitutions:
device_friendly_name: "Riden RD6006"
device_description: "Monitor and control a RD6006 PSU via WiFi"
time_timezone: "Europe/Berlin"
# Model specific settings (Don't change these!)
RD6006_voltage_maximum: "60"
RD6006_voltage_accuracy: "2"
@@ -18,17 +16,13 @@ substitutions:
RD6006_current_maximum: "6"
RD6006_current_accuracy: "3"
RD6006_current_multiplier: "0.001"
RD6006_power_accuracy: "2"
RD6006_power_multiplier: "0.01"
RD6006P_voltage_maximum: "60"
RD6006P_voltage_accuracy: "3"
RD6006P_voltage_multiplier: "0.001"
RD6006P_current_maximum: "6"
RD6006P_current_accuracy: "4"
RD6006P_current_multiplier: "0.0001"
RD6006P_power_accuracy: "3"
RD6006P_power_multiplier: "0.001"
RD6012_voltage_maximum: "60"
RD6012_voltage_accuracy: "2"
@@ -36,8 +30,6 @@ substitutions:
RD6012_current_maximum: "12"
RD6012_current_accuracy: "2"
RD6012_current_multiplier: "0.01"
RD6012_power_accuracy: "2"
RD6012_power_multiplier: "0.01"
RD6018_voltage_maximum: "60"
RD6018_voltage_accuracy: "2"
@@ -45,8 +37,6 @@ substitutions:
RD6018_current_maximum: "18"
RD6018_current_accuracy: "2"
RD6018_current_multiplier: "0.01"
RD6018_power_accuracy: "2"
RD6018_power_multiplier: "0.01"
esphome:
name: $device_name
@@ -55,7 +45,7 @@ esphome:
name_add_mac_suffix: false
project:
name: "wildekek.rd6006-controller"
version: "1.5"
version: "1.4.1"
esp8266:
board: esp12e
@@ -66,7 +56,7 @@ network:
wifi:
ssid: "Voltage-legacy"
password: !secret voltage_legacy_psk
use_address: riden-labornetzteil-6a.home
#use_address: riden-labornetzteil-6a.home
power_save_mode: high
fast_connect: on
min_auth_mode: WPA2
@@ -86,12 +76,12 @@ logger:
# Enable Home Assistant API
api:
encryption:
encryption:
key: !secret apikey
ota:
platform: esphome
encryption:
password: !secret ota
# Enable status LED
status_led:
@@ -162,9 +152,7 @@ sensor:
on_value:
then:
- lambda: |-
id(model_name).publish_state(
std::to_string(static_cast<uint16_t>(x))
);
id(model_name).publish_state(value_accuracy_to_string(x, 0));
- platform: modbus_controller
name: "Serial Number"
@@ -176,7 +164,7 @@ sensor:
register_type: holding
value_type: U_DWORD
accuracy_decimals: 0
- platform: modbus_controller
modbus_controller_id: powersupply
address: 3
@@ -225,9 +213,9 @@ sensor:
unit_of_measurement: "W"
register_type: holding
value_type: U_DWORD
accuracy_decimals: ${${model}_power_accuracy}
accuracy_decimals: 2
filters:
- multiply: ${${model}_power_multiplier}
- multiply: 0.01
- platform: modbus_controller
modbus_controller_id: powersupply
@@ -238,9 +226,9 @@ sensor:
unit_of_measurement: "V"
register_type: holding
value_type: U_WORD
accuracy_decimals: 2
accuracy_decimals: ${${model}_voltage_accuracy}
filters:
- multiply: 0.01
- multiply: ${${model}_voltage_multiplier}
- platform: modbus_controller
modbus_controller_id: powersupply
@@ -278,10 +266,10 @@ sensor:
unit_of_measurement: "V"
register_type: holding
value_type: U_WORD
accuracy_decimals: 2
accuracy_decimals: ${${model}_voltage_accuracy}
filters:
- multiply: 0.01
- multiply: ${${model}_voltage_multiplier}
- platform: modbus_controller
name: "Temperature"
device_class: temperature
@@ -291,7 +279,7 @@ sensor:
address: 4
value_type: S_DWORD
unit_of_measurement: "°C"
- platform: modbus_controller
name: "Temperature external"
state_class: measurement
@@ -301,7 +289,7 @@ sensor:
value_type: S_DWORD
device_class: temperature
unit_of_measurement: "°C"
- platform: wifi_signal
name: "Wi-Fi Signal"
disabled_by_default: True
@@ -420,7 +408,7 @@ number:
step: ${${model}_voltage_multiplier}
lambda: !lambda return x * ${${model}_voltage_multiplier};
write_lambda: !lambda return x * (1/${${model}_voltage_multiplier});
- platform: modbus_controller
modbus_controller_id: powersupply
name: "Output current"
+1 -3
View File
@@ -1,10 +1,8 @@
substitutions:
device_description: "ESP32-C3 server-room temperature and atmospheric pressure monitor with BMP280 sensor"
name: "serverroom"
friendly_name: "Serverraum Luft"
esphome:
comment: ${device_description}
name: ${name}
friendly_name: ${friendly_name}
name_add_mac_suffix: false
@@ -46,7 +44,7 @@ api:
ota:
platform: esphome
encryption:
password: !secret ota
# Initialize I²C
i2c:
-456
View File
@@ -1,456 +0,0 @@
# Board: ESP32-C3 Super Mini (Generic)
# Definition: definitions/boards/esp32-c3-supermini/manifest.yaml
# Based largely on https://github.com/misterblack1/HU-058_ESPHome by Adrian Black aka "Adrian's Digital Basement"
# AI slop in here
substitutions:
device_description: "ESP32 Geiger counter with radiation dose rate, accumulated dose and MAX7219 seven-segment display"
name: "sleepingroom-clock"
friendly_name: "Schlafzimmeruhr"
esphome:
comment: ${device_description}
name: ${name}
friendly_name: ${friendly_name}
name_add_mac_suffix: false
project:
name: sensor.radiation
version: "1.0"
min_version: 2022.11.0
# Template numbers and selects restore their value by publishing it, which
# does not fire their set_action, so a restored effect would show in the UI
# and do nothing. Push the lot into the component once everything is up.
on_boot:
priority: -100
then:
- lambda: |-
id(panel)->set_effect_speed(id(effect_speed).state);
id(panel)->set_effect_angle(id(effect_angle).state);
id(panel)->set_effect_hue_span(id(effect_hue_span).state);
id(panel)->set_flash_fade(id(fx_flash_fade).state);
std::string sp = id(effect_spread).current_option();
id(panel)->set_effect_spread(sp == "Per Digit" ? 1 : sp == "Per LED" ? 2 : 0);
std::string ef = id(effect_mode).current_option();
id(panel)->set_effect(ef == "Color Cycle" ? 1 : ef == "Flash" ? 2 : 0);
esp32:
variant: esp32c3
flash_size: 4MB
framework:
type: esp-idf
# Enable logging
logger:
# Enable Home Assistant API
api:
encryption:
key: !secret apikey
actions:
- action: show_seconds
variables:
duration: int
then:
- lambda: id(panel)->show_seconds(duration);
# Right aligned digits with an optional unit in the rightmost position, so
# 78F and -5C both read correctly. A unit of C or F also lights the degree
# mark. Pass an empty unit to give the number all four positions. There is
# no decimal point on the panel, so round before sending.
- action: show_number
variables:
value: int
unit: string
duration: int
then:
- lambda: id(panel)->show_number(value, unit, duration);
# Every populated LED, white, for a few seconds, then back to the time.
# It ignores color, effects, brightness and the light being off. Duration
# is milliseconds, and 3000 is the button below.
- action: lamp_test
variables:
duration: int
then:
- lambda: id(panel)->lamp_test(duration);
# Per digit color. Digit 0 is the leftmost and 3 the rightmost, and -1
# sets all four at once. Components are 0 to 255 and are not rescaled
# against each other, so a digit can be dimmer than its neighbors as well
# as a different hue. Each digit carries its own annunciator, so the colon
# takes the color of the hour ones digit and the AM mark the hour tens.
# This is runtime state and is not remembered across a reboot.
- action: set_digit_color
variables:
digit: int
red: int
green: int
blue: int
then:
- lambda: |-
id(panel)->set_digit_color(digit, red / 255.0f, green / 255.0f, blue / 255.0f);
# Hand the whole panel back to the Display light, gradients included.
- action: clear_digit_colors
then:
- lambda: id(panel)->clear_digit_colors();
# One LED, by the id on the board layout map. See docs/led-layout.md.
- action: set_position_color
variables:
position: int
red: int
green: int
blue: int
then:
- lambda: |-
id(panel)->set_position_color(position, red / 255.0f, green / 255.0f,
blue / 255.0f);
# A linear ramp between two colors across the whole panel. Angle is in
# degrees, 0 left to right and 90 top to bottom, so -45 runs from the
# bottom left corner to the top right.
# Everything about the running effect in one call, for automations that
# want to set it up atomically rather than nudging five entities.
# mode 0 off, 1 color cycle, 2 flash. spread 0 whole panel, 1 per digit,
# 2 per LED. speed is seconds for one full cycle, which for flash is one
# complete on and off. angle is the direction the spread runs. hue_span is
# how many degrees of the color wheel the panel covers end to end.
# flash_fade is seconds per flash transition, 0 to snap.
- action: set_effect
variables:
mode: int
spread: int
speed: float
angle: float
hue_span: float
flash_fade: float
then:
# Drives the entities rather than the component, so the Home Assistant
# UI ends up showing what the panel is actually doing. Calling the
# component directly would work and leave every slider stale.
#
# Values are clamped here because a number call outside its range is
# dropped rather than clamped, which would silently ignore the whole
# setting.
- lambda: |-
id(effect_speed).make_call().set_value(clamp(speed, 0.2f, 600.0f)).perform();
id(effect_angle).make_call().set_value(clamp(angle, -180.0f, 180.0f)).perform();
id(effect_hue_span).make_call().set_value(clamp(hue_span, 0.0f, 360.0f)).perform();
id(fx_flash_fade).make_call().set_value(clamp(flash_fade, 0.0f, 30.0f)).perform();
id(effect_spread).make_call().set_option(
spread == 1 ? "Per Digit" : spread == 2 ? "Per LED" : "Whole Panel").perform();
id(effect_mode).make_call().set_option(
mode == 1 ? "Color Cycle" : mode == 2 ? "Flash" : "None").perform();
- action: set_gradient
variables:
red1: int
green1: int
blue1: int
red2: int
green2: int
blue2: int
angle: float
then:
- lambda: |-
id(panel)->set_gradient(red1 / 255.0f, green1 / 255.0f, blue1 / 255.0f,
red2 / 255.0f, green2 / 255.0f, blue2 / 255.0f, angle);
ota:
platform: esphome
encryption:
network:
enable_ipv6: true
wifi:
ssid: "Voltage-legacy"
password: !secret voltage_legacy_psk
#use_address: ${name}.home
power_save_mode: high
fast_connect: on
min_auth_mode: WPA2
# The panel uses the upper colon dot as its Wi-Fi connection indicator.
on_connect:
- lambda: id(panel)->set_online(true);
on_disconnect:
- lambda: id(panel)->set_online(false);
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Schlafzimmeruhr Fallback Hotspot"
password: !secret fallback_psk
captive_portal:
external_components:
- source:
type: local
path: components
time:
# No timezone on this one, deliberately. Home Assistant pushes its own
# timezone to the device on every time sync, DST rules included, but only
# if this platform has no timezone of its own. Setting one here compiles
# that path out and pins the clock to whatever is written instead.
- platform: homeassistant
id: ha_time
# SNTP is the fallback for a boot with no Home Assistant. It has nowhere to
# learn a timezone from, so this one is spelled out. It is also what the
# display shows for the first few seconds of every boot, until Home
# Assistant answers. Change it if the clock moves.
#- platform: sntp
# id: sntp_time
# timezone: !secret timezone
aip33628:
id: panel
clk_pin: GPIO21 # MCU socket pin 14 (HU-058D) or 16 (HU-058/SE), driver 1
data_pin: GPIO20 # MCU socket pin 5, driver 1
clk2_pin: GPIO10 # MCU socket pin 1, driver 2
data2_pin: GPIO9 # MCU socket pin 2, driver 2
time_id: ha_time
# Power on defaults. The switches below own both after that, and they
# restore their last state, so these only matter for a first ever boot.
twelve_hour: false
blink_colon: true
# Ceiling on IS[3:0], 0 to 15. Fixed, never varied by content. The stock
# firmware ran 0xF and drew 404mA doing it. Drop this if the drivers
# run hotter than you want. See docs/display-map.md.
max_current: 15
light:
- platform: aip33628
id: display
aip33628_id: panel
name: Display
restore_mode: RESTORE_DEFAULT_ON
# Gamma is applied inside the component, because it also has to allow for
# the 2.5mA floor the drivers cannot go below. Leaving it on here as well
# would square it.
gamma_correct: 1.0
# The two front panel buttons. Nothing on the board pulls these nets up. The
# stock 8051 held them high with its own quasi-bidirectional port pullup, and
# that chip is out of the socket, so the ESP32 internal pullup is the only one
# and the lines never see 5V. Switch closed shorts to ground, hence inverted.
#
# No behavior is attached here on purpose. Home Assistant is the control
# surface, so these are just inputs it can bind to. Press and hold patterns
# belong in an automation, not in this file.
binary_sensor:
- platform: gpio
id: button_1
name: Button 1
pin:
number: GPIO8 # MCU socket pin 9, net S1, top button on the case
mode:
input: true
pullup: true
inverted: true
filters:
- delayed_on: 20ms
- delayed_off: 20ms
- platform: gpio
id: button_2
name: Button 2
pin:
number: GPIO7 # MCU socket pin 10, net S2, bottom button on the case
mode:
input: true
pullup: true
inverted: true
filters:
- delayed_on: 20ms
- delayed_off: 20ms
switch:
- platform: template
id: twelve_hour_mode
name: 12 Hour Time
optimistic: true
restore_mode: RESTORE_DEFAULT_ON
turn_on_action:
- lambda: id(panel)->set_twelve_hour(true);
turn_off_action:
- lambda: id(panel)->set_twelve_hour(false);
# Off means a steady colon, not a dark one.
- platform: template
id: colon_blink
name: Blink Colon
optimistic: true
restore_mode: RESTORE_DEFAULT_ON
turn_on_action:
- lambda: id(panel)->set_blink_colon(true);
turn_off_action:
- lambda: id(panel)->set_blink_colon(false);
button:
# Three seconds of every populated LED lit white at half brightness, then
# back to the time with the settings it had before.
- platform: template
name: Lamp Test
on_press:
- lambda: id(panel)->lamp_test(3000);
# A shortcut for the common case, and something to press by hand.
# Anything more elaborate belongs in a Home Assistant automation calling
# the api actions above.
- platform: template
name: Show Seconds
on_press:
- lambda: id(panel)->show_seconds(5000);
# A UI handle for set_digit_color, and the quickest way to see the four
# digits driven independently.
- platform: template
name: Digit Color Demo
on_press:
- lambda: |-
id(panel)->set_digit_color(0, 1.00f, 0.00f, 0.00f);
id(panel)->set_digit_color(1, 1.00f, 0.45f, 0.00f);
id(panel)->set_digit_color(2, 0.00f, 1.00f, 0.25f);
id(panel)->set_digit_color(3, 0.10f, 0.30f, 1.00f);
- platform: template
name: Clear Digit Colors
on_press:
- lambda: id(panel)->clear_digit_colors();
# Green in the bottom left corner running to yellow in the top right, which
# is the sort of thing the stock firmware did. -45 degrees is that diagonal.
- platform: template
name: Diagonal Gradient
on_press:
- lambda: |-
id(panel)->set_gradient(0.00f, 1.00f, 0.10f,
1.00f, 0.85f, 0.00f, -45.0f);
# A UI handle for the show_number action, which otherwise lives only under
# Developer Tools > Actions. Setting either entity redraws immediately and the
# panel falls back to the time ten seconds later on its own.
select:
# Effects run on the device, not in Home Assistant, so a fade stays smooth
# and keeps going if the network drops. Every entity here is a normal one,
# so an automation can drive them, or call the set_effect action to set the
# lot at once.
- platform: template
name: Effect
id: effect_mode
optimistic: true
restore_value: true
initial_option: "None"
options: ["None", "Color Cycle", "Flash"]
set_action:
- lambda: |-
std::string v = x;
id(panel)->set_effect(v == "Color Cycle" ? 1 : v == "Flash" ? 2 : 0);
# Whole Panel moves everything together. Per Digit gives each digit its own
# phase, so the color walks across the four of them. Per LED gives every
# position its own, which is the smooth sweep.
- platform: template
name: Effect Spread
id: effect_spread
optimistic: true
restore_value: true
initial_option: "Whole Panel"
options: ["Whole Panel", "Per Digit", "Per LED"]
set_action:
- lambda: |-
std::string v = x;
id(panel)->set_effect_spread(v == "Per Digit" ? 1 : v == "Per LED" ? 2 : 0);
- platform: template
name: Test Unit
id: test_unit
optimistic: true
restore_value: true
initial_option: "F"
options: ["None", "F", "C"]
set_action:
- lambda: |-
std::string u = x;
if (u == "None") u.clear();
id(panel)->show_number((int) id(test_number).state, u, 10000);
number:
# Seconds for one full cycle. For Flash this is one complete on and off.
- platform: template
name: Effect Speed
id: effect_speed
optimistic: true
restore_value: true
initial_value: 10
min_value: 0.2
max_value: 600
step: 0.2
unit_of_measurement: s
mode: box
set_action:
- lambda: id(panel)->set_effect_speed(x);
# Which way the spread runs. 0 is left to right, 90 top to bottom, 180
# right to left. -45 is the bottom left to top right diagonal and 135 is
# the other one, top right to bottom left.
- platform: template
name: Effect Angle
id: effect_angle
optimistic: true
restore_value: true
initial_value: 0
min_value: -180
max_value: 180
step: 15
unit_of_measurement: deg
mode: box
set_action:
- lambda: id(panel)->set_effect_angle(x);
# How many degrees of the color wheel the panel covers end to end. A full
# 360 packs the whole spectrum across four digits and reads as noise, so
# the useful settings are narrow. 60 is roughly red through orange, 90
# reaches yellow. 0 puts the whole panel on one color that still cycles.
# Only Color Cycle uses this, and only when Spread is not Whole Panel.
- platform: template
name: Effect Hue Span
id: effect_hue_span
optimistic: true
restore_value: true
initial_value: 90
min_value: 0
max_value: 360
step: 5
unit_of_measurement: deg
mode: box
set_action:
- lambda: id(panel)->set_effect_hue_span(x);
# Seconds each flash transition takes, independent of the flash rate. 0
# snaps on and off. 0.1 gives a quick ramp. Anything past half the Effect
# Speed is capped there, which is the point where it becomes a triangle.
- platform: template
name: Flash Fade
id: fx_flash_fade
optimistic: true
restore_value: true
initial_value: 0
min_value: 0
max_value: 30
step: 0.05
unit_of_measurement: s
mode: box
set_action:
- lambda: id(panel)->set_flash_fade(x);
- platform: template
name: Test Number
id: test_number
optimistic: true
restore_value: true
initial_value: 72
min_value: -999
max_value: 9999
step: 1
mode: box
set_action:
- lambda: |-
std::string u = id(test_unit).current_option();
if (u == "None") u.clear();
id(panel)->show_number((int) x, u, 10000);
-307
View File
@@ -1,307 +0,0 @@
#include "../energy_day_history.h"
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <type_traits>
static_assert(std::is_trivially_copyable<EnergyDayHistory>::value,
"ESPHome restore_value requires trivially copyable state");
#define CHECK(condition) \
do { \
if (!(condition)) { \
std::cerr << __FILE__ << ':' << __LINE__ << ": " #condition "\n"; \
std::exit(EXIT_FAILURE); \
} \
} while (false)
static bool near(float actual, float expected) {
return std::fabs(actual - expected) < 0.0001f;
}
static void first_zero_and_ordinary() {
EnergyDayHistory h;
CHECK(h.day() == 0);
for (int c = 0; c < 3; ++c) {
for (int hour = 0; hour < 24; ++hour) {
CHECK(!h.has_data(c, hour));
CHECK(h.value(c, hour) == 0.0f);
CHECK(h.coverage_seconds(c, hour) == 0);
}
h.observe(c, 1000.0f, 20261113, 8, 100, 1000);
CHECK(h.day() == 20261113);
CHECK(!h.has_data(c, 8)); // Lifetime totals are never bars.
CHECK(h.coverage_seconds(c, 8) == 0);
h.observe(c, 1000.0f, 20261113, 8, 110, 1010);
CHECK(h.has_data(c, 8));
CHECK(h.value(c, 8) == 0.0f);
CHECK(h.coverage_seconds(c, 8) == 10);
h.observe(c, 1000.25f, 20261113, 8, 120, 1020);
h.observe(c, 1000.75f, 20261113, 8, 130, 1030);
CHECK(near(h.value(c, 8), 0.75f));
CHECK(h.coverage_seconds(c, 8) == 30);
CHECK(!h.has_data(c, 7));
CHECK(!h.has_data(c, 9));
}
}
static void hour_boundaries() {
EnergyDayHistory h;
h.observe(0, 10.0f, 20261113, 8, 3595, 1000);
h.observe(0, 10.4f, 20261113, 9, 15, 1020);
CHECK(near(h.value(0, 8), 0.1f));
CHECK(near(h.value(0, 9), 0.3f));
CHECK(h.coverage_seconds(0, 8) == 5);
CHECK(h.coverage_seconds(0, 9) == 15);
h.observe(1, 5.0f, 20261113, 8, 3590, 1000);
h.observe(1, 5.2f, 20261113, 9, 0, 1010);
CHECK(h.has_data(1, 8));
CHECK(near(h.value(1, 8), 0.2f));
CHECK(!h.has_data(1, 9)); // No time in hour 9 has been observed yet.
CHECK(h.coverage_seconds(1, 8) == 10);
CHECK(h.coverage_seconds(1, 9) == 0);
h.observe(1, 5.2f, 20261113, 9, 10, 1020);
CHECK(h.has_data(1, 9));
CHECK(h.value(1, 9) == 0.0f);
CHECK(h.coverage_seconds(1, 9) == 10);
h.observe(2, 4.0f, 20261113, 8, 3595, 1000);
h.observe(2, 4.0f, 20261113, 9, 5, 1010);
CHECK(h.has_data(2, 8) && h.has_data(2, 9));
CHECK(h.value(2, 8) == 0.0f && h.value(2, 9) == 0.0f);
CHECK(h.coverage_seconds(2, 8) == 5 && h.coverage_seconds(2, 9) == 5);
}
static void midnight() {
EnergyDayHistory h;
h.observe(0, 10.0f, 20261231, 23, 3580, 1000);
h.observe(0, 10.1f, 20261231, 23, 3590, 1010);
h.observe(1, 20.0f, 20261231, 23, 3595, 1015);
h.observe(2, 30.0f, 20261231, 23, 3590, 1010);
h.observe(0, 10.5f, 20270101, 0, 10, 1030);
CHECK(h.day() == 20270101);
CHECK(h.coverage_seconds(0, 0) == 10);
for (int c = 0; c < 3; ++c)
CHECK(h.coverage_seconds(c, 23) == 0);
CHECK(near(h.value(0, 0), 0.2f));
CHECK(!h.has_data(0, 23));
// Baselines for the other channels survive the shared histogram reset.
h.observe(1, 20.6f, 20270101, 0, 15, 1035);
CHECK(near(h.value(1, 0), 0.45f));
CHECK(h.coverage_seconds(1, 0) == 15);
CHECK(!h.has_data(1, 23));
h.observe(2, 30.0f, 20270101, 0, 0, 1020);
CHECK(!h.has_data(2, 0));
CHECK(h.coverage_seconds(2, 0) == 0);
h.observe(2, 30.0f, 20270101, 0, 10, 1030);
CHECK(h.has_data(2, 0));
CHECK(h.value(2, 0) == 0.0f);
CHECK(h.coverage_seconds(2, 0) == 10);
}
static void restored_copy() {
EnergyDayHistory original;
original.observe(0, 100.0f, 20261113, 10, 100, 1000);
original.observe(0, 100.5f, 20261113, 10, 110, 1010);
EnergyDayHistory restored = original;
restored.observe(0, 100.75f, 20261113, 10, 120, 1020);
CHECK(near(restored.value(0, 10), 0.75f));
CHECK(near(original.value(0, 10), 0.5f));
CHECK(restored.coverage_seconds(0, 10) == 20);
CHECK(original.coverage_seconds(0, 10) == 10);
original.observe(1, 200.0f, 20261113, 23, 3590, 2000);
restored = original;
restored.observe(1, 200.4f, 20261114, 0, 10, 2020);
CHECK(near(restored.value(1, 0), 0.2f));
CHECK(!restored.has_data(0, 10));
CHECK(restored.coverage_seconds(0, 10) == 0);
CHECK(restored.coverage_seconds(1, 0) == 10);
}
static void disconnected_and_invalid_totals() {
const float bad[] = {std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity(), -1.0f};
for (float total : bad) {
EnergyDayHistory h;
h.observe(0, 10.0f, 20261113, 8, 100, 1000);
h.observe(1, 20.0f, 20261113, 8, 100, 1000);
h.observe(0, total, 20261113, 8, 110, 1010);
h.observe(0, 12.0f, 20261113, 8, 120, 1020);
CHECK(!h.has_data(0, 8));
CHECK(h.coverage_seconds(0, 8) == 0);
h.observe(0, 12.25f, 20261113, 8, 130, 1030);
CHECK(near(h.value(0, 8), 0.25f));
h.observe(1, 20.5f, 20261113, 8, 130, 1030);
CHECK(near(h.value(1, 8), 0.5f));
h.observe(0, total, 20261113, 8, 140, 1040);
CHECK(near(h.value(0, 8), 0.25f)); // Existing data is preserved.
CHECK(h.coverage_seconds(0, 8) == 10);
CHECK(h.coverage_seconds(1, 8) == 30);
}
}
static void gaps_and_counter_reset() {
EnergyDayHistory h;
h.observe(0, 10.0f, 20261113, 8, 3400, 1000);
h.observe(0, 11.0f, 20261113, 9, 101, 1301);
CHECK(!h.has_data(0, 8) && !h.has_data(0, 9));
CHECK(h.coverage_seconds(0, 8) == 0 && h.coverage_seconds(0, 9) == 0);
h.observe(0, 11.25f, 20261113, 9, 111, 1311);
CHECK(near(h.value(0, 9), 0.25f));
h.observe(0, 0.0f, 20261113, 9, 121, 1321);
CHECK(near(h.value(0, 9), 0.25f));
CHECK(h.coverage_seconds(0, 9) == 10);
h.observe(0, 0.5f, 20261113, 9, 131, 1331);
CHECK(near(h.value(0, 9), 0.75f));
CHECK(h.coverage_seconds(0, 9) == 20);
h.observe(1, 5.0f, 20261113, 8, 100, 1000);
h.observe(1, 5.5f, 20261113, 8, 400, 1300);
CHECK(near(h.value(1, 8), 0.5f)); // Exactly 300 seconds is valid.
CHECK(h.coverage_seconds(1, 8) == 300);
h.observe(2, 5.0f, 20261113, 23, 3590, 1000);
h.observe(2, 9.0f, 20261114, 0, 291, 1301);
CHECK(h.day() == 20261114);
CHECK(!h.has_data(2, 0) && !h.has_data(2, 23));
CHECK(h.coverage_seconds(1, 8) == 0);
CHECK(h.coverage_seconds(2, 0) == 0 && h.coverage_seconds(2, 23) == 0);
}
static void clock_rewind() {
for (uint32_t timestamp : {1000u, 990u}) {
EnergyDayHistory h;
h.observe(0, 10.0f, 20261113, 8, 100, 1000);
h.observe(0, 11.0f, 20261113, 8, 90, timestamp);
CHECK(!h.has_data(0, 8));
CHECK(h.coverage_seconds(0, 8) == 0);
h.observe(0, 11.25f, 20261113, 8, 100, timestamp + 10);
CHECK(near(h.value(0, 8), 0.25f));
CHECK(h.coverage_seconds(0, 8) == 10);
}
EnergyDayHistory h;
h.observe(0, 10.0f, 20261113, 8, 100, 1000);
h.observe(0, 11.0f, 20261113, 8, 90, 1010); // Inconsistent local clock.
CHECK(!h.has_data(0, 8));
CHECK(h.coverage_seconds(0, 8) == 0);
h.observe(0, 11.25f, 20261113, 8, 100, 1020);
CHECK(near(h.value(0, 8), 0.25f));
CHECK(h.coverage_seconds(0, 8) == 10);
}
static void dst() {
EnergyDayHistory fallback;
fallback.observe(0, 10.0f, 20261025, 2, 3580, 1000);
fallback.observe(0, 10.1f, 20261025, 2, 3590, 1010);
fallback.observe(0, 10.5f, 20261025, 2, 10, 1030);
CHECK(near(fallback.value(0, 2), 0.5f));
CHECK(fallback.coverage_seconds(0, 2) == 30);
CHECK(!fallback.has_data(0, 1) && !fallback.has_data(0, 3));
EnergyDayHistory spring;
spring.observe(0, 10.0f, 20260329, 1, 3595, 1000);
spring.observe(0, 10.4f, 20260329, 3, 15, 1020);
CHECK(near(spring.value(0, 1), 0.1f));
CHECK(!spring.has_data(0, 2));
CHECK(near(spring.value(0, 3), 0.3f));
CHECK(spring.coverage_seconds(0, 1) == 5);
CHECK(spring.coverage_seconds(0, 2) == 0);
CHECK(spring.coverage_seconds(0, 3) == 15);
// A fully observed repeated hour contains two actual hours, not a capped 3600s.
EnergyDayHistory repeated;
for (int elapsed = 0; elapsed <= 7200; elapsed += 300) {
repeated.observe(0, 10.0f, 20261025, elapsed < 7200 ? 2 : 3,
elapsed % 3600, 1000 + elapsed);
if (elapsed == 3600)
CHECK(repeated.coverage_seconds(0, 2) == 3600);
}
CHECK(repeated.coverage_seconds(0, 2) == 7200);
CHECK(repeated.coverage_seconds(0, 3) == 0);
}
static void invalid_inputs() {
EnergyDayHistory h;
for (int c : {-1, 3, 100}) {
h.observe(c, 10.0f, 20261113, 8, 100, 1000);
CHECK(!h.has_data(c, 8) && h.value(c, 8) == 0.0f);
CHECK(h.coverage_seconds(c, 8) == 0);
}
const uint32_t bad_days[] = {0, 20260001, 20261301, 20261100, 20261131,
20260229, 19000229, 100000101};
for (uint32_t day : bad_days)
h.observe(0, 10.0f, day, 8, 100, 1000);
for (int hour : {-1, 24, 100}) {
h.observe(0, 10.0f, 20261113, hour, 100, 1000);
CHECK(!h.has_data(0, hour) && h.value(0, hour) == 0.0f);
CHECK(h.coverage_seconds(0, hour) == 0);
}
for (int seconds : {-1, 3600, 10000})
h.observe(0, 10.0f, 20261113, 8, seconds, 1000);
CHECK(h.day() == 0);
h.observe(0, 10.0f, 20000229, 8, 100, 1000);
CHECK(h.day() == 20000229);
CHECK(!h.has_data(0, 8));
// Bad clock samples must not change the established baseline or day.
h.observe(0, 100.0f, 20261131, 8, 105, 1005);
h.observe(0, 100.0f, 20261113, 24, 105, 1005);
h.observe(0, 100.0f, 20261113, 8, -1, 1005);
CHECK(h.day() == 20000229);
h.observe(0, 10.25f, 20000229, 8, 110, 1010);
CHECK(near(h.value(0, 8), 0.25f));
CHECK(h.coverage_seconds(0, 8) == 10);
}
static void explicit_invalidation() {
EnergyDayHistory h;
h.invalidate(0);
CHECK(h.day() == 0);
CHECK(h.coverage_seconds(0, 8) == 0);
for (int c = 0; c < 3; ++c) {
h.observe(c, 10.0f, 20261113, 8, 100, 1000);
h.observe(c, 10.25f, 20261113, 8, 110, 1010);
}
h.invalidate(0);
h.invalidate(0); // Repeated invalidations are harmless.
CHECK(h.day() == 20261113);
CHECK(h.has_data(0, 8));
CHECK(near(h.value(0, 8), 0.25f));
CHECK(h.coverage_seconds(0, 8) == 10);
h.observe(0, 20.0f, 20261113, 8, 120, 1020);
CHECK(near(h.value(0, 8), 0.25f)); // First fresh receipt only rebaselines.
CHECK(h.coverage_seconds(0, 8) == 10);
h.observe(0, 20.5f, 20261113, 8, 130, 1030);
CHECK(near(h.value(0, 8), 0.75f));
CHECK(h.coverage_seconds(0, 8) == 20);
for (int c : {-1, 3, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()}) {
h.invalidate(c);
CHECK(h.coverage_seconds(c, 8) == 0);
}
for (int c = 1; c < 3; ++c) {
h.observe(c, 10.5f, 20261113, 8, 120, 1020);
CHECK(near(h.value(c, 8), 0.5f)); // Other channel baselines are untouched.
CHECK(h.coverage_seconds(c, 8) == 20);
}
h.observe(0, 20.5f, 20261113, 8, 140, 1040);
CHECK(near(h.value(0, 8), 0.75f));
CHECK(h.coverage_seconds(0, 8) == 30);
}
int main() {
first_zero_and_ordinary();
hour_boundaries();
midnight();
restored_copy();
disconnected_and_invalid_totals();
gaps_and_counter_reset();
clock_rewind();
dst();
invalid_inputs();
explicit_invalidation();
std::cout << "All 10 energy day history test groups passed.\n";
}
-321
View File
@@ -1,321 +0,0 @@
"""Focused slideshow regressions; run: python3 esphome/tests/slideshow_test.py.
Requires PyYAML and g++. Only the configuration itself is read, never secrets.
The native harness executes the actual YAML lambdas, not Python translations.
"""
from pathlib import Path
import subprocess
import tempfile
import unittest
import yaml
class ConfigLoader(yaml.SafeLoader):
pass
ConfigLoader.add_constructor("!secret", lambda loader, node: "<secret>")
ConfigLoader.add_constructor("!lambda", lambda loader, node: loader.construct_scalar(node))
CONFIG = Path(__file__).resolve().parents[1] / "energymonitor.yaml"
FIELDS = (
"page_index", "page_one_gauge_view", "device_usage_view",
"clock_digital_view", "internet_view", "climate_graph_view",
)
# State order follows FIELDS; a view's identity ignores other pages' memories.
DEFAULT = (0, 1, 0, 0, 0, 0)
VIEWS = (
(0, 1), (0, 0), (1, 0), (1, 1), (2, 0), (2, 1),
(3, 0), (3, 1), (3, 2), (4, 0), (4, 1),
)
SUBPAGE_FIELD = (1, 2, 3, 4, 5)
MANUAL = ("show_previous_page", "toggle_page_mode", "show_next_page")
def by_id(config, section, name):
return next(item for item in config[section] if item.get("id") == name)
def view(state):
return state[0], state[SUBPAGE_FIELD[state[0]]]
def state_for(current_view):
state = list(DEFAULT)
page, subpage = current_view
state[0] = page
state[SUBPAGE_FIELD[page]] = subpage
return tuple(state)
class SlideshowTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.config = yaml.load(CONFIG.read_text(), Loader=ConfigLoader)
cls.scripts = {item["id"]: item for item in cls.config["script"]}
cls.worker = cls.scripts["slideshow_worker"]
cls.loop = cls.worker["then"][0]["while"]
cls.interval = by_id(cls.config, "number", "slideshow_interval")
cls.scope = by_id(cls.config, "select", "slideshow_scope")
cls.switch = by_id(cls.config, "switch", "slideshow_enabled")
cls.all_views = cls.scope["initial_option"]
temporary = tempfile.TemporaryDirectory(prefix="slideshow-test-")
cls.addClassCleanup(temporary.cleanup)
directory = Path(temporary.name)
cls.binary = directory / "slideshow"
source = directory / "slideshow.cpp"
globals_by_id = {item["id"]: item for item in cls.config["globals"]}
declarations = "\n".join(
f"{globals_by_id[name]['type']} {name} = "
f"{globals_by_id[name]['initial_value']};"
for name in FIELDS
)
functions = [
"void advance_slideshow() {\n"
+ cls.scripts["advance_slideshow"]["then"][0]["lambda"] + "\n}",
"uint32_t slideshow_delay() {\n"
+ cls.loop["then"][0]["delay"] + "\n}",
]
for name in MANUAL:
functions.append(
f"void {name}() {{\n"
+ cls.scripts[name]["then"][1]["lambda"] + "\n}"
)
source.write_text(
"#include <cmath>\n#include <cstdint>\n#include <iostream>\n"
"#include <string>\n#define id(name) name\n"
+ declarations
+ "\nstruct { float state; } slideshow_interval;\n"
+ "struct { std::string option;\n"
+ " const std::string &current_option() const { return option; }\n"
+ "} slideshow_scope;\n"
+ "\n".join(functions)
+ r'''
void print_state() {
std::cout << page_index << ' ' << page_one_gauge_view << ' '
<< device_usage_view << ' ' << clock_digital_view << ' '
<< internet_view << ' ' << climate_graph_view << '\n';
}
int main(int argc, char **argv) {
if (argc != 4) return 2;
const std::string action = argv[1];
const int steps = std::stoi(argv[2]);
slideshow_scope.option = argv[3];
if (action == "delay") {
std::string seconds;
std::cin >> seconds;
slideshow_interval.state = std::stof(seconds);
std::cout << slideshow_delay() << '\n';
return 0;
}
if (action != "defaults") {
std::cin >> page_index >> page_one_gauge_view >> device_usage_view
>> clock_digital_view >> internet_view >> climate_graph_view;
if (!std::cin) return 3;
}
for (int i = 0; i < steps; ++i) {
if (action == "advance") advance_slideshow();
else if (action == "show_previous_page") show_previous_page();
else if (action == "toggle_page_mode") toggle_page_mode();
else if (action == "show_next_page") show_next_page();
else if (action != "defaults") return 4;
print_state();
}
}
'''
)
result = subprocess.run(
["g++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
str(source), "-o", str(cls.binary)],
capture_output=True, text=True, timeout=30,
)
if result.returncode:
raise RuntimeError("Native harness compilation failed:\n" + result.stderr)
def native(self, action, state=DEFAULT, *, steps=1, scope=None):
result = subprocess.run(
[str(self.binary), action, str(steps),
self.all_views if scope is None else scope],
input=" ".join(map(str, state)), capture_output=True, text=True,
timeout=5,
)
self.assertEqual(result.returncode, 0, result.stderr)
return [tuple(map(int, line.split())) for line in result.stdout.splitlines()]
def delay(self, seconds):
return self.native("delay", (seconds,))[0][0]
def test_default_cycle_has_exactly_eleven_distinct_views(self):
initial = self.native("defaults")[0]
self.assertEqual(initial, DEFAULT)
self.assertEqual(self.all_views, "Alle Ansichten")
cycle = [initial] + self.native("advance", initial, steps=11)
self.assertEqual(tuple(map(view, cycle)), VIEWS + (VIEWS[0],))
self.assertEqual(len(set(map(view, cycle[:-1]))), 11)
self.assertEqual(view(cycle[-1]), view(initial))
def test_full_cycle_from_every_view_wraps_once(self):
for offset, current in enumerate(VIEWS):
with self.subTest(start=current):
initial = state_for(current)
cycle = [initial] + self.native("advance", initial, steps=11)
expected = tuple(VIEWS[(offset + step) % 11] for step in range(12))
self.assertEqual(tuple(map(view, cycle)), expected)
self.assertEqual(len(set(map(view, cycle[:-1]))), 11)
self.assertEqual(sum(view(state) == current for state in cycle[1:]), 1)
self.assertEqual(sum(
cycle[i][0] == 4 and cycle[i + 1][0] == 0
for i in range(11)
), 1)
def test_entering_each_main_page_resets_stale_subpage(self):
# Every remembered page starts on its last subpage, not its first.
stale = (0, 0, 1, 1, 2, 1)
first_subpages = (1, 0, 0, 0, 0)
for destination in range(5):
with self.subTest(destination=destination):
initial = list(stale)
initial[0] = (destination - 1) % 5
actual = self.native("advance", initial)[0]
expected = list(initial)
expected[0] = destination
expected[SUBPAGE_FIELD[destination]] = first_subpages[destination]
self.assertEqual(actual, tuple(expected))
def test_main_pages_only_wraps_five_and_preserves_all_flags(self):
for flags in (DEFAULT[1:], (0, 1, 1, 2, 1)):
for page in range(5):
with self.subTest(page=page, flags=flags):
initial = (page,) + flags
cycle = [initial] + self.native(
"advance", initial, steps=5, scope="Nur Hauptseiten"
)
self.assertEqual([state[0] for state in cycle],
[(page + step) % 5 for step in range(6)])
self.assertEqual(len({state[0] for state in cycle[:-1]}), 5)
self.assertTrue(all(state[1:] == flags for state in cycle))
self.assertEqual(cycle[-1], initial)
def test_current_subpage_continues_without_reset_on_enable(self):
# Declarative enable/worker tests below prove there is no pre-delay action;
# these native checks prove the first eventual tick continues each view.
for index, current in enumerate(VIEWS):
with self.subTest(current=current):
initial = state_for(current)
self.assertEqual(self.delay(self.interval["initial_value"]), 15000)
actual = self.native("advance", initial)[0]
self.assertEqual(view(actual), VIEWS[(index + 1) % 11])
def test_delay_default_bounds_and_nan_fallback(self):
for seconds, milliseconds in (
(self.interval["initial_value"], 15000),
(-100, 5000), (0, 5000), (4.999, 5000), (5, 5000),
(42, 42000), (300, 300000), (300.001, 300000), (9999, 300000),
("nan", 15000), ("inf", 15000), ("-inf", 15000),
):
with self.subTest(seconds=seconds):
self.assertEqual(self.delay(seconds), milliseconds)
def test_interval_and_scope_configuration(self):
for key, expected in {
"platform": "template", "min_value": 5, "max_value": 300,
"step": 5, "initial_value": 15, "unit_of_measurement": "s",
"optimistic": True, "restore_value": True,
}.items():
self.assertEqual(self.interval[key], expected, key)
self.assertEqual(self.scope["options"], ["Alle Ansichten", "Nur Hauptseiten"])
self.assertEqual(self.scope["initial_option"], "Alle Ansichten")
self.assertIs(self.scope["optimistic"], True)
self.assertIs(self.scope["restore_value"], True)
def test_switch_is_optimistic_always_off_and_only_starts_or_stops_worker(self):
self.assertEqual(self.switch["platform"], "template")
self.assertIs(self.switch["optimistic"], True)
self.assertEqual(self.switch["restore_mode"], "ALWAYS_OFF")
self.assertEqual(self.switch["on_turn_on"],
[{"script.execute": "slideshow_worker"}])
self.assertEqual(self.switch["on_turn_off"],
[{"script.stop": "slideshow_worker"}])
self.assertNotIn("turn_on_action", self.switch)
self.assertNotIn("turn_off_action", self.switch)
def test_worker_restarts_delays_first_then_guards_advance(self):
self.assertEqual(self.worker["mode"], "restart")
self.assertEqual(len(self.worker["then"]), 1)
self.assertEqual(set(self.worker["then"][0]), {"while"})
self.assertEqual(set(self.loop), {"condition", "then"})
self.assertEqual(self.loop["condition"], {"switch.is_on": "slideshow_enabled"})
self.assertEqual(len(self.loop["then"]), 2)
self.assertEqual(set(self.loop["then"][0]), {"delay"})
self.assertIsInstance(self.loop["then"][0]["delay"], str)
self.assertEqual(self.loop["then"][1], {"if": {
"condition": {"switch.is_on": "slideshow_enabled"},
"then": [{"script.execute": "advance_slideshow"}],
}})
def test_number_and_select_restart_only_when_running(self):
for entity in (self.interval, self.scope):
with self.subTest(entity=entity["id"]):
self.assertEqual(entity["on_value"], [{"if": {
"condition": {"switch.is_on": "slideshow_enabled"},
"then": [{"script.execute": "slideshow_worker"}],
}}])
def test_advancement_refreshes_without_manual_navigation(self):
actions = self.scripts["advance_slideshow"]["then"]
self.assertEqual(len(actions), 2)
self.assertEqual(set(actions[0]), {"lambda"})
self.assertEqual(actions[1], {"script.execute": "refresh_display"})
def test_manual_scripts_stop_first_then_original_action_and_refresh(self):
for name in MANUAL:
with self.subTest(script=name):
actions = self.scripts[name]["then"]
self.assertEqual(len(actions), 3)
self.assertEqual(actions[0], {"switch.turn_off": "slideshow_enabled"})
self.assertEqual(set(actions[1]), {"lambda"})
self.assertEqual(actions[2], {"script.execute": "refresh_display"})
for current in VIEWS:
initial = state_for(current)
expected = list(initial)
if name == "show_previous_page":
expected[0] = (initial[0] - 1) % 5
elif name == "show_next_page":
expected[0] = (initial[0] + 1) % 5
else:
field = SUBPAGE_FIELD[initial[0]]
expected[field] = (initial[field] + 1) % (3 if initial[0] == 3 else 2)
self.assertEqual(self.native(name, initial)[0], tuple(expected), current)
def test_hardware_and_home_assistant_buttons_share_manual_scripts(self):
routes = (
("button_left", "Zurück", "show_previous_page", "GPIO39"),
("button_middle", "Modus", "toggle_page_mode", "GPIO38"),
("button_right", "Weiter", "show_next_page", "GPIO37"),
)
for hardware_id, name, script, pin in routes:
with self.subTest(button=name):
hardware = by_id(self.config, "binary_sensor", hardware_id)
ha = next(button for button in self.config["button"] if button["name"] == name)
expected = [{"script.execute": script}]
self.assertEqual(hardware["on_press"], expected)
self.assertEqual(ha["on_press"], expected)
self.assertEqual(hardware["platform"], "gpio")
self.assertEqual(hardware["pin"]["number"], pin)
self.assertEqual(ha["platform"], "template")
def test_no_extra_slideshow_button(self):
self.assertEqual(len(self.config["button"]), 3)
self.assertEqual({button["name"] for button in self.config["button"]},
{"Zurück", "Modus", "Weiter"})
hardware = [item for item in self.config["binary_sensor"]
if item["platform"] == "gpio"]
self.assertEqual({item["id"] for item in hardware},
{"button_left", "button_middle", "button_right"})
if __name__ == "__main__":
unittest.main(verbosity=2)
-40
View File
@@ -1,40 +0,0 @@
epaper_demotivationszitat:
name: Epaper Demotivationszitat
icon: mdi:emoticon-sad-outline
options:
- "Erwarte nichts. Dann kann dich auch wenig enttäuschen."
- "Du musst nicht scheitern. Es reicht, es nie zu versuchen."
- "Der Weg ist das Ziel. Leider führt er im Kreis."
- "Auch ein Rückschritt ist Bewegung. Nur eben rückwärts."
- "Nicht jeder Tag muss gut sein. Dieser hier zum Beispiel nicht."
- "Dein Potenzial ist beeindruckend. Seine Nutzung bleibt optional."
- "Morgen wird alles besser. Wahrscheinlich aber auch nicht."
- "Motivation ist vergänglich. Frust ist zuverlässig."
- "Man kann nicht alles haben. Nicht einmal gute Laune."
- "Wenn Plan A scheitert, war Plan B vermutlich auch keine Hilfe."
- "Es ist nie zu spät, die Erwartungen zu senken."
- "Du bist nicht zu spät. Die anderen sind nur früher gescheitert."
- "Das wird schon. Nur eben nicht gut."
- "Ziele sind wichtig. Besonders wenn man sie verfehlt."
- "Die Konkurrenz schläft nicht. Du darfst trotzdem weitermachen."
- "Du gibst dein Bestes. Das erklärt einiges."
- "Jeder Fehler ist eine Lektion. Du bist bald Experte."
- "Heute ist ein neuer Tag. Die Probleme sind dieselben."
- "Erfolg braucht Geduld. Enttäuschung ist sofort verfügbar."
- "Ein kleiner Schritt für dich. Ein kaum bemerkbarer für alle anderen."
- "Wer früh aufgibt, hat länger frei."
- "Es gibt keine dummen Fragen. Nur ungünstige Zeitpunkte."
- "Deine Komfortzone vermisst dich nicht."
- "Manchmal gewinnt man. Meistens lernt man daraus."
- "Der erste Schritt ist der schwerste. Die anderen sind nur länger."
- "Arbeite hart. Vielleicht merkt es niemand."
- "Nicht aufgeben. Es könnte noch schlimmer werden."
- "Träume groß. Die Realität übernimmt den Rest."
- "Das Glas ist halb voll. Mit Problemen."
- "Jeder Tag bietet Chancen. Manche davon sind Termine."
- "Du kannst alles schaffen. Außer vielleicht heute."
- "Das Leben ist kurz. Besprechungen sind länger."
- "Mut steht am Anfang. Die Rechnung kommt später."
- "Wenn es einfach wäre, würde es jemand anders machen."
- "Deine To-do-Liste glaubt an dich. Sie muss ja nicht mitmachen."
- "Perfektion ist erreichbar. Nur nicht von hier."
-9
View File
@@ -1,12 +1,3 @@
button:
- name: Haustür öffnen
unique_id: gdoor_haustuer_oeffnen
icon: mdi:door-open
command_topic: gdoor/bus_tx
payload_press: '0200319A59A60000A1E2A1A494'
qos: 0
retain: false
sensor:
# MQTT/RTL_433 (outdoor) sensors
# Reliable sensor with good placement (good values) and good reception
-97
View File
@@ -1,97 +0,0 @@
# Display contract shared with the ESPHome calendar page: compact German labels,
# a bounded number of events, and strings sized for the e-paper layout.
CALENDAR_NAMES = {
"calendar.tkrz_kalender": "Arbeit",
"calendar.privat": "Privat",
}
DAY_NAMES = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]
MAX_ENTRIES = 8
# Reserve the right side of each row for start and end times.
MAX_TITLE_LENGTH = 22
MAX_META_LENGTH = 35
# Keep variable event text within the fixed-width e-paper agenda columns.
def shorten(value, maximum):
value = (value or "").strip()
if len(value) <= maximum:
return value
return value[: maximum - 3].rstrip() + "..."
# Convert one Home Assistant calendar event into the small JSON shape consumed
# by ESPHome, separating all-day, start-time, end-time, and metadata display data.
def compact_event(event, calendar_name):
start = event.get("start", "")
all_day = "T" not in start
end = event.get("end", "")
time = "ganzt." if all_day else start[11:16]
end_time = "" if all_day or "T" not in end else end[11:16]
location = (event.get("location") or "").split("\n")[0].strip()
meta = calendar_name
if location:
meta += " / " + location
return {
"title": shorten(event.get("summary", "Ohne Titel"), MAX_TITLE_LENGTH),
"time": time,
"end": end_time,
"meta": shorten(meta, MAX_META_LENGTH),
"all_day": int(all_day),
}
# Read the calendar.get_events response supplied by the calling template sensor
# and collect events under the date on which they should appear in the agenda.
calendar_data = data.get("calendar", {})
today = str(data.get("now", ""))[:10]
events_by_date = {}
for calendar_id, calendar in calendar_data.items():
calendar_name = CALENDAR_NAMES.get(calendar_id, calendar_id.split(".")[-1].capitalize())
for event in calendar.get("events", []):
start = event.get("start", "")
end = event.get("end", "")
event_date = start[:10]
end_date = end[:10]
# Ignore malformed or already finished entries. All-day event end dates
# are exclusive in Home Assistant; timed events ending today may still be
# active. Multi-day entries remain visible on today's date rail.
all_day = "T" not in start
if not event_date or (all_day and end_date <= today) or (not all_day and end_date < today):
continue
if event_date < today:
event_date = today
events_by_date.setdefault(event_date, []).append(
compact_event(event, calendar_name)
)
# Sort day groups and events, put all-day entries first, and cap the payload so
# deserializing it stays safe on the ESP32 without PSRAM.
entries = []
entry_count = 0
for date in sorted(events_by_date):
if entry_count >= MAX_ENTRIES:
break
events = events_by_date[date]
events.sort(key=lambda item: (item["all_day"] == 0, item["time"]))
remaining = MAX_ENTRIES - entry_count
events = events[:remaining]
entry_count += len(events)
parsed_date = dt_util.parse_datetime(date)
entries.append(
{
"day": parsed_date.day,
"weekday": DAY_NAMES[parsed_date.weekday()],
"today": int(date == today),
"events": events,
}
)
# Return only the normalized agenda payload to the Home Assistant template sensor.
output["entries"] = entries
+9 -13
View File
@@ -4,37 +4,33 @@
- 'time'
- 'date'
# SNMP (VyOS) cumulative traffic counters; one octet is one byte.
# SNMP (Juniper) router traffic sensor
- platform: snmp
name: snmp_wan_in
unique_id: '3303381540758'
host: !secret router_ip
community: !secret router_community
# baseoid: .1.3.6.1.2.1.31.1.1.1.6.511
# baseoid: .1.3.6.1.2.1.2.2.1.10.12
baseoid: .1.3.6.1.2.1.31.1.1.1.6.12 # IF-MIB::ifHCInOctets.12
baseoid: .1.3.6.1.2.1.31.1.1.1.6.511
version: 2c
unit_of_measurement: "B"
unit_of_measurement: "Octets"
- platform: snmp
name: snmp_wan_out
unique_id: '1573258703922'
host: !secret router_ip
community: !secret router_community
# baseoid: .1.3.6.1.2.1.31.1.1.1.10.511
# baseoid: .1.3.6.1.2.1.2.2.1.16.12
baseoid: .1.3.6.1.2.1.31.1.1.1.10.12 # IF-MIB::ifHCOutOctets.12
baseoid: .1.3.6.1.2.1.31.1.1.1.10.511
version: 2c
unit_of_measurement: "B"
unit_of_measurement: "Octets"
- platform: derivative
source: sensor.snmp_wan_in
unit_time: s
unit: B/s
unit: B
name: wan_in_derivative
- platform: derivative
source: sensor.snmp_wan_out
unit_time: s
unit: B/s
unit: B
name: wan_out_derivative
- platform: statistics
@@ -42,13 +38,13 @@
unique_id: '9081721471264'
state_characteristic: mean
entity_id: sensor.internet_speed_in
sampling_size: 2
sampling_size: 10
- platform: statistics
name: 'WAN Traffic Out'
unique_id: '8688955223027'
state_characteristic: mean
entity_id: sensor.internet_speed_out
sampling_size: 2
sampling_size: 10
# Sensor for Riemann sum of energy import (W -> Wh)
- platform: integration
+28 -36
View File
@@ -49,11 +49,6 @@
name: Sun Setting Template
state: '{{ as_timestamp(states.sun.sun.attributes.next_setting) | timestamp_custom
(''%H:%M'') }}'
- unique_id: epaper_demotivational_quote
default_entity_id: sensor.epaper_demotivationszitat
name: Epaper Demotivationszitat
state: "{{ states('input_select.epaper_demotivationszitat') }}"
- name: "power_other"
unique_id: '5579422933393'
unit_of_measurement: "W"
@@ -78,42 +73,12 @@
{% set waschmaschine = states('sensor.waschmaschine_leistung') | float %}
{% set arcade = states('sensor.arcade_automat_leistung') | float %}
{% set spuelmaschine = states('sensor.spulmaschine_leistung') | float %}
{% set mikrowelle = states('sensor.waschetrockner_leistung') | float %}
{{ (total + solar - raumduft - keller - musik - bett - heimkino_sz - deko - schreibtisch - serverraum - heimkino_wz - spieleschrank - kuehlschrank - kaffeemaschine - waeschetrockner - waschmaschine - arcade - spuelmaschine - mikrowelle) | round(1) }}
{{ (total + solar - raumduft - keller - musik - bett - heimkino_sz - deko - schreibtisch - serverraum - heimkino_wz - spieleschrank - kuehlschrank - kaffeemaschine - waeschetrockner - waschmaschine - arcade - spuelmaschine) | round(1) }}
device_class: power
state_class: measurement
attributes:
last_reset: '1970-01-01T00:00:00+00:00'
# Compact calendar feed for the e-paper display. The actual event data lives in
# the `entries` attribute, which ESPHome reads as a text sensor.
- trigger:
- trigger: homeassistant
event: start
- trigger: time_pattern
minutes: /15
action:
- action: calendar.get_events
target:
entity_id:
- calendar.tkrz_kalender
- calendar.privat
data:
duration:
days: 14
response_variable: calendar_response
- action: python_script.epaper_calendar_data
data:
calendar: "{{ calendar_response }}"
now: "{{ now().date() }}"
response_variable: calendar_converted
sensor:
- name: Epaper Kalenderdaten
unique_id: epaper_calendar_data
state: "{{ calendar_converted.entries | count }}"
attributes:
entries: "{{ calendar_converted.entries }}"
# Shelly 3EM cumulative sensors (incl. PV)
- sensor:
# Template sensor for values of power import (active_power > 0)
@@ -180,3 +145,30 @@
unit_of_measurement: 'Mbps'
attributes:
last_reset: '1970-01-01T00:00:00+00:00'
# ── Kalender-Ereignisse für epaperframe ──
# Alle Events werden per Automation (automations.yaml) in input_text Helfer geschrieben.
# Diese template sensors lesen nur noch daraus. Das verhindert doppelte Logik und garantiert,
# dass sowohl "heute" als auch "morgen" Events mit Titeln, Uhrzeiten und Beschreibungen verfügbar sind.
- sensor:
# ── HEUTE ──
- name: "Kalender heute Privat"
unique_id: kalender_heute_privat
state: "{{ states('input_text.kalender_heute_privat') }}"
icon: mdi:calendar-account
- name: "Kalender heute Arbeit"
unique_id: kalender_heute_arbeit
state: "{{ states('input_text.kalender_heute_arbeit') }}"
icon: mdi:calendar-account
# ── MORGEN ──
- name: "Kalender morgen Privat"
unique_id: kalender_morgen_privat
state: "{{ states('input_text.kalender_morgen_privat') }}"
icon: mdi:calendar-calendar-today
- name: "Kalender morgen Arbeit"
unique_id: kalender_morgen_arbeit
state: "{{ states('input_text.kalender_morgen_arbeit') }}"
icon: mdi:calendar-calendar-today
+20
View File
@@ -0,0 +1,20 @@
kalender_heute_privat:
name: "Kalender heute Privat"
initial: "-"
icon: mdi:calendar-account
mode: text
kalender_heute_arbeit:
name: "Kalender heute Arbeit"
initial: "-"
icon: mdi:calendar-account
mode: text
kalender_morgen_privat:
name: "Kalender morgen Privat"
initial: "-"
icon: mdi:calendar-calendar-today
mode: text
kalender_morgen_arbeit:
name: "Kalender morgen Arbeit"
initial: "-"
icon: mdi:calendar-calendar-today
mode: text
+1 -14
View File
@@ -1,47 +1,34 @@
# Internet traffic: difference cumulative byte counters, not derivative rates (B/s).
# Allow counters to reset when the router/interface restarts.
# Internet traffic
internet_usage_in_monthly:
source: sensor.snmp_wan_in
name: Monthly internet traffic in
unique_id: monthly_internet_traffic_in
cycle: monthly
delta_values: false
periodically_resetting: true
internet_usage_out_monthly:
source: sensor.snmp_wan_out
name: Monthly internet traffic out
unique_id: monthly_internet_traffic_out
cycle: monthly
delta_values: false
periodically_resetting: true
internet_usage_in_daily:
source: sensor.snmp_wan_in
name: Daily internet traffic in
unique_id: daily_internet_traffic_in
cycle: daily
delta_values: false
periodically_resetting: true
internet_usage_out_daily:
source: sensor.snmp_wan_out
name: Daily internet traffic out
unique_id: daily_internet_traffic_out
cycle: daily
delta_values: false
periodically_resetting: true
internet_usage_in_hourly:
source: sensor.snmp_wan_in
name: Hourly internet traffic in
unique_id: hourly_internet_traffic_in
cycle: hourly
delta_values: false
periodically_resetting: true
internet_usage_out_hourly:
source: sensor.snmp_wan_out
name: Hourly internet traffic out
unique_id: hourly_internet_traffic_out
cycle: hourly
delta_values: false
periodically_resetting: true
# Energy
energy_import_daily: