ESPHome - конфигурация JXD-R6-E1ETH
Конфигурация контроллера JXD-R6-E1ETH (v1) для ESPHome.
Примечание
Конфигурация использует расширители портов PCA9535 (драйвер pca9554, добавлен в ESPHome
2023.11.0), синтаксис секции ota с platform: esphome (действует с ESPHome 2024.6.0),
компонент ds248x шины 1-Wire и списочную форму секции packages (поддерживается
с ESPHome 2025.6.0). Минимальная версия ESPHome для сборки примеров - 2025.6.0.
Содержание
Конфигурация
- В данной конфигурации реализованы:
Настройка Ethernet с автоматическим определением IP-адреса.
Отслеживание состояния подключения Ethernet.
Интеграция с Home Assistant без перезагрузки при отсутствии подключения.
Настройка светодиода
STAT.Настройка реле.
Определение событий от кнопки
FN.Определение событий от всех дискретных входов.
Шина 1-Wire и датчик температуры.
Измерение температуры внутри корпуса.
Измерение напряжений питания на клемме
DC INи на разъеме Ethernet.Вывод на дисплей шести страниц с переключением джойстиком.
Определение событий от джойстика и кнопок модуля дисплея.
Примечание
После загрузки контроллера и получения IP-адреса контроллер будет автоматически доступен в Home Assistant, работающем в этой же сети.
Подсказка
1# Automation type shown on the System page.
2# The automation file that includes this package overrides it.
3substitutions:
4 logic: "None"
5
6esphome:
7 name: jxd
8 name_add_mac_suffix: true # This option adds MAC address to the end of the device name
9
10esp32:
11 board: nodemcu-32s
12 framework:
13 type: esp-idf
14
15## PSRAM is installed depending on the controller configuration
16#psram:
17
18## WARNING: Disable WiFi and captive_portal if Ethernet enabled
19#wifi:
20# ssid: "***"
21# password: "***"
22#
23# # Enable fallback hotspot (captive portal) in case wifi connection fails
24# ap:
25# ssid: "JXD Fallback Hotspot"
26# password: "***"
27#
28#captive_portal:
29
30# Enable Ethernet
31ethernet:
32 id: eth
33 type: LAN8720
34 mdc_pin: GPIO23
35 mdio_pin: GPIO18
36 clk_mode: GPIO17_OUT
37 phy_addr: 1
38 power_pin: GPIO15 # Ethernet PHY hardware reset
39 on_connect:
40 - logger.log: "Ethernet connected"
41 - component.update: eth_connected
42 on_disconnect:
43 - logger.log: "Ethernet disconnected"
44 - component.update: eth_connected
45
46# Enable logging
47logger:
48
49# Enable Home Assistant API
50api:
51 # Do not reboot when no API client is connected ("No clients; rebooting").
52 # The default is 15min, which reboots the controller when it runs without Home Assistant.
53 reboot_timeout: 0s
54
55# Enable OTA firmware update
56ota:
57 - platform: esphome
58
59# Enable internal WEB server
60web_server:
61 port: 80
62
63# Enable internal I2C bus
64i2c:
65 - id: i2c_int
66 sda: 5
67 scl: 4
68 frequency: 400kHz
69 scan: true
70
71## External I2C bus
72# - id: i2c_ext
73# sda: 14
74# scl: 13
75# frequency: 400kHz
76# scan: true
77
78# UART interfaces routed to the JXM expansion module connectors
79uart:
80 - id: uart_jxm1
81 tx_pin: GPIO33
82 rx_pin: GPIO34
83 baud_rate: 115200
84 - id: uart_jxm2
85 tx_pin: GPIO32
86 rx_pin: GPIO39
87 baud_rate: 115200
88
89# Enable I2C GPIO expanders
90pca9554:
91 - id: mb_gpio_exp
92 pin_count: 16
93 address: 0x22
94 i2c_id: i2c_int
95 # Display module expander, present in the extended configuration only
96 - id: display_gpio_exp
97 pin_count: 16
98 address: 0x24
99 i2c_id: i2c_int
100
101# Enable digital outputs: STAT LED and relays
102switch:
103 - platform: gpio
104 name: "STAT LED"
105 id: stat_led
106 pin:
107 number: 2
108 mode: OUTPUT
109 inverted: false # logical 0 - green, logical 1 - red
110 - platform: gpio
111 name: "Relay 1"
112 id: relay_1
113 pin:
114 pca9554: mb_gpio_exp
115 number: 0
116 mode: OUTPUT
117 inverted: false
118 on_turn_on:
119 - component.update: oled
120 on_turn_off:
121 - component.update: oled
122 - platform: gpio
123 name: "Relay 2"
124 id: relay_2
125 pin:
126 pca9554: mb_gpio_exp
127 number: 1
128 mode: OUTPUT
129 inverted: false
130 on_turn_on:
131 - component.update: oled
132 on_turn_off:
133 - component.update: oled
134 - platform: gpio
135 name: "Relay 3"
136 id: relay_3
137 pin:
138 pca9554: mb_gpio_exp
139 number: 2
140 mode: OUTPUT
141 inverted: false
142 on_turn_on:
143 - component.update: oled
144 on_turn_off:
145 - component.update: oled
146 - platform: gpio
147 name: "Relay 4"
148 id: relay_4
149 pin:
150 pca9554: mb_gpio_exp
151 number: 3
152 mode: OUTPUT
153 inverted: false
154 on_turn_on:
155 - component.update: oled
156 on_turn_off:
157 - component.update: oled
158 - platform: gpio
159 name: "Relay 5"
160 id: relay_5
161 pin:
162 pca9554: mb_gpio_exp
163 number: 4
164 mode: OUTPUT
165 inverted: false
166 on_turn_on:
167 - component.update: oled
168 on_turn_off:
169 - component.update: oled
170 - platform: gpio
171 name: "Relay 6"
172 id: relay_6
173 pin:
174 pca9554: mb_gpio_exp
175 number: 5
176 mode: OUTPUT
177 inverted: false
178 on_turn_on:
179 - component.update: oled
180 on_turn_off:
181 - component.update: oled
182
183 # Control lines of the JXM expansion modules
184 - platform: gpio
185 name: "JXM1 reset"
186 id: jxm1_reset
187 pin:
188 pca9554: mb_gpio_exp
189 number: 6
190 mode: OUTPUT
191 inverted: false
192 - platform: gpio
193 name: "JXM1 mode"
194 id: jxm1_mode
195 pin:
196 pca9554: mb_gpio_exp
197 number: 7
198 mode: OUTPUT
199 inverted: false
200 - platform: gpio
201 name: "JXM2 reset"
202 id: jxm2_reset
203 pin:
204 pca9554: mb_gpio_exp
205 number: 14
206 mode: OUTPUT
207 inverted: false
208 - platform: gpio
209 name: "JXM2 mode"
210 id: jxm2_mode
211 pin:
212 pca9554: mb_gpio_exp
213 number: 15
214 mode: OUTPUT
215 inverted: false
216
217# Enable discrete inputs
218binary_sensor:
219 - platform: gpio
220 name: "Input 1"
221 id: input_1
222 pin:
223 pca9554: mb_gpio_exp
224 number: 8
225 inverted: false
226 on_press:
227 - component.update: oled
228 on_release:
229 - component.update: oled
230 - platform: gpio
231 name: "Input 2"
232 id: input_2
233 pin:
234 pca9554: mb_gpio_exp
235 number: 9
236 inverted: false
237 on_press:
238 - component.update: oled
239 on_release:
240 - component.update: oled
241 - platform: gpio
242 name: "Input 3"
243 id: input_3
244 pin:
245 pca9554: mb_gpio_exp
246 number: 10
247 inverted: false
248 on_press:
249 - component.update: oled
250 on_release:
251 - component.update: oled
252 - platform: gpio
253 name: "Input 4"
254 id: input_4
255 pin:
256 pca9554: mb_gpio_exp
257 number: 11
258 inverted: false
259 on_press:
260 - component.update: oled
261 on_release:
262 - component.update: oled
263 - platform: gpio
264 name: "Input 5"
265 id: input_5
266 pin:
267 pca9554: mb_gpio_exp
268 number: 12
269 inverted: false
270 on_press:
271 - component.update: oled
272 on_release:
273 - component.update: oled
274 - platform: gpio
275 name: "Input 6"
276 id: input_6
277 pin:
278 pca9554: mb_gpio_exp
279 number: 13
280 inverted: false
281 on_press:
282 - component.update: oled
283 on_release:
284 - component.update: oled
285
286 # Joystick and buttons of the display module, extended configuration only
287 - platform: gpio
288 name: "Joystick up"
289 id: joystick_up
290 pin:
291 pca9554: display_gpio_exp
292 number: 8
293 inverted: false
294 - platform: gpio
295 name: "Joystick down"
296 id: joystick_down
297 pin:
298 pca9554: display_gpio_exp
299 number: 9
300 inverted: false
301 - platform: gpio
302 name: "Joystick left"
303 id: joystick_left
304 pin:
305 pca9554: display_gpio_exp
306 number: 10
307 inverted: false
308 on_press:
309 - display.page.show_previous: oled
310 - component.update: oled
311 - platform: gpio
312 name: "Joystick right"
313 id: joystick_right
314 pin:
315 pca9554: display_gpio_exp
316 number: 11
317 inverted: false
318 on_press:
319 - display.page.show_next: oled
320 - component.update: oled
321 - platform: gpio
322 name: "Joystick enter"
323 id: joystick_enter
324 pin:
325 pca9554: display_gpio_exp
326 number: 12
327 inverted: false
328 - platform: gpio
329 name: "Button home"
330 id: button_home
331 pin:
332 pca9554: display_gpio_exp
333 number: 13
334 inverted: false
335 - platform: gpio
336 name: "Button back"
337 id: button_back
338 pin:
339 pca9554: display_gpio_exp
340 number: 14
341 inverted: false
342
343 # Ethernet link state, tracked continuously
344 - platform: template
345 name: "Ethernet connected"
346 id: eth_connected
347 lambda: |-
348 return id(eth).is_connected();
349
350# Enable the DS2482S-100 I2C-to-1-Wire bridge
351ds248x:
352 - id: onewire_hub
353 type: ds2482-100
354 address: 0x18
355 i2c_id: i2c_int
356
357# Enable the 1-Wire bus of the bridge
358one_wire:
359 - platform: ds248x
360 ds248x_id: onewire_hub
361 id: onewire_bus
362
363# 1-Wire temperature sensors: one entry per sensor connected to the bus
364sensor:
365 - platform: dallas_temp
366 one_wire_id: onewire_bus
367 address: 0xc800000c23c4c128
368 name: "Temperature"
369 id: temperature
370 update_interval: 5s # default is 60s
371
372 # Case temperature sensor on the internal I2C bus
373 - platform: tmp102
374 name: "Case temperature"
375 id: case_temperature
376 address: 0x48
377 i2c_id: i2c_int
378 update_interval: 5s
379
380 # Supply voltage measurement
381 - platform: adc
382 name: "DC IN voltage"
383 id: dc_in_voltage
384 pin: GPIO35
385 attenuation: auto
386 update_interval: 5s
387 unit_of_measurement: "V"
388 device_class: voltage
389 accuracy_decimals: 1
390 filters:
391 - multiply: 32 # 1:32 voltage divider in front of the ADC
392 - platform: adc
393 name: "PoE voltage"
394 id: poe_voltage
395 pin: GPIO37
396 attenuation: auto
397 update_interval: 5s
398 unit_of_measurement: "V"
399 device_class: voltage
400 accuracy_decimals: 1
401 filters:
402 - multiply: 32 # 1:32 voltage divider in front of the ADC
403
404# Fonts for the display
405# Terminus is a bitmap font: ter-u12n.bdf is 6x12 px, 21 characters per 128 px line.
406# Put the .bdf file into a "fonts" folder next to this configuration file.
407font:
408 - file: "fonts/ter-u12n.bdf"
409 id: terminus_12
410 size: 12
411
412# Ethernet information
413text_sensor:
414 - platform: ethernet_info
415 ip_address:
416 name: "IP Address"
417 id: eth_ip
418
419# Display module: six pages switched with the joystick
420# NOTE: the display module is installed depending on the controller configuration
421display:
422 - platform: ssd1306_i2c
423 id: oled
424 model: "SH1106 128x64"
425 address: 0x3C
426 i2c_id: i2c_int
427 update_interval: 5s
428 pages:
429 # Page 1: device name and the automation type
430 - id: page_system
431 lambda: |-
432 // Page title: dark text on a filled bar
433 it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
434 it.print(2, 0, id(terminus_12), COLOR_OFF, "System");
435 it.printf(0, 16, id(terminus_12), "Name: %s", App.get_name().c_str());
436 it.printf(0, 32, id(terminus_12), "Logic: ${logic}");
437 # Page 2: network state
438 - id: page_network
439 lambda: |-
440 // Page title: dark text on a filled bar
441 it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
442 it.print(2, 0, id(terminus_12), COLOR_OFF, "Network");
443 if (id(eth).is_connected()) {
444 it.printf(0, 16, id(terminus_12), "Ethernet: connected");
445 it.printf(0, 32, id(terminus_12), "IP: %s", id(eth_ip).state.c_str());
446 } else {
447 it.printf(0, 16, id(terminus_12), "Ethernet: no link");
448 }
449 # Page 3: temperatures
450 - id: page_sensors
451 lambda: |-
452 // Page title: dark text on a filled bar
453 it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
454 it.print(2, 0, id(terminus_12), COLOR_OFF, "Temperatures");
455 if (!std::isnan(id(temperature).state)) {
456 it.printf(0, 16, id(terminus_12), "1-Wire: %.1f C", id(temperature).state);
457 } else {
458 it.printf(0, 16, id(terminus_12), "1-Wire: ---");
459 }
460 if (!std::isnan(id(case_temperature).state)) {
461 it.printf(0, 32, id(terminus_12), "Case: %.1f C", id(case_temperature).state);
462 } else {
463 it.printf(0, 32, id(terminus_12), "Case: ---");
464 }
465 # Page 4: supply voltages
466 - id: page_power
467 lambda: |-
468 // Page title: dark text on a filled bar
469 it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
470 it.print(2, 0, id(terminus_12), COLOR_OFF, "Power supply");
471 if (!std::isnan(id(dc_in_voltage).state)) {
472 it.printf(0, 16, id(terminus_12), "DC IN: %.1f V", id(dc_in_voltage).state);
473 } else {
474 it.printf(0, 16, id(terminus_12), "DC IN: ---");
475 }
476 if (!std::isnan(id(poe_voltage).state)) {
477 it.printf(0, 32, id(terminus_12), "PoE: %.1f V", id(poe_voltage).state);
478 } else {
479 it.printf(0, 32, id(terminus_12), "PoE: ---");
480 }
481 # Page 5: relay states
482 - id: page_relays
483 lambda: |-
484 // Page title: dark text on a filled bar
485 it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
486 it.print(2, 0, id(terminus_12), COLOR_OFF, "Relays");
487 it.printf(0, 16, id(terminus_12), "1:%-3s 2:%-3s 3:%-3s",
488 id(relay_1).state ? "ON" : "OFF",
489 id(relay_2).state ? "ON" : "OFF",
490 id(relay_3).state ? "ON" : "OFF");
491 it.printf(0, 32, id(terminus_12), "4:%-3s 5:%-3s 6:%-3s",
492 id(relay_4).state ? "ON" : "OFF",
493 id(relay_5).state ? "ON" : "OFF",
494 id(relay_6).state ? "ON" : "OFF");
495 # Page 6: discrete input states
496 - id: page_inputs
497 lambda: |-
498 // Page title: dark text on a filled bar
499 it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
500 it.print(2, 0, id(terminus_12), COLOR_OFF, "Inputs");
501 it.printf(0, 16, id(terminus_12), "1:%-3s 2:%-3s 3:%-3s",
502 id(input_1).state ? "ON" : "OFF",
503 id(input_2).state ? "ON" : "OFF",
504 id(input_3).state ? "ON" : "OFF");
505 it.printf(0, 32, id(terminus_12), "4:%-3s 5:%-3s 6:%-3s",
506 id(input_4).state ? "ON" : "OFF",
507 id(input_5).state ? "ON" : "OFF",
508 id(input_6).state ? "ON" : "OFF");
Разъяснения
Ethernet
Микросхема Ethernet PHY LAN8720A подключена к микроконтроллеру по интерфейсу RMII.
Вывод GPIO15 используется для аппаратного сброса микросхемы и задается опцией power_pin:
# Enable Ethernet
ethernet:
id: eth
type: LAN8720
mdc_pin: GPIO23
mdio_pin: GPIO18
clk_mode: GPIO17_OUT
phy_addr: 1
power_pin: GPIO15 # Ethernet PHY hardware reset
on_connect:
- logger.log: "Ethernet connected"
- component.update: eth_connected
on_disconnect:
- logger.log: "Ethernet disconnected"
- component.update: eth_connected
Предупреждение
При использовании Ethernet секции wifi и captive_portal должны быть отключены.
Компоненту ethernet присвоен идентификатор eth, что позволяет обращаться к состоянию
подключения из других частей конфигурации. Триггеры on_connect и on_disconnect
срабатывают при установлении и потере соединения.
Состояние подключения публикуется отдельным датчиком, доступным в Home Assistant.
Значение возвращает метод is_connected() компонента ethernet. Датчик шаблонный
и опрашивается периодически, поэтому оба триггера дополнительно вызывают
component.update - иначе после появления или пропадания связи датчик обновился бы
только при следующем опросе:
# Ethernet link state, tracked continuously
- platform: template
name: "Ethernet connected"
id: eth_connected
lambda: |-
return id(eth).is_connected();
Примечание
В автоматизациях то же состояние проверяется условием ethernet.connected.
Home Assistant API
По умолчанию компонент api перезагружает контроллер, если в течение 15 минут к нему
не подключился ни один клиент. В журнале это выглядит как сообщение No clients; rebooting.
Такое поведение мешает, если контроллер работает автономно, без Home Assistant,
или если сервер временно недоступен.
Перезагрузка отключается заданием reboot_timeout: 0s:
# Enable Home Assistant API
api:
# Do not reboot when no API client is connected ("No clients; rebooting").
# The default is 15min, which reboots the controller when it runs without Home Assistant.
reboot_timeout: 0s
Шина I2C
Внутренняя шина I2C, к которой подключена вся периферия контроллера, выведена на выводы
GPIO4 (SCL) и GPIO5 (SDA):
# Enable internal I2C bus
i2c:
- id: i2c_int
sda: 5
scl: 4
frequency: 400kHz
scan: true
## External I2C bus
# - id: i2c_ext
# sda: 14
# scl: 13
# frequency: 400kHz
# scan: true
Внешняя шина I2C (GPIO13 - SCL, GPIO14 - SDA) в конфигурации закомментирована.
Расширитель портов
В контроллере используются две микросхемы расширителя портов PCA9535: на материнской плате
(адрес 0x22, реле и дискретные входы) и на модуле дисплея (адрес 0x24, джойстик
и кнопки). Для них можно использовать драйвер pca9554:
# Enable I2C GPIO expanders
pca9554:
- id: mb_gpio_exp
pin_count: 16
address: 0x22
i2c_id: i2c_int
# Display module expander, present in the extended configuration only
- id: display_gpio_exp
pin_count: 16
address: 0x24
i2c_id: i2c_int
Модули расширения JXM
К каждому слоту модуля расширения подведены интерфейс UART и две линии управления - аппаратного сброса и переключения режима. Скорость обмена задана 115200 бод:
# UART interfaces routed to the JXM expansion module connectors
uart:
- id: uart_jxm1
tx_pin: GPIO33
rx_pin: GPIO34
baud_rate: 115200
- id: uart_jxm2
tx_pin: GPIO32
rx_pin: GPIO39
baud_rate: 115200
Линии RESET и MODE подключены к расширителю портов материнской платы:
# Control lines of the JXM expansion modules
- platform: gpio
name: "JXM1 reset"
id: jxm1_reset
pin:
pca9554: mb_gpio_exp
number: 6
mode: OUTPUT
inverted: false
- platform: gpio
name: "JXM1 mode"
id: jxm1_mode
pin:
pca9554: mb_gpio_exp
number: 7
mode: OUTPUT
inverted: false
- platform: gpio
name: "JXM2 reset"
id: jxm2_reset
pin:
pca9554: mb_gpio_exp
number: 14
mode: OUTPUT
inverted: false
- platform: gpio
name: "JXM2 mode"
id: jxm2_mode
pin:
pca9554: mb_gpio_exp
number: 15
mode: OUTPUT
inverted: false
Примечание
На материнской плате выходы RESET и MODE выполнены по схеме «открытый коллектор»,
поэтому логика их работы зависит от подключенного модуля JXM.
Реле
Реле подключены к расширителю портов материнской платы, порты 0 … 5.
Для управления реле используется прямая логика: логический уровень 1 - реле включено.
# Enable digital outputs: STAT LED and relays
switch:
- platform: gpio
name: "Relay 1"
id: relay_1
pin:
pca9554: mb_gpio_exp
number: 0
mode: OUTPUT
inverted: false
on_turn_on:
- component.update: oled
on_turn_off:
- component.update: oled
- platform: gpio
name: "Relay 2"
id: relay_2
pin:
pca9554: mb_gpio_exp
number: 1
mode: OUTPUT
inverted: false
on_turn_on:
- component.update: oled
on_turn_off:
- component.update: oled
- platform: gpio
name: "Relay 3"
id: relay_3
pin:
pca9554: mb_gpio_exp
number: 2
mode: OUTPUT
inverted: false
on_turn_on:
- component.update: oled
on_turn_off:
- component.update: oled
- platform: gpio
name: "Relay 4"
id: relay_4
pin:
pca9554: mb_gpio_exp
number: 3
mode: OUTPUT
inverted: false
on_turn_on:
- component.update: oled
on_turn_off:
- component.update: oled
- platform: gpio
name: "Relay 5"
id: relay_5
pin:
pca9554: mb_gpio_exp
number: 4
mode: OUTPUT
inverted: false
on_turn_on:
- component.update: oled
on_turn_off:
- component.update: oled
- platform: gpio
name: "Relay 6"
id: relay_6
pin:
pca9554: mb_gpio_exp
number: 5
mode: OUTPUT
inverted: false
on_turn_on:
- component.update: oled
on_turn_off:
- component.update: oled
Примечание
При изменении состояния выходов, через некоторое время (~40 сек) ESPHome по-умолчанию автоматически сохраняет их состояние и после перезагрузки восстанавливает состояния выходов на сохраненные ранее.
Если данный функционал не нужен, то необходимо изменить эту функцию, задав состояние выхода
при загрузке с помощью опции restore_mode, например:
switch:
- platform: gpio
...
restore_mode: ALWAYS_OFF
...
Светодиод STAT
Двухцветный светодиод STAT подключен к выводу GPIO2 микроконтроллера. Логический
уровень 0 - светодиод горит зеленым, логический уровень 1 - красным:
# Enable digital outputs: STAT LED and relays
switch:
- platform: gpio
name: "STAT LED"
id: stat_led
pin:
number: 2
mode: OUTPUT
inverted: false # logical 0 - green, logical 1 - red
Дискретные входы
Дискретные входы подключены к расширителю портов материнской платы, порты 8 … 13.
Логический уровень 1 соответствует замкнутому входу.
Пример конфигурации дискретного входа:
# Enable discrete inputs
binary_sensor:
- platform: gpio
name: "Input 1"
id: input_1
pin:
pca9554: mb_gpio_exp
number: 8
inverted: false
on_press:
- component.update: oled
on_release:
- component.update: oled
- platform: gpio
name: "Input 2"
id: input_2
pin:
pca9554: mb_gpio_exp
number: 9
inverted: false
on_press:
- component.update: oled
on_release:
- component.update: oled
- platform: gpio
name: "Input 3"
id: input_3
pin:
pca9554: mb_gpio_exp
number: 10
inverted: false
on_press:
- component.update: oled
on_release:
- component.update: oled
- platform: gpio
name: "Input 4"
id: input_4
pin:
pca9554: mb_gpio_exp
number: 11
inverted: false
on_press:
- component.update: oled
on_release:
- component.update: oled
- platform: gpio
name: "Input 5"
id: input_5
pin:
pca9554: mb_gpio_exp
number: 12
inverted: false
on_press:
- component.update: oled
on_release:
- component.update: oled
- platform: gpio
name: "Input 6"
id: input_6
pin:
pca9554: mb_gpio_exp
number: 13
inverted: false
on_press:
- component.update: oled
on_release:
- component.update: oled
Примечание
Конфигурация описывает только периферию контроллера и не задает логику его работы. Примеры логики приведены в разделе Примеры автоматизаций.
Кнопка FN
Пользовательская кнопка FN контроллера JXD-R6-E1ETH (v1) вынесена в отдельный файл-пакет:
1# The FN user button of the JXD-R6-E1ETH (v1) controller, on GPIO0.
2# Add it to the packages list to use the FN button.
3
4binary_sensor:
5 - platform: gpio
6 name: "FN button"
7 id: fn_button
8 pin:
9 number: 0
10 inverted: true
Подсказка
Чтобы использовать кнопку FN, добавьте этот пакет в список packages вашей конфигурации:
packages:
- !include jxd_r6_e1eth_lcd_base.yaml
- !include jxd_r6_e1eth_v1_fn_button.yaml
1-Wire
Шина 1-Wire реализована на микросхеме преобразователя I2C в 1-Wire DS2482S-100,
установленной на материнской плате. Для нее используется компонент ds248x, поддерживающий
микросхемы DS2482-100, DS2482-101, DS2482-800 и DS2484.
Сам мост описывается в секции ds248x: тип микросхемы задается обязательной опцией type,
адрес на внутренней шине I2C - 0x18. Шина 1-Wire моста описывается платформой
ds248x в секции one_wire:
# Enable the DS2482S-100 I2C-to-1-Wire bridge
ds248x:
- id: onewire_hub
type: ds2482-100
address: 0x18
i2c_id: i2c_int
# Enable the 1-Wire bus of the bridge
one_wire:
- platform: ds248x
ds248x_id: onewire_hub
id: onewire_bus
Датчики температуры
Датчики температуры, подключенные к шине 1-Wire, описываются платформой dallas_temp.
Опция one_wire_id указывает на шину моста, address - адрес конкретного датчика.
Период опроса задается опцией update_interval; для всех датчиков контроллера
в примере задано 5 секунд вместо 60 секунд по умолчанию. Идентификатор temperature
позволяет обращаться к показаниям датчика из лямбда-функции дисплея. В конфигурации
описан один датчик:
# 1-Wire temperature sensors: one entry per sensor connected to the bus
sensor:
- platform: dallas_temp
one_wire_id: onewire_bus
address: 0xc800000c23c4c128
name: "Temperature"
id: temperature
update_interval: 5s # default is 60s
Примечание
Для каждого датчика, подключенного к шине, добавляется отдельная запись со своим адресом. Адреса найденных на шине датчиков ESPHome выводит в журнал при запуске контроллера.
Температура внутри корпуса
Для измерения температуры внутри корпуса на процессорном модуле установлена микросхема
TMP102, подключенная к внутренней шине I2C по адресу 0x48. Используется платформа
tmp102:
# Case temperature sensor on the internal I2C bus
- platform: tmp102
name: "Case temperature"
id: case_temperature
address: 0x48
i2c_id: i2c_int
update_interval: 5s
Измерение напряжений питания
Напряжения питания измеряются встроенным АЦП микроконтроллера через делитель напряжения
с коэффициентом 1:32: напряжение на клемме DC IN - вывод GPIO35, напряжение
Passive PoE на разъеме Ethernet - вывод GPIO37.
Режим attenuation: auto подбирает диапазон АЦП автоматически, а фильтр multiply: 32
пересчитывает измеренное напряжение обратно во входное:
# Supply voltage measurement
- platform: adc
name: "DC IN voltage"
id: dc_in_voltage
pin: GPIO35
attenuation: auto
update_interval: 5s
unit_of_measurement: "V"
device_class: voltage
accuracy_decimals: 1
filters:
- multiply: 32 # 1:32 voltage divider in front of the ADC
- platform: adc
name: "PoE voltage"
id: poe_voltage
pin: GPIO37
attenuation: auto
update_interval: 5s
unit_of_measurement: "V"
device_class: voltage
accuracy_decimals: 1
filters:
- multiply: 32 # 1:32 voltage divider in front of the ADC
Примечание
Точность измерения напряжения - около 3%.
Дисплей
Примечание
Модуль дисплея устанавливается в зависимости от комплектации контроллера: в базовой комплектации JXD-R6-E1ETH дисплей отсутствует. Приведенная конфигурация рассчитана на контроллер с установленным модулем дисплея.
На модуле дисплея установлен OLED-экран на драйвере SH1106 с разрешением 128х64 точек,
подключенный к внутренней шине I2C по адресу 0x3C. Для него используется платформа
ssd1306_i2c.
Для вывода текста необходим шрифт. Для экрана такого размера удобнее растровый шрифт: он
отрисовывается без сглаживания и остается читаемым при малом кегле. В примере используется
Terminus - файл ter-u12n.bdf размером 6х12 точек, что дает 21 символ в строке
и 5 строк на экране 128х64:
# Fonts for the display
# Terminus is a bitmap font: ter-u12n.bdf is 6x12 px, 21 characters per 128 px line.
# Put the .bdf file into a "fonts" folder next to this configuration file.
font:
- file: "fonts/ter-u12n.bdf"
id: terminus_12
size: 12
Примечание
Файл шрифта не входит в поставку ESPHome: скачайте Terminus и положите ter-u12n.bdf
в папку fonts рядом с файлом конфигурации.
Для растровых шрифтов опция size должна совпадать с одним из размеров, имеющихся
в файле шрифта, иначе сборка завершится ошибкой. В файле ter-u12n.bdf доступен
единственный размер - 12.
IP-адрес контроллера предоставляет платформа ethernet_info. Текстовый сенсор получает
идентификатор eth_ip, по которому к нему обращается лямбда-функция дисплея:
# Ethernet information
text_sensor:
- platform: ethernet_info
ip_address:
name: "IP Address"
id: eth_ip
Информация разнесена на шесть страниц, каждая со своей лямбда-функцией:
page_system- имя контроллера и тип автоматизации, отображается при включении;page_network- состояние подключения Ethernet и IP-адрес;page_sensors- температура датчика 1-Wire и температура внутри корпуса;page_power- напряжения питания на клеммеDC INи на разъеме Ethernet;page_relays- состояние шести реле;page_inputs- состояние шести дискретных входов.
Имя контроллера берется из секции esphome вызовом App.get_name(). В базовом файле
задано короткое имя jxd, к которому опция name_add_mac_suffix добавляет суффикс
из MAC-адреса - имя вида jxd-a1b2c3 умещается в строку экрана целиком.
Тип автоматизации задается подстановкой logic: в базовом файле она имеет значение
None, а файл автоматизации переопределяет ее - Light switch, Light button
или Thermostat (см. Примеры автоматизаций).
Состояния реле и дискретных входов выводятся двумя строками по три значения; для обращения
к ним из лямбда-функции реле и входам присвоены идентификаторы relay_1 … relay_6
и input_1 … input_6.
Показания датчиков обновляются на экране по update_interval дисплея, а состояния реле
и дискретных входов - сразу при изменении: к триггерам on_turn_on и on_turn_off
каждого реле и к триггерам on_press и on_release каждого входа добавлено действие
component.update:
- platform: gpio
name: "Relay 1"
id: relay_1
pin:
pca9554: mb_gpio_exp
number: 0
mode: OUTPUT
inverted: false
on_turn_on:
- component.update: oled
on_turn_off:
- component.update: oled
Примечание
Триггеры реле срабатывают при любом изменении состояния, в том числе при управлении из Home Assistant, а триггеры входов - при изменении состояния входа. Изменение входа переключает реле, поэтому экран перерисовывается дважды; на работу это не влияет.
Верхняя строка каждой страницы - заголовок - выводится инверсно: сначала заливается полоса
во всю ширину экрана цветом COLOR_ON, затем поверх нее печатается текст цветом
COLOR_OFF. Для монохромного экрана доступны только эти два цвета.
Состояние подключения лямбда-функция получает напрямую от компонента ethernet вызовом
id(eth).is_connected(), IP-адрес - из текстового сенсора eth_ip, остальные
значения - из соответствующих датчиков.
Вместо значения выводятся прочерки ---, если показание отсутствует. Проверяется именно
NaN, а не наличие состояния: метод has_state() становится истинным и тогда, когда
датчик опубликовал NaN, и на экран попадала бы надпись nan:
# Display module: six pages switched with the joystick
# NOTE: the display module is installed depending on the controller configuration
display:
- platform: ssd1306_i2c
id: oled
model: "SH1106 128x64"
address: 0x3C
i2c_id: i2c_int
update_interval: 5s
pages:
# Page 1: device name and the automation type
- id: page_system
lambda: |-
// Page title: dark text on a filled bar
it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
it.print(2, 0, id(terminus_12), COLOR_OFF, "System");
it.printf(0, 16, id(terminus_12), "Name: %s", App.get_name().c_str());
it.printf(0, 32, id(terminus_12), "Logic: ${logic}");
# Page 2: network state
- id: page_network
lambda: |-
// Page title: dark text on a filled bar
it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
it.print(2, 0, id(terminus_12), COLOR_OFF, "Network");
if (id(eth).is_connected()) {
it.printf(0, 16, id(terminus_12), "Ethernet: connected");
it.printf(0, 32, id(terminus_12), "IP: %s", id(eth_ip).state.c_str());
} else {
it.printf(0, 16, id(terminus_12), "Ethernet: no link");
}
# Page 3: temperatures
- id: page_sensors
lambda: |-
// Page title: dark text on a filled bar
it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
it.print(2, 0, id(terminus_12), COLOR_OFF, "Temperatures");
if (!std::isnan(id(temperature).state)) {
it.printf(0, 16, id(terminus_12), "1-Wire: %.1f C", id(temperature).state);
} else {
it.printf(0, 16, id(terminus_12), "1-Wire: ---");
}
if (!std::isnan(id(case_temperature).state)) {
it.printf(0, 32, id(terminus_12), "Case: %.1f C", id(case_temperature).state);
} else {
it.printf(0, 32, id(terminus_12), "Case: ---");
}
# Page 4: supply voltages
- id: page_power
lambda: |-
// Page title: dark text on a filled bar
it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
it.print(2, 0, id(terminus_12), COLOR_OFF, "Power supply");
if (!std::isnan(id(dc_in_voltage).state)) {
it.printf(0, 16, id(terminus_12), "DC IN: %.1f V", id(dc_in_voltage).state);
} else {
it.printf(0, 16, id(terminus_12), "DC IN: ---");
}
if (!std::isnan(id(poe_voltage).state)) {
it.printf(0, 32, id(terminus_12), "PoE: %.1f V", id(poe_voltage).state);
} else {
it.printf(0, 32, id(terminus_12), "PoE: ---");
}
# Page 5: relay states
- id: page_relays
lambda: |-
// Page title: dark text on a filled bar
it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
it.print(2, 0, id(terminus_12), COLOR_OFF, "Relays");
it.printf(0, 16, id(terminus_12), "1:%-3s 2:%-3s 3:%-3s",
id(relay_1).state ? "ON" : "OFF",
id(relay_2).state ? "ON" : "OFF",
id(relay_3).state ? "ON" : "OFF");
it.printf(0, 32, id(terminus_12), "4:%-3s 5:%-3s 6:%-3s",
id(relay_4).state ? "ON" : "OFF",
id(relay_5).state ? "ON" : "OFF",
id(relay_6).state ? "ON" : "OFF");
# Page 6: discrete input states
- id: page_inputs
lambda: |-
// Page title: dark text on a filled bar
it.filled_rectangle(0, 0, it.get_width(), 13, COLOR_ON);
it.print(2, 0, id(terminus_12), COLOR_OFF, "Inputs");
it.printf(0, 16, id(terminus_12), "1:%-3s 2:%-3s 3:%-3s",
id(input_1).state ? "ON" : "OFF",
id(input_2).state ? "ON" : "OFF",
id(input_3).state ? "ON" : "OFF");
it.printf(0, 32, id(terminus_12), "4:%-3s 5:%-3s 6:%-3s",
id(input_4).state ? "ON" : "OFF",
id(input_5).state ? "ON" : "OFF",
id(input_6).state ? "ON" : "OFF");
Примеры автоматизаций
Файл jxd_r6_e1eth_lcd_base.yaml описывает только
периферию контроллера и не задает логику его работы. Логика выносится в отдельный файл, который
подключает базовый файл как пакет и дополняет уже описанные компоненты по их идентификаторам
с помощью !extend.
Ниже приведены готовые файлы конфигурации для типовых сценариев. Каждый из них собирается командой ESPHome как обычная конфигурация - базовый файл должен лежать рядом:
esphome run jxd_r6_e1eth_lcd_switches.yaml
Примечание
При слиянии списки компонентов объединяются по id, поэтому !extend дополняет уже
описанный компонент, а не заменяет его. Значения из основного файла имеют приоритет над
значениями пакета - так подстановка logic переопределяет значение, заданное
в базовом файле. Подробнее - в документации ESPHome о packages.
Управление светом выключателями с фиксацией
Каждое реле повторяет состояние соответствующего входа: вход замкнут - реле включено, вход разомкнут - реле выключено. Подходит для клавишных выключателей с фиксацией.
Подсказка
1# Lighting controlled by latching switches.
2# Every relay repeats the state of the discrete input with the same number.
3#
4# Build this file together with jxd_r6_e1eth_lcd_base.yaml, which must be
5# placed next to it.
6
7packages:
8 - !include jxd_r6_e1eth_lcd_base.yaml
9
10# Shown on the System page of the display
11substitutions:
12 logic: "Light switch"
13
14binary_sensor:
15 - id: !extend input_1
16 on_press:
17 - switch.turn_on: relay_1
18 on_release:
19 - switch.turn_off: relay_1
20
21 - id: !extend input_2
22 on_press:
23 - switch.turn_on: relay_2
24 on_release:
25 - switch.turn_off: relay_2
26
27 - id: !extend input_3
28 on_press:
29 - switch.turn_on: relay_3
30 on_release:
31 - switch.turn_off: relay_3
32
33 - id: !extend input_4
34 on_press:
35 - switch.turn_on: relay_4
36 on_release:
37 - switch.turn_off: relay_4
38
39 - id: !extend input_5
40 on_press:
41 - switch.turn_on: relay_5
42 on_release:
43 - switch.turn_off: relay_5
44
45 - id: !extend input_6
46 on_press:
47 - switch.turn_on: relay_6
48 on_release:
49 - switch.turn_off: relay_6
Примечание
Реле остаются доступны для управления из Home Assistant, но при следующем изменении состояния входа вернутся в состояние, заданное входом.
Термостат
Реле 1 управляет нагревателем по показаниям датчика температуры 1-Wire: ниже уставки реле
включается, выше - выключается. Чтобы реле не щелкало при колебаниях температуры около уставки,
пороги включения и выключения разнесены на величину гистерезиса.
В примере уставка 25 °C, гистерезис 0,5 °C: нагреватель включается при температуре ниже 25 °C и выключается при температуре выше 25,5 °C.
Подсказка
1# Thermostat: relay 1 drives a heater from the 1-Wire temperature sensor.
2# Setpoint 25 C, hysteresis 0.5 C: on below 25.0 C, off above 25.5 C.
3#
4# Build this file together with jxd_r6_e1eth_lcd_base.yaml, which must be
5# placed next to it.
6
7packages:
8 - !include jxd_r6_e1eth_lcd_base.yaml
9
10# Shown on the System page of the display
11substitutions:
12 logic: "Thermostat"
13
14sensor:
15 - id: !extend temperature
16 filters:
17 # Publish NaN if readings stop arriving at all
18 - timeout: 30s
19 on_value:
20 # The hysteresis is evaluated on every reading rather than with
21 # on_value_range, which ignores NaN and would keep the thermostat off
22 # after the sensor has been reconnected.
23 - lambda: |-
24 if (std::isnan(x)) {
25 // Emergency shutoff: the sensor does not answer
26 if (id(relay_1).state)
27 id(relay_1).turn_off();
28 } else if (x < 25.0) {
29 if (!id(relay_1).state)
30 id(relay_1).turn_on();
31 } else if (x > 25.5) {
32 if (id(relay_1).state)
33 id(relay_1).turn_off();
34 }
Гистерезис вычисляется в лямбда-функции при каждом измерении, а не триггером
on_value_range. Причина в том, как устроен этот триггер: он запоминает, находилось ли
предыдущее значение внутри диапазона, а значения NaN пропускает, не изменяя этот признак.
В результате после отключения и повторного подключения датчика вход в диапазон не был бы
обнаружен, и нагреватель остался бы выключенным.
Между порогами 25 °C и 25,5 °C никаких действий не выполняется - это и есть зона гистерезиса, в которой реле сохраняет свое состояние. Состояние реле проверяется перед переключением, поэтому лишних публикаций состояния не происходит.
Аварийное отключение нагревателя реализовано двумя механизмами:
Если датчик не отвечает, платформа
dallas_tempпубликует значениеNaN, и лямбда-функция выключает реле.Если показания перестали поступать совсем, фильтр
timeoutчерез 30 секунд сам публикуетNaN, что приводит к тому же выключению. Период опроса датчика - 5 секунд, то есть срабатывание происходит после шести пропущенных измерений.
После восстановления связи с датчиком термостат возвращается к работе самостоятельно: первое же полученное значение снова проходит проверку порогов.