SVG-Dashboards/en: различия между версиями

Материал из Wiren Board
(Новая страница: «Once uploaded, the image will be displayed on the open page: # Specify links and behavior of svg elements using link editor. # Save the changes and see the result by clicking on the '''Demo''' button.»)
(не показано 10 промежуточных версий этого же участника)
Строка 21: Строка 21:
Full-screen mode allows you to switch between panels through the side menu, and in HMI mode, you need to implement the switch yourself: add a button (object) with a URL to the desired panel in the SVG image.
Full-screen mode allows you to switch between panels through the side menu, and in HMI mode, you need to implement the switch yourself: add a button (object) with a URL to the desired panel in the SVG image.


<gallery mode="packed" heights="150px" caption="Panel modes">
<gallery mode="packed" heights="150px" caption="Режимы панелей">
Image: WebUI SVG.png | Standard view
Image: WebUI SVG.png | Standard view
Image: WebUI SVG fullscreen.png | Fullscreen
Image: WebUI SVG fullscreen.png | Fullscreen
Строка 121: Строка 121:
The image is prepared in an external vector editor, but the assignment of links to elements is done in the controller web interface.
The image is prepared in an external vector editor, but the assignment of links to elements is done in the controller web interface.


To associate an image svg element with values or events, select it with the mouse, after which fields for setting the element's behavior will appear next to the image.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Чтобы связать svg-элемент изображения со значениями или событиями, выберите его мышкой, после этого рядом с изображением появятся поля настройки поведения элемента.
{{SupportedSinceRelease
{{SupportedSinceRelease
| release = wb-2307
| release = wb-2307
|content=
|content=
In addition to selecting a single element, you can select a group. To do this, hold down the Alt key on your keyboard and click on one of the elements of the group. The group containing the element will be highlighted. Clicking again while holding down the Alt key will select the group one level higher and so on up to the very top of the hierarchy.
Кроме выделения одиночного элемента, можно выделять группу. Для этого зажмите на клавиатуре клавишу Alt и кликните по одному из элементов группы. Будет выделена группа, куда входит элемент. Повторный клик при зажатой клавише Alt выберет группу уровнем выше и так далее до самого верха иерархии.
</div>


Groups are convenient to use for creating buttons: we combined a rectangle and an icon in the editor and got a button.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Группы удобно использовать для создания кнопок: объединили в редакторе прямоугольник и иконку и получилась кнопка.
}}
}}
</div>


After setting up all connections, click the '''Save''' button.
<div lang="ru" dir="ltr" class="mw-content-ltr">
После настройки всех связи нажмите кнопку '''Сохранить'''.
</div>


=== Read ===
<div lang="ru" dir="ltr" class="mw-content-ltr">
Display values from the source in a text field.
=== Чтение ===
Отображение значений из источника в текстовом поле.
</div>


The value from the source selected in the '''Channel''' field is placed in the '''val''' variable, which must be specified in the '''Value''' field.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Значение из выбранного в поле '''Канал''' источника помещается в переменную '''val''', которую нужно указать в поле '''Значение'''.
</div>


To display the value, just specify the variable:
<div lang="ru" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="javascript">  
Чтобы вывести значение, просто укажите переменную:
<syntaxhighlight lang="javascript">
val
val
</syntaxhighlight>
</syntaxhighlight>
</div>


You can add arbitrary text to the value, for example, the unit of measure:
<div lang="ru" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="javascript">  
К значению можно добавить произвольный текст, например, единицу измерения:
val + '°C'
<syntaxhighlight lang="javascript">
val + ' °C'
</syntaxhighlight>
</syntaxhighlight>
</div>


You can also change the received value, for example, replace it with a human-readable status:
<div lang="ru" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="javascript">  
Также можно подменить полученное значение, например, заменить его на понятный человеку статус:
(val == 1) ? 'ON' : 'OFF'
<syntaxhighlight lang="javascript">
(val == 1) ? 'ВКЛ' : 'ОТКЛ'
</syntaxhighlight>
</syntaxhighlight>
</div>


=== Write to channel ===
<div lang="ru" dir="ltr" class="mw-content-ltr">
With this setting you can write a value to the topic when the user clicks on the element.
=== Запись в канал ===
С помощью этой настройки вы можете записать значение в топик при клике пользователя по элементу.
</div>


There are two states ON and OFF. When a user clicks on an element, the value in the MQTT topic will change to the opposite.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Доступно два состояния ON и OFF. При клике пользователя на элементе, значение в MQTT-топике будет меняться на противоположное.
</div>


In the '''Channel''' field, select the MQTT topic for writing values, and in the '''On State Value''' and '''Off State Value''' fields specify which values correspond to the states.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Выберите в поле '''Канал''' MQTT топик для записи значений, а в полях '''Значение включенного состояния''' и '''Значение выключенного состояния''' укажите какие значения соответствуют состояниям.
</div>


For example, to switch a relay, specify:
<div lang="ru" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="javascript">  
Например, для переключения реле нужно указать:
On value = 1
<syntaxhighlight lang="javascript">
Off value = 0
Значение включенного состояния = 1
Значение выключенного состояния = 0
</syntaxhighlight>
</syntaxhighlight>
</div>


=== Jump and swipe ===
<div lang="ru" dir="ltr" class="mw-content-ltr">
=== Переход и смахивания ===
{{SupportedSinceRelease
{{SupportedSinceRelease
| release = wb-2307
| release = wb-2307
|content=
|content=
[[Image: svg-tap.png |300px|thumb|right| Creating a transition ]]
[[Image: svg-tap.png |300px|thumb|right| Создание перехода ]]
</div>


Using transitions, you can create multi-page interfaces:
<div lang="ru" dir="ltr" class="mw-content-ltr">
# Draw a custom picture for each page.
С помощью переходов можно создавать многостраничные интерфейсы:
# Load these pictures into the controller.
# Нарисуйте для каждой страницы свой рисунок.
# Select a panel for one of the three events to navigate to.
# Загрузите эти рисунки в контроллер.
# Выберите для одного из трёх событий панель, куда надо переходить.
</div>


Events available: single and long press, as well as swipe left and right.  
<div lang="ru" dir="ltr" class="mw-content-ltr">
Доступны события: одиночное и длинное нажатие, а также смахивание влево и вправо.
</div>


By single and long pressing, the transition to SVG and text panels is available, and by swiping - only SVG. This is an architectural limitation that we are not yet able to fix.
<div lang="ru" dir="ltr" class="mw-content-ltr">
По одиночному и длинному нажатию доступен переход на SVG и текстовые панели, а по смахиванию — только SVG. Это архитектурное ограничение, которое мы пока не модем устранить.
}}
}}
</div>


=== Visibility ===
<div lang="ru" dir="ltr" class="mw-content-ltr">
Here you can specify under what condition to show the image element. By default, the element will be hidden and displayed only while the condition is met.
=== Видимость ===
Здесь можно указать при каком условии показывать элемент изображения. По умолчанию элемент будет скрыт и отобразится только пока выполняется условие.
</div>


In the '''Channel''' field, select the MQTT topic that the element will respond to, in the '''Condition''' field, select a condition, and in the '''Value''' field, select a value.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Выберите в поле '''Канал''' MQTT-топик, на информацию из которого будет реагировать элемент, в поле '''Условие''' выберите условие, а в поле '''Значение''' — значение.
</div>


=== Design style ===
<div lang="ru" dir="ltr" class="mw-content-ltr">
Allows you to change the style of image elements. Can be used to create feedback for actions, notify the user about an event, etc.
=== Стиль оформления ===
Позволяет изменять стиль элементов изображения. Можно использовать для создания обратной связи для действий, оповещения пользователя о событии т.д.
</div>


Element properties available for styling:
<div lang="ru" dir="ltr" class="mw-content-ltr">
* fill — fill color;
Доступные для стилизации свойства элемента:
* fill-opacity — fill opacity, values from 0.0 to 1.0 or as a percentage;
* fill — цвет заливки;
* stroke — stroke color;
* fill-opacity — непрозрачность заливки, значения от 0.0 до 1.0 или в процентах;
* stroke- width — stroke thickness;
* stroke — цвет обводки;
* stroke-dasharray — dashed stroke type, set in units of length or percentage.
* stroke-width — толщина обводки;
* stroke-opacity — stroke opacity, values from 0.0 to 1.0 or percentage.
* stroke-dasharray — вид пунктирной обводки, задается в единицах длины или процентах.
* stroke-opacity — непрозрачность обводки, значения от 0.0 до 1.0 или в процентах.
</div>


Colors can be named <code>black, red, yellow и т.п.</code> or hex values <code>#ffe680ff, #4f4f4dff и т.п.</code> .
<div lang="ru" dir="ltr" class="mw-content-ltr">
Цвета можно задавать именами <code>black, red, yellow и т.п.</code> или шестнадцатеричными значениями <code>#ffe680ff, #4f4f4dff и т.п.</code>.
</div>


Let's change the color of the element depending on the state of the relay, if the value in the topic is <code>1</code> , then paint the object yellow, otherwise - gray:
<div lang="ru" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="javascript">  
Изменим цвет элемента в зависимости от состояния реле, если в топике значение <code>1</code>, то закрашиваем объект желтым, иначе — серым:
<syntaxhighlight lang="javascript">
(val == 1) ? ';fill: yellow' : ';fill: gray'
(val == 1) ? ';fill: yellow' : ';fill: gray'
</syntaxhighlight>
</syntaxhighlight>
</div>


Let's make it so that when the value is greater than 20, the stroke of the element becomes red, dotted and 2px thick. For values less than or equal to 20, the element style will be left by default:
<div lang="ru" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="javascript">  
Сделаем так, чтобы при значении больше 20 обводка элемента стала красного цвета, пунктиром и толщиной 2px. При значениях меньше или равно 20 стиль элемента оставим по умолчанию:
<syntaxhighlight lang="javascript">
(val > 20) ? 'stroke: red; stroke-width:2px; stroke-dasharray:2,1' : ''
(val > 20) ? 'stroke: red; stroke-width:2px; stroke-dasharray:2,1' : ''
</syntaxhighlight>
</syntaxhighlight>
</div>


== Editing ==
<div lang="ru" dir="ltr" class="mw-content-ltr">
== Редактирование ==
</div>


=== Panel ===
<div lang="ru" dir="ltr" class="mw-content-ltr">
To make changes:
=== Панель ===
# Open the SVG panel.
Чтобы внести изменения:
# Click on the '''Edit''' button.
# Откройте SVG-панель.
# Make changes and save them by clicking on the ' button ''Demonstration'''.
# Нажмите кнопку '''Редактировать'''.
# Внесите изменения и сохраните их нажатием на кнопку '''Демонстрация'''.
</div>


=== SVG Image ===
<div lang="ru" dir="ltr" class="mw-content-ltr">
==== Release wb-2307 and newer ====
=== SVG-изображение ===
==== Релиз wb-2307 и новее ====
{{SupportedSinceRelease
{{SupportedSinceRelease
| release=wb-2307
| release = wb-2307
|content=
|content=
</div>


SVG panels use identifiers embedded in the file (the id tag), so to edit the panel, simply make changes to the drawing and upload the new version to the controller.  
<div lang="ru" dir="ltr" class="mw-content-ltr">
В SVG-панелях используются встроенные в файл идентификаторы (тег id), поэтому для редактирования панели просто внесите изменения в рисунок и загрузите новую версию в контроллер.
</div>


Important! If you have made a binding to a group of elements, then do not ungroup this group! If you need to change it, just go to the group in Inkscape and add or remove elements.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Важно! Если вы сделали привязку к группе элементов, то не разгруппировывайте эту группу! Если вам надо её изменить, просто войдите в группу в Inkscape и добавьте или удалите элементы.
</div>


<div lang="ru" dir="ltr" class="mw-content-ltr">
}}
}}
</div>


==== Release wb-2304 and older ====
<div lang="ru" dir="ltr" class="mw-content-ltr">
The SVG panel editor assigns data-svg-param-id at the time of binding actions to the element, so to edit the image, you need to load it from the controller to the computer:
==== Релиз wb-2304 и старее ====
Редактор SVG-панели в момент привязки действий к элементу прописывает data-svg-param-id, поэтому для редактирования изображения нужно его загрузить с контроллера на компьютер:
</div>


# Open the SVG panel for editing.
<div lang="ru" dir="ltr" class="mw-content-ltr">
# At the top of the window, click the '''Download''' button, the svg file will be downloaded to your computer.
# Откройте SVG-панель для редактирования.
# Edit the file in Inkscape. We do not recommend editing such files in Adobe Illustrator - [https://support.wirenboard.com/t/redaktirovanie-svg-dacsboard bindings are lost], there is no information about other editors.
# В верхней части окна нажмите кнопку '''Download''', на компьютер загрузится svg-файл.
# Отредактируйте файл в Inkscape. В Adobe Illustrator редактировать такие файлы не рекомендуем — [https://support.wirenboard.com/t/redaktirovanie-svg-dacsboard теряются привязки], про другие редакторы информации нет.
</div>


When editing, keep in mind that if a link was assigned to an svg element, then it contains a hidden data-svg-param-id and when it is duplicated, a new element is created with the same data-svg-param-id.
<div lang="ru" dir="ltr" class="mw-content-ltr">
При редактировании учтите, что если на svg-элемент была назначена связь, то он содержит скрытый data-svg-param-id и при его дублировании создается новый элемент с тем же data-svg-param-id.
</div>


Edit the resulting svg file and upload it to the controller again:
<div lang="ru" dir="ltr" class="mw-content-ltr">
# In the edit window, click the '''Select File''' button.
Отредактируйте полученный svg-файл и вновь загрузите его на контроллер:
# After the '''Change''' button becomes active, click on her.
# В окне редактирования нажмите кнопку '''Выберите файл'''.
# После того, как кнопка '''Change''' станет активной, нажмите на нее.
</div>


== Transfer to another controller ==
<div lang="ru" dir="ltr" class="mw-content-ltr">
Sometimes you need to make a backup copy of the svg-panel, for example, to transfer to another controller. To do this, you need to save the svg file converted by the editor and the description of its links and upload them to another controller.
== Перенос на другой контроллер ==
Иногда нужно сделать резервную копию svg-панели, например, для переноса на другой контроллер. Для этого нужно сохранить преобразованный редактором svg-файл и описание его связей и загрузить их на другой контроллер.
</div>


Please note that the names of the MQTT topics on both controllers must match. If this is not the case, svg elements will need to be attached to new MQTT topics.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Учтите, что на имена MQTT-топиков на обоих контроллерах должны совпадать. Если это не так — svg-элементы нужно будет привязать к новым MQTT-топикам.
</div>


=== Saving ===
<div lang="ru" dir="ltr" class="mw-content-ltr">
Save the svg file and link description:
=== Сохранение ===
# Download the file from the controller to your computer. To do this, click on the button with the image of a down arrow.
Сохраните svg-файл и описание связей:
# In the editor of the svg-panel, click the button '''As JSON''', copy and save the lines to a file.
# Скачайте файл с контроллера на компьютер. Для этого нажмите на кнопку с изображением стрелки вниз.
# В редакторе svg-панели нажмите кнопку '''В виде JSON''', скопируйте и сохраните строки в файл.
</div>


=== Loading ===
<div lang="ru" dir="ltr" class="mw-content-ltr">
# Create a new SVG panel following the instructions in the [[#Creating an SVG panel| Creating an SVG panel]].
=== Загрузка ===
# In the svg panel editor, click the '''As JSON''' button, copy the link description from the saved file and paste the text into the field
# Создайте новую SVG-панель по инструкции в разделе [[#Создание SVG-панели| Создание SVG-панели]].
# Click the '''Save'' button '' at the bottom of the page.
# В редакторе svg-панели нажмите кнопку '''В виде JSON''', скопируйте из сохраненного файла описание связей и вставьте текст в поле
# Нажмите кнопку '''Сохранить''' внизу страницы.
</div>


==Animation of SVG panel elements==
<div lang="ru" dir="ltr" class="mw-content-ltr">
[[File:animation-svg.gif|598x|thumb|right| SVG panel element animation example]]
==Анимация элементов SVG-панели==
SVG panel elements can be animated using CSS.
[[Файл:animation-svg.gif|598x|thumb|right| Пример анимации элемента SVG-панели]]
Элементы SVG-панели можно анимировать с помощью CSS.
</div>


To do this:
<div lang="ru" dir="ltr" class="mw-content-ltr">
#Draw an SVG panel in a vector editor like Inkscape.
Для этого нужно:
#Open the SVG file in a text editor and add a style block wrapped in tags<style></style> .
#Нарисовать SVG-панель в векторном редакторе, например, Inkscape.
#Add the '''@keyframes''' rule in the style block.
#Открыть файл SVG в текстовом редакторе и добавить блок стилей, заключенный в теги <code><style></style></code>.
#Save the file and load it into the controller.
#В блоке стилей добавить правило '''@keyframes'''.
#Go to the SVG panel editor in the controller's web interface.
#Сохранить файл и загрузить его в контроллер.
#Activate the '''Style''' parameter and set the property '''animation''' in the '''Value''' field. You also need to set the condition under which the animation will work.
#Перейти в редактор SVG-панели в веб-интерфейсе контроллера.
#Активировать параметр '''Style''' и задать в поле '''Value''' свойство '''animation'''. Также нужно задать условие при котором анимация будет срабатывать.
</div>


Rendering in CSS is done using the '''animation''' property and the '''@keyframes''' rule.  
<div lang="ru" dir="ltr" class="mw-content-ltr">
Визуализация в CSS осуществляется с помощью свойства '''animation''' и правила '''@keyframes'''.
</div>


'''@keyframes''', or keyframes, contain information about how the element should look at each point in time.
<div lang="ru" dir="ltr" class="mw-content-ltr">
'''@keyframes''', или ключевые кадры, содержат информацию о том как должен выглядеть элемент в каждый из моментов времени.
</div>


A rule containing two keyframes would look like this:
<div lang="ru" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="css">  
Правило содержащее два ключевых кадра будет выглядеть так:
@keyframes <keyframe name> {
<syntaxhighlight lang="css">
from: { description of the initial state of the element }
@keyframes <имя кейфрейма> {
to: { description of the final state of the element }
from: { описание начального состояния элемента }
to: { описание конечного состояния элемента }
}
}
</syntaxhighlight>  
</syntaxhighlight>
Here '''from''' and '''to''' keywords denote the start and end points of the animation. Instead, you can use 0% and 100%, as well as add intermediate values.
Здесь '''from''' и '''to''' ключевые слова обозначающие начальную и конечную точки анимации. Вместо них можно использовать 0% и 100%, а также добавить промежуточные значения.
</div>


The keyframe name is an identifier by which the rule will be called from the style description.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Имя кейфрейма — идентификатор, по которому правило будет вызываться из описания стилей.
</div>


In order for the animation to work, you need to set the element style to the '''animation''' property.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Чтобы анимация заработала нужно задать стилю элемента свойство '''animation'''.
</div>


The '''animation''' property sets the animation action parameters (animation duration, repetition, direction, movement type, steps), and the '''@keyframes''' block sets the animation itself in steps (changes in appearance and position).
<div lang="ru" dir="ltr" class="mw-content-ltr">
Свойство '''animation''' задаёт параметры действия для анимации (длительность анимации, повторение, направление, тип движения, шаги), а в блоке '''@keyframes''' задаётся сама анимация по шагам (изменения вида и положения).
</div>


Let's use an example to create an animation to change the text color from red to green and vice versa. Since text is filled in SVG, you will need to change the '''fill''' property.
<div lang="ru" dir="ltr" class="mw-content-ltr">
[[Image: animation-style.png |350px|thumb|right| The '''animation''' property is set in the '''Value''' field of the '''Style''' parameter ]]
Покажем на примере создание анимации для изменения цвета текста с красного на зеленый и обратно. Так как в SVG текст выполняется заливкой, то потребуется изменять свойство '''fill'''.
#Let's create a new SVG document in the Inlscape editor and add the Text element to it.  
[[Image: animation-style.png |350px|thumb|right| Свойство '''animation''' задается в поле '''Value''' параметра '''Style''' ]]
#Let's save the file and open it in a text editor.
#Создадим новый SVG-документ в редакторе Inlskape и добавим в него элемент Текст.  
#Add a style block like this:
#Сохраним файл и откроем его в текстовом редакторе.
#:<syntaxhighlight lang="html">  
#Добавим блок style следующего вида:
<style>
#:<syntaxhighlight lang="html">
  <style>
@keyframes changecolor {
@keyframes changecolor {
   0% {fill:red}
   0% {fill:red}
Строка 301: Строка 392:
   }
   }
   </style>
   </style>
</syntaxhighlight>  
</syntaxhighlight>
#Save the SVG file and load it into the controller.
#Сохраним SVG-файл и загрузим его в контроллер.
#In the dashboard editor, select the created test element and set its animation property in the following form:
#В редакторе дашбордов выберем созданным тестовый элемент и зададим ему свойство animation в следующем виде:
#:<syntaxhighlight lang="javascript">  
#:<syntaxhighlight lang="javascript">
(val > 20) ? 'animation: changecolor 3s infinite linear;' : ' '
(val > 20) ? 'animation: changecolor 3s infinite linear;' : ' '
</syntaxhighlight>  
</syntaxhighlight>
#:Since the element style can only be changed by a condition involving a value from the MQTT topic, we chose the '''CPU Temperature''' topic and set the condition '''>20'''. This means that the animation will only work when the value of the '''CPU Temperature''' topic is greater than 20.  
#:Так как изменение стиля элемента может происходить только по условию, в котором участвует значение из MQTT топика, то мы выбрали топик '''CPU Temperature''' и задали условие '''>20'''. Это значит, что анимация будет работать, только когда значение топика '''CPU Temperature''' больше 20.  
#Save the dashboard and go to the view.
#Сохраним дашборд и перейдем в просмотр.
== Add external links ==
== Добавление внешних ссылок ==
[[Image : svg-hyperlink.png |300px|thumb|right| Creating a link in Inkscape ]]
[[Image: svg-hyperlink.png |300px|thumb|right| Создание ссылки в Inkscape ]]
</div>


The transition to external links is set at the stage of creating a picture in the Inkscape editor.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Переход по внешним ссылкам задаётся на этапе создания картинки в редакторе Inkscape.
</div>


Create hyperlinks like this:
<div lang="ru" dir="ltr" class="mw-content-ltr">
# Select an element that will serve as a link, then in the context menu Create a link (hyperlink).
Создавать гиперссылки так:
# Insert a link into the opened field.
# Выбрать элемент, который будет служить ссылкой, далее в контекстном меню Создать ссылку (hyperlink).
# Save.
# Вставить в открывшееся поле ссылку.
# Сохранить.
</div>


Now it remains to load the image into the controller and check.
<div lang="ru" dir="ltr" class="mw-content-ltr">
Теперь остаётся загрузить рисунок в контроллер и проверить.
</div>


== Useful Links & Materials ==
<div lang="ru" dir="ltr" class="mw-content-ltr">
* [[Media:Examples SVG-Dashboards.zip|SVG Dashboard Example Archive]]
== Полезные ссылки и материалы ==
* [https://github.com/wirenboard/wb-dashboards- demo Sample panels in the wb-dashboards-demo repository]
* [[Media:Examples SVG-Dashboards.zip|Архив с примерами SVG-панелей]]
* [https://support.wirenboard.com/t/vyvod-dannyh-v-vide-grafika-v-realnom-vremeni/13623/5 How to add to SVG panel link to a graph or another page]
* [https://github.com/wirenboard/wb-dashboards-demo Примеры панелей в репозитории wb-dashboards-demo]
* [https://wirenboard.com/en/pages/wb-software/ Wiren Board Web Interface article]
* [https://support.wirenboard.com/t/vyvod-dannyh-v-vide-grafika-v-realnom-vremeni/13623/5 Как добавить в SVG-панель ссылку на график или другую страницу]
* [[Wiren Board Web Interface | Description of the controller web interface on the wiki]]
* [https://wirenboard.com/ru/pages/wb-software/ Статья о веб-интерфейсе контроллера Wiren Board]
* [https://inkscape.org/en/ Free Inkscape SVG editor]
* [[Wiren Board Web Interface | Описание веб-интерфейса контроллера на вики]]
* [https://inkscape.org/ru/ Свободный SVG-редактор Inkscape]
</div>

Версия 12:53, 4 августа 2023

Другие языки:
Sample SVG Dashboard
Displaying textual information, statuses and interaction with the element

Introduction

On devices in HMI mode.
Watch video

In web interface of the Wiren Board controller, you can create interactive graphical panels. With their help, it is convenient to visualize automation control schemes.

Features:

  • displaying textual or logical information;
  • changing the appearance of the svg element depending on the received information: you can change the style of the element, replace the received value with your own or hide / show elements;
  • influence on actuators: turn on and off the load, change the operating modes of devices.

SVG panels work on mobile devices, but image size needs to be taken into account. If the elements are too small, they will be difficult to use. A good solution would be to separate graphical panels into desktop and mobile ones, which are created taking into account the characteristics of a mobile device.

Fullscreen and HMI modes

In some tasks, you need to hide browser controls and controller web interface panels from the user, for this there is Full screen and HMi modes.

Full-screen mode allows you to switch between panels through the side menu, and in HMI mode, you need to implement the switch yourself: add a button (object) with a URL to the desired panel in the SVG image.

Preparing

Change WebUI Access Level

Administrator level

To change the settings of the controller, you need the Administrator access level, which can be set in the SettingsPermissions section.

After completing the settings, we recommend that you set the access level to User or Operator - this will help you avoid making random mistakes when working with the web interface every day.

Image requirements

The basis for the SVG panel is an svg image, which we recommend creating in Inkscape - it fully supports the SVG standard without deviations.

You can output information to any text elements and set up interactions with any shapes and text.

Release wb-2307 and newer

Inside the svg file, the content tag must not contain other tags. If you uploaded a file to the controller, made a binding, downloaded this file to the computer and it did not open in the editor, open the svg file with a text editor and remove the contents of the content tag. After that you will be able to edit the file in the svg editor.

The image can be of any width and height, as well as with any number of elements.

Release wb-2304 and older

Restrictions:

  • You cannot interact with the rectangle. If necessary, convert it to curves (outline).
  • SVG panel editor ignores grouping. Therefore, if you need to customize the interaction with a composite element, then convert it to a single shape consisting of paths.
  • Inside the svg file, the content tag should not contain other tags. If you uploaded a file to the controller, made a binding, downloaded this file to the computer and it did not open in the editor, open the svg file with a text editor and remove the contents of the content tag. After that you will be able to edit the file in the svg editor.

The image can be of any width and height, as well as with any number of elements.

Creating an SVG panel

An example of creating a panel

Create a new SVG panel:

  1. Go to PanelsList.
  2. In the SVG panel section, click the Add button , the binding editor will open.
  3. Click the Load SVG button and select the SVG image file..

Once uploaded, the image will be displayed on the open page:

  1. Specify links and behavior of svg elements using link editor.
  2. Save the changes and see the result by clicking on the Demo button.

Don't forget to fill in the fields Identifier and Name with the unique ID of the new panel for the machine and the name for the people.

The option Stretch to full screen will fit the panel to the free space.

Syntax

In the Value fields With the Link Editor you can compose simple expressions that contain conditions and simple arithmetic operations.

MQTT topic value

The value from the MQTT topic specified in the Channel field is placed into the val variable.

Conditional expressions

Available operations:

  • > — greater than
  • >= — greater than or equal to
  • < — less than
  • <= — less than or equal to!N !* == — equals
  • != — not equal

Syntax:

 
(CONDITION) ? 'VALUE1' : 'VALUE2'

For example, if the value of the MQTT topic is equal to 1 , then print the value ВКЛ , otherwise — ОТКЛ :

 
(val == 1) ? 'ON' : 'OFF'

Arithmetic operations

Simple arithmetic operations can be performed on a topic received from an MQTT topic:

  • + — addition
  • - — subtraction
  • * — multiplication
  • / — division

For example, output the value АВАРИЯ if the value in the MQTT topic multiplied by 0.1 is greater than 20 and НОРМА otherwise:

 
(val*0.1>20) ? 'ALARM' : 'NORMAL'

Rounding values

Often, values from sensors come with several decimal places, if you do not need such accuracy in the svg panel, then they can be rounded:

 
val.toFixed(n) //round the value of the variable val to n decimal places
val.toFixed(2) //round the value of the variable val to two decimal places 220.238 → 220.24

Link Editor

SVG panel editor

The image is prepared in an external vector editor, but the assignment of links to elements is done in the controller web interface.

Чтобы связать svg-элемент изображения со значениями или событиями, выберите его мышкой, после этого рядом с изображением появятся поля настройки поведения элемента.

Кроме выделения одиночного элемента, можно выделять группу. Для этого зажмите на клавиатуре клавишу Alt и кликните по одному из элементов группы. Будет выделена группа, куда входит элемент. Повторный клик при зажатой клавише Alt выберет группу уровнем выше и так далее до самого верха иерархии.

Группы удобно использовать для создания кнопок: объединили в редакторе прямоугольник и иконку и получилась кнопка.

После настройки всех связи нажмите кнопку Сохранить.

Чтение

Отображение значений из источника в текстовом поле.

Значение из выбранного в поле Канал источника помещается в переменную val, которую нужно указать в поле Значение.

Чтобы вывести значение, просто укажите переменную:

val

К значению можно добавить произвольный текст, например, единицу измерения:

val + ' °C'

Также можно подменить полученное значение, например, заменить его на понятный человеку статус:

(val  == 1) ? 'ВКЛ' : 'ОТКЛ'

Запись в канал

С помощью этой настройки вы можете записать значение в топик при клике пользователя по элементу.

Доступно два состояния ON и OFF. При клике пользователя на элементе, значение в MQTT-топике будет меняться на противоположное.

Выберите в поле Канал MQTT топик для записи значений, а в полях Значение включенного состояния и Значение выключенного состояния укажите какие значения соответствуют состояниям.

Например, для переключения реле нужно указать:

Значение включенного состояния = 1
Значение выключенного состояния = 0

Переход и смахивания

Создание перехода

С помощью переходов можно создавать многостраничные интерфейсы:

  1. Нарисуйте для каждой страницы свой рисунок.
  2. Загрузите эти рисунки в контроллер.
  3. Выберите для одного из трёх событий панель, куда надо переходить.

Доступны события: одиночное и длинное нажатие, а также смахивание влево и вправо.

По одиночному и длинному нажатию доступен переход на SVG и текстовые панели, а по смахиванию — только SVG. Это архитектурное ограничение, которое мы пока не модем устранить.

Видимость

Здесь можно указать при каком условии показывать элемент изображения. По умолчанию элемент будет скрыт и отобразится только пока выполняется условие.

Выберите в поле Канал MQTT-топик, на информацию из которого будет реагировать элемент, в поле Условие выберите условие, а в поле Значение — значение.

Стиль оформления

Позволяет изменять стиль элементов изображения. Можно использовать для создания обратной связи для действий, оповещения пользователя о событии т.д.

Доступные для стилизации свойства элемента:

  • fill — цвет заливки;
  • fill-opacity — непрозрачность заливки, значения от 0.0 до 1.0 или в процентах;
  • stroke — цвет обводки;
  • stroke-width — толщина обводки;
  • stroke-dasharray — вид пунктирной обводки, задается в единицах длины или процентах.
  • stroke-opacity — непрозрачность обводки, значения от 0.0 до 1.0 или в процентах.

Цвета можно задавать именами black, red, yellow и т.п. или шестнадцатеричными значениями #ffe680ff, #4f4f4dff и т.п..

Изменим цвет элемента в зависимости от состояния реле, если в топике значение 1, то закрашиваем объект желтым, иначе — серым:

(val == 1) ? ';fill: yellow' : ';fill: gray'

Сделаем так, чтобы при значении больше 20 обводка элемента стала красного цвета, пунктиром и толщиной 2px. При значениях меньше или равно 20 стиль элемента оставим по умолчанию:

(val > 20) ? 'stroke: red; stroke-width:2px; stroke-dasharray:2,1' : ''

Редактирование

Панель

Чтобы внести изменения:

  1. Откройте SVG-панель.
  2. Нажмите кнопку Редактировать.
  3. Внесите изменения и сохраните их нажатием на кнопку Демонстрация.

SVG-изображение

Релиз wb-2307 и новее

В SVG-панелях используются встроенные в файл идентификаторы (тег id), поэтому для редактирования панели просто внесите изменения в рисунок и загрузите новую версию в контроллер.

Важно! Если вы сделали привязку к группе элементов, то не разгруппировывайте эту группу! Если вам надо её изменить, просто войдите в группу в Inkscape и добавьте или удалите элементы.

Релиз wb-2304 и старее

Редактор SVG-панели в момент привязки действий к элементу прописывает data-svg-param-id, поэтому для редактирования изображения нужно его загрузить с контроллера на компьютер:

  1. Откройте SVG-панель для редактирования.
  2. В верхней части окна нажмите кнопку Download, на компьютер загрузится svg-файл.
  3. Отредактируйте файл в Inkscape. В Adobe Illustrator редактировать такие файлы не рекомендуем — теряются привязки, про другие редакторы информации нет.

При редактировании учтите, что если на svg-элемент была назначена связь, то он содержит скрытый data-svg-param-id и при его дублировании создается новый элемент с тем же data-svg-param-id.

Отредактируйте полученный svg-файл и вновь загрузите его на контроллер:

  1. В окне редактирования нажмите кнопку Выберите файл.
  2. После того, как кнопка Change станет активной, нажмите на нее.

Перенос на другой контроллер

Иногда нужно сделать резервную копию svg-панели, например, для переноса на другой контроллер. Для этого нужно сохранить преобразованный редактором svg-файл и описание его связей и загрузить их на другой контроллер.

Учтите, что на имена MQTT-топиков на обоих контроллерах должны совпадать. Если это не так — svg-элементы нужно будет привязать к новым MQTT-топикам.

Сохранение

Сохраните svg-файл и описание связей:

  1. Скачайте файл с контроллера на компьютер. Для этого нажмите на кнопку с изображением стрелки вниз.
  2. В редакторе svg-панели нажмите кнопку В виде JSON, скопируйте и сохраните строки в файл.

Загрузка

  1. Создайте новую SVG-панель по инструкции в разделе Создание SVG-панели.
  2. В редакторе svg-панели нажмите кнопку В виде JSON, скопируйте из сохраненного файла описание связей и вставьте текст в поле
  3. Нажмите кнопку Сохранить внизу страницы.

Анимация элементов SVG-панели

Пример анимации элемента SVG-панели

Элементы SVG-панели можно анимировать с помощью CSS.

Для этого нужно:

  1. Нарисовать SVG-панель в векторном редакторе, например, Inkscape.
  2. Открыть файл SVG в текстовом редакторе и добавить блок стилей, заключенный в теги <style></style>.
  3. В блоке стилей добавить правило @keyframes.
  4. Сохранить файл и загрузить его в контроллер.
  5. Перейти в редактор SVG-панели в веб-интерфейсе контроллера.
  6. Активировать параметр Style и задать в поле Value свойство animation. Также нужно задать условие при котором анимация будет срабатывать.

Визуализация в CSS осуществляется с помощью свойства animation и правила @keyframes.

@keyframes, или ключевые кадры, содержат информацию о том как должен выглядеть элемент в каждый из моментов времени.

Правило содержащее два ключевых кадра будет выглядеть так:

@keyframes <имя кейфрейма> {
from: { описание начального состояния элемента }
to: { описание конечного состояния элемента }
}

Здесь from и to ключевые слова обозначающие начальную и конечную точки анимации. Вместо них можно использовать 0% и 100%, а также добавить промежуточные значения.

Имя кейфрейма — идентификатор, по которому правило будет вызываться из описания стилей.

Чтобы анимация заработала нужно задать стилю элемента свойство animation.

Свойство animation задаёт параметры действия для анимации (длительность анимации, повторение, направление, тип движения, шаги), а в блоке @keyframes задаётся сама анимация по шагам (изменения вида и положения).

Покажем на примере создание анимации для изменения цвета текста с красного на зеленый и обратно. Так как в SVG текст выполняется заливкой, то потребуется изменять свойство fill.

Свойство animation задается в поле Value параметра Style
  1. Создадим новый SVG-документ в редакторе Inlskape и добавим в него элемент Текст.
  2. Сохраним файл и откроем его в текстовом редакторе.
  3. Добавим блок style следующего вида:
      <style>
    @keyframes changecolor {
       0% {fill:red}
       50% {fill:green}
       100% {fill:red}
       }
      </style>
    
  4. Сохраним SVG-файл и загрузим его в контроллер.
  5. В редакторе дашбордов выберем созданным тестовый элемент и зададим ему свойство animation в следующем виде:
    (val > 20) ? 'animation: changecolor 3s infinite linear;' : ' '
    
    Так как изменение стиля элемента может происходить только по условию, в котором участвует значение из MQTT топика, то мы выбрали топик CPU Temperature и задали условие >20. Это значит, что анимация будет работать, только когда значение топика CPU Temperature больше 20.
  6. Сохраним дашборд и перейдем в просмотр.

Добавление внешних ссылок

Создание ссылки в Inkscape

Переход по внешним ссылкам задаётся на этапе создания картинки в редакторе Inkscape.

Создавать гиперссылки так:

  1. Выбрать элемент, который будет служить ссылкой, далее в контекстном меню Создать ссылку (hyperlink).
  2. Вставить в открывшееся поле ссылку.
  3. Сохранить.

Теперь остаётся загрузить рисунок в контроллер и проверить.