Skip to content

Commit 0da1a51

Browse files
committed
feat: add blog
1 parent f4c210c commit 0da1a51

File tree

5 files changed

+2867
-1973
lines changed

5 files changed

+2867
-1973
lines changed

docs/en/posts/lvgl开发过程.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
---
2+
title: LVGL development process
3+
date: 2024-05-23 11:16:32
4+
tag:
5+
- lvgl
6+
category:
7+
- front-end development
8+
---
9+
10+
## Background
11+
12+
I just took on a new project, doing `c++` page development. Since I hadn't been involved in this kind of development before, I'm writing down the process here and also commemorating the approximately 20 days of development. About 50% of the time was spent getting familiar with `lvgl` development, its rendering process, syntax, APIs, and so on. Around 30% of the time was used for compilation and testing, and only the remaining time was actually used for writing code. During this process, the newly added logic led to a continuous growth of corresponding code branches, which required me to spend more time understanding the code later. In the end, I managed to complete the task, but I'm not entirely satisfied with the overall robustness, cleanliness, and readability of the code.
13+
14+
## Style
15+
16+
Due to time constraints, I didn't install a suitable code style management plugin, and the original project also had inconsistent styles, such as mixing tabs and spaces, and inconsistent method alignment. Therefore, I could only maintain a consistent style for the pages I added. Maintaining a consistent project style is actually a high return on investment, as it not only facilitates code reading, but also makes it easier for successors to learn. A healthy project especially needs to pay attention to this point.
17+
18+
## Common Code
19+
20+
Building common code is very important. I've come to realize that "c++" loves reinventing the wheel, but it's not necessary to write a set of wheels for each page in a project. The same goes for modifying gui styles, such as the `disable` and `active` states of buttons that almost every page will have. I think it's entirely possible to abstract these out, rather than having to reset text colors, background colors, and so on each time. For example:
21+
22+
```c++
23+
static void setBtnActive(lv_obj_t* btn){
24+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, LIGHT_BTN_NORMAL);
25+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, LIGHT_BTN_PRESSED);
26+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, GUI_COLOR_BLACK);
27+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, GUI_COLOR_BLACK);
28+
}
29+
static void setBtnDefault(lv_obj_t* btn){
30+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, GUI_DEF_BTN_COLOR);
31+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, GUI_SELECT_BTN_COLOR);
32+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, GUI_COLOR_WHITE);
33+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, GUI_COLOR_BLACK);
34+
}
35+
```
36+
37+
This is very simple, yet very necessary, just like how "element-ui" greatly reduces the mental burden of frontend development, a relatively complete ui component can achieve the same effect. It's a pity that "lvgl" doesn't have this, and this project doesn't either.
38+
39+
It seems that "c++" doesn't have package management, nor does it have a tool similar to "npm," which makes the process of referencing libraries relatively complex and lacks that kind of open-source community. At the same time, the high cost of version updates and the fact that a project is only targeted at the current state of a piece of hardware seems to lack the motivation to consider migration and adaptation. Making modifications to a new project based on an old one seems to be a common problem.
40+
41+
## Data Integration
42+
43+
Integration with interfaces is one of the most troublesome issues. Since I only found the cJSON library, I will only talk about the data integration issues related to cJSON.
44+
45+
1. Nesting: For a data structure with many layers of nesting, it requires more effort to obtain the corresponding values. When there are multiple nested arrays, for loops can become a disaster.
46+
2. Modification: When you need to make changes to the data for a certain requirement, you need to pay attention to the difference in references to ensure that the original data is not destroyed.
47+
3. Variables: Storing variables in an appropriate way requires extra attention to the differences between `char[], char*, string`, and proficiency in their assignment, conversion, and other operations.
48+
4. Passing values: When your cJSON*object needs to be passed as a variable, you can first convert it to char*, which may be helpful when unknown errors occur.
49+
50+
## Efficiency
51+
52+
`c++` is fast, and so is `lvgl`. I always thought that creating a `map` to map the index of a `button` in a `vector` would improve the runtime efficiency, but when I tried to get the index through a `for` loop, I didn't find the runtime efficiency decrease, perhaps it's due to the amount of data. In any case, use `for` loops more, although they may not look good, they are at least easy to implement.
53+
54+
Implementing multi-level nested multi-select using `lvgl` is painful, but this is already the most complex functionality in this project. Designing a good data structure to implement this can achieve twice the result with half the effort, as for gui, it doesn't need to be overthought, even if it uses a `for` loop, it can meet basic requirements.
55+
56+
Many design concepts of `lvgl` are inspired by `css`, but you need to confirm its version before you start working on it. Also, this is not html, its position does not change with the content, so when you need to change the position, remember to modify the position of the child objects as well.
57+
58+
## Conclusion
59+
60+
`lvgl` is actually very easy to get started with, even for someone like me who isn't very familiar with `c++`, it can be used to implement functionality. Correspondingly, for performance reasons, `lvgl` does not provide a very complete set of functional components, and the implementation of these functions should be further encapsulated by the project architecture. Otherwise, mixing functionality and business on the page will lead to a heavier mental burden.
61+
62+
> This post is translated using ChatGPT, please [**feedback**](https://github.com/linyuxuanlin/Wiki_MkDocs/issues/new) if any omissions.

docs/es/posts/lvgl开发过程.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
---
2+
title: Proceso de desarrollo lvgl
3+
date: 2024-05-23 11:16:32
4+
tag:
5+
- lvgl
6+
category:
7+
- desarrollo front-end
8+
---
9+
10+
## Background
11+
12+
Acabo de tomar un proyecto para desarrollar en `C++` y debido a que nunca antes me había involucrado en este tipo de desarrollo, he decidido documentar el proceso aquí, al mismo tiempo que conmemoro aproximadamente 20 días de tiempo de desarrollo. Aproximadamente el 50% del tiempo lo dediqué a familiarizarme con el desarrollo de `lvgl`, su proceso de renderizado, sintaxis, API, etc. El 30% restante lo empleé en compilar, probar, y solo el tiempo restante lo invertí en la escritura de código real. Durante este proceso, la lógica recién agregada hizo que las ramas de código correspondientes fueran creciendo constantemente, lo que significó que me llevaría más tiempo comprender el código más adelante. Al final, logré completar la tarea, pero no quedé satisfecho con la robustez, limpieza y legibilidad del código en general.
13+
14+
## Estilo
15+
16+
Debido a la falta de tiempo, no instalé ningún complemento de gestión de estilo de codificación adecuado, y el proyecto original tampoco tenía una convención de estilo unificada, lo que ocasionaba la mezcla de tabulaciones y espacios, la alineación de métodos, entre otros problemas. Por lo tanto, solo pude mantener un estilo coherente en las páginas que recién agregué. Mantener un estilo de código uniforme es una actividad muy rentable en términos de inversión, ya que no solo facilita la lectura del código, sino que también facilita el aprendizaje para quienes lo aborden más adelante. Este aspecto es especialmente crucial para la salud de un proyecto.
17+
18+
## Código compartido
19+
20+
El desarrollo de código compartido es clave. Me he dado cuenta de que en `C++` se tiende a reinventar la rueda, pero no es necesario crear una nueva instancia de la misma rueda para cada página en un proyecto. Lo mismo ocurre con las modificaciones de estilos de interfaz gráfica: por ejemplo, la forma en que se desactiva y activa un botón que aparece en casi todas las páginas. Considero que estos aspectos pueden abstraerse para evitar tener que configurar repetidamente el color del texto, el color de fondo, etc. Por ejemplo:
21+
22+
```c++
23+
static void setBtnActive(lv_obj_t* btn){
24+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, LIGHT_BTN_NORMAL);
25+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, LIGHT_BTN_PRESSED);
26+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, GUI_COLOR_BLACK);
27+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, GUI_COLOR_BLACK);
28+
}
29+
static void setBtnDefault(lv_obj_t* btn){
30+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, GUI_DEF_BTN_COLOR);
31+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, GUI_SELECT_BTN_COLOR);
32+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, GUI_COLOR_WHITE);
33+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, GUI_COLOR_BLACK);
34+
}
35+
```
36+
37+
Esta es una solución simple pero necesaria, al igual que `element-ui` reduce considerablemente la carga mental del desarrollo frontend, un componente de UI relativamente completo podría hacer lo mismo, pero lamentablemente `lvgl` no lo ofrece, y tampoco este proyecto.
38+
39+
Al parecer, `C++` no cuenta con un sistema de gestión de paquetes similar a `npm`, lo que dificulta el proceso de referencia de bibliotecas, y tampoco cuenta con una comunidad de código abierto como esa. Además, el alto costo de actualizar las versiones y el enfoque en la situación de hardware específica complican la posibilidad de migrar o adaptar un proyecto. Es común encontrarse con este problema al trabajar en un nuevo proyecto manteniendo uno anterior.
40+
41+
## Integración de datos
42+
43+
La integración con las interfaces es uno de los problemas más complicados. Dado que solo encontré la biblioteca cJSON, me centraré en los problemas relacionados con la integración de datos a través de cJSON.
44+
45+
1. Anidamiento: Para desglosar datos con varios niveles de anidamiento, se requiere un esfuerzo mayor para extraer los valores correspondientes, y si hay varios arrays anidados, los bucles `for` pueden convertirse en un desastre.
46+
2. Modificación: Cuando necesitas realizar modificaciones en los datos por ciertas necesidades, debes prestar atención a las diferencias en las referencias para asegurarte de que los datos originales no se vean afectados.
47+
3. Variables: Almacenar las variables de manera adecuada requiere una atención adicional a las diferencias entre `char[]`, `char*`, y `string`, y dominar las operaciones de asignación y conversión entre ellas.
48+
4. Paso de valores: Si necesitas enviar un objeto cJSON* como una variable, primero puedes convertirlo en un `char*`, lo cual podría ser útil en caso de que ocurran errores desconocidos.
49+
50+
## Rendimiento
51+
52+
`C++` es rápido y también `lvgl`. Anteriormente, pensaba que crear un `map` para hacer coincidir el índice de un `button` en un `vector` mejoraría la eficiencia del proceso, pero cuando intenté obtener el índice mediante un bucle `for`, no noté que la eficiencia se redujera, quizás debido al tamaño de los datos. En resumen, es mejor usar bucles `for`, a pesar de que no sean tan legibles, al menos son fáciles de implementar.
53+
54+
Implementar selección múltiple en varias capas con `lvgl` resultó ser doloroso, pero esta funcionalidad compleja ya representa el mayor reto de este proyecto. Diseñar una estructura de datos adecuada podría simplificar el trabajo considerablemente, y en lo que respecta a la interfaz gráfica, no es necesario preocuparse demasiado, ya que incluso con un bucle `for`, se pueden cumplir los requisitos básicos.
55+
56+
Muchos principios de diseño de `lvgl` se inspiran en `css`, pero es importante confirmar su versión antes de utilizarlo. Además, `lvgl` no es HTML, por lo que no se ajusta automáticamente, por lo que si necesitas cambiar su posición, recuerda ajustar también la posición de sus elementos secundarios.
57+
58+
## Conclusión
59+
60+
`lvgl` es fácil de usar, incluso para alguien como yo, que no tiene un gran dominio de `C++`, puedo usarlo para implementar funcionalidades. Sin embargo, en términos de rendimiento, `lvgl` no proporciona una gama completa de componentes funcionales; esa tarea debería ser delegada a la arquitectura del proyecto para su posterior encapsulación. De lo contrario, la mezcla de funciones y negocios en las páginas aumentaría la carga mental.
61+
62+
> Este post está traducido usando ChatGPT, por favor [**feedback**](https://github.com/linyuxuanlin/Wiki_MkDocs/issues/new) si hay alguna omisión.

docs/posts/lvgl开发过程.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
---
2+
title: lvgl 开发过程
3+
date: 2024-05-23 11:16:32
4+
tag: ["lvgl"]
5+
category: ["前端开发"]
6+
---
7+
8+
## 背景
9+
10+
新接了项目,做`c++`页面的开发,由于之前没有接触过相关的开发,在此记录下过程,同时也纪念下二十天左右的开发时长。大约50%左右的时间用在熟悉`lvgl`开发,它的渲染过程,语法,API等方面,30%左右的时间用来编译,测试,只有剩下的时间是真正用来编写代码的。在这个过程中,新加的逻辑,对应的代码分支在不断增长,也会让后来的我需要更长的时间理解代码,最后磕磕绊绊,算是完成了任务,但我对代码的整体健壮性,整洁度,可读性都不太满意。
11+
12+
## 风格
13+
14+
由于时间紧迫,我并没有安装一个合适的代码风格管理插件,原项目也存在风格不统一的情况,tab和空格混用,方法对齐之类,因此我只能在我新加的页面中保持风格统一。保持项目风格的统一其实是一件投入产出比很高的事情,因为这不仅方便代码阅读,也方便后来者接手学习,一个健康的项目尤其需要注意这点。
15+
16+
## 公共代码
17+
18+
公共代码建设是很重要的一点,`c++`爱造轮子我算是见识到了,但在一个项目中倒是不必每个页面都写一套轮子,对gui样式的修改也是如此,比如几乎每个页面都会有的按钮,设置它的`disable``active`状态,我觉得完全可以抽象出来,而不必每次都去重新设置文字颜色,背景颜色等。比如:
19+
20+
```c++
21+
static void setBtnActive(lv_obj_t* btn){
22+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, LIGHT_BTN_NORMAL);
23+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, LIGHT_BTN_PRESSED);
24+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, GUI_COLOR_BLACK);
25+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, GUI_COLOR_BLACK);
26+
}
27+
static void setBtnDefault(lv_obj_t* btn){
28+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, GUI_DEF_BTN_COLOR);
29+
lv_obj_set_style_local_bg_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, GUI_SELECT_BTN_COLOR);
30+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_DEFAULT, GUI_COLOR_WHITE);
31+
lv_obj_set_style_local_text_color (btn, GUI_BTN_PART_MAIN, GUI_STATE_PRESSED, GUI_COLOR_BLACK);
32+
}
33+
```
34+
35+
这很简单,也很有必要,就像`element-ui`大大减小了前端开发的心智负担,一个相对完整的ui组件也能做到同样的事情,很可惜`lvgl`并没有,这个项目也没有。
36+
37+
`c++`似乎没有包管理,没有类似`npm`的工具,导致其引用库的过程相对复杂,也没有那种开源的社区。同时版本的更新成本高,一个项目只针对一个硬件的现状导致了其似乎没有动力考虑迁移,适配的问题。新项目在老项目上修修改改也能做,这似乎是个普遍的问题。
38+
39+
## 对接数据
40+
41+
和接口对接是最麻烦的问题之一,由于我只找到了cJSON库,所以只谈谈cJSON对接数据的问题。
42+
43+
1. 嵌套: 对于一个有很多层嵌套的数据解构来说,需要耗费更大的精力来获取对应的值,当其中包括多个嵌套数组的话,for循环会成为一个灾难。
44+
2. 修改:当你出于某种需求需要对数据做些修改时,需要注意引用的区别,确保原数据不会被破坏。
45+
3. 变量:把变量以合适的方式存储,需要额外注意 `char[],char*,string` 的区别,熟练掌握它们之间的赋值,转换等操作。
46+
4. 传值:当你的cJSON*对象需要作为变量传递时,可以先把它转成char*,在出现未知错误的时候这一点可能有帮助。
47+
48+
## 快
49+
50+
`c++`很快,`lvgl`也很快。我之前一直觉得创建一个`map`来映射`button`在`vector`中的索引会提高运行效率,但当我尝试过`for`循环获取索引后,并没有发现运行效率变慢,或许是数据量的问题。总之,多用`for`循环,虽然它不是很好看,但至少很容易实现。
51+
52+
用`lvgl`实现多层嵌套的多选很痛苦,但这已经算是这个项目中最复杂的功能了。设计一个好的解构体来实现能事半功倍,至于gui,其实不需要过多考虑,就算是用for循环,也能达到基本要求。
53+
54+
`lvgl`的很多设计理念参考了`css`,但在上手前需要确认它的版本。另外,这不是html,它的位置不会跟随变化,当需要修改位置时,记得把子对象的位置也一起修改。
55+
56+
## 总结
57+
58+
`lvgl`还是很容易上手的,对于我这种`c++`不是很熟悉的人,也能用它来实现功能。相对应的,出于性能的原因,`lvgl`并没有提供很全的功能组件,这些功能的实现应交由项目架构来进行进一步的封装。否则的话,页面混杂着功能和业务,心智负担就较重了。

package.json

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,28 +42,28 @@
4242
"@vueuse/core": "10.5.0",
4343
"echarts": "5.4.3",
4444
"lodash-es": "4.17.21",
45-
"naive-ui": "^2.35.0",
46-
"wasm-feature-detect": "^1.6.0"
45+
"naive-ui": "^2.38.2",
46+
"wasm-feature-detect": "^1.6.1"
4747
},
4848
"devDependencies": {
4949
"@antfu/eslint-config": "0.43.1",
5050
"@commitlint/cli": "18.2.0",
5151
"@commitlint/config-conventional": "18.1.0",
5252
"@types/color": "3.0.5",
53-
"@types/emscripten": "^1.39.9",
53+
"@types/emscripten": "^1.39.12",
5454
"@vuepress/client": "2.0.0-beta.67",
5555
"eslint": "8.52.0",
5656
"husky": "8.0.3",
57-
"katex": "^0.16.9",
57+
"katex": "^0.16.10",
5858
"lint-staged": "15.0.2",
5959
"markdownlint-cli": "0.37.0",
6060
"mathjax-full": "^3.2.2",
6161
"prettier": "3.0.3",
6262
"sass-loader": "13.3.2",
6363
"sort-package-json": "2.6.0",
64-
"taze": "^0.12.0",
64+
"taze": "^0.12.3",
6565
"typescript": "5.2.2",
66-
"unocss": "^0.57.1",
66+
"unocss": "^0.57.7",
6767
"vue": "3.3.7",
6868
"vue-router": "4.2.5",
6969
"vuepress": "2.0.0-beta.67",

0 commit comments

Comments
 (0)