嵌入式编程模型 - MVC模型


大家好,我是杂烩君。

嵌入式 / 单片机项目开发中,我们常常会根据实际情况选择大方向的软件框架:裸机系统、前后台系统、RTOS、Linux等。实际开发中,选择什么样的软件架构,只是第一步。

系统里面的各个模块怎么协同工作,业务逻辑怎么设计?也得在项目前期好好考虑,如果是想到哪写到哪,可能后面会受很多苦。

我们有必要学习各种编程模型了(设计模式)。如事件驱动编程模型、消息驱动编程模型、状态机模型等。

编程模型与大方向的软件框架并不冲突,如我们常用的状态机模型,裸机系统也能跑、RTOS也能跑、Linux也能跑。

本篇笔记我们一起来学习MVC编程模型。

1、MVC编程模型简介

MVC(Model-View-Controller)是一种软件设计模式,它将应用程序分为三个主要部分:模型(Model)、视图(View)和控制器(Controller),这种分离有助于提高代码的可维护性、可扩展性和可测试性。

  • 模型(Model):专注于数据管理和业务逻辑。
  • 视图(View):负责呈现数据给用户,它是用户界面的部分。
  • 控制器(Controller):作为模型和视图之间的桥梁,接收用户的输入请求,根据请求调用相应的模型方法进行数据处理,然后选择合适的视图将处理结果展示给用户。

MVC 最初是为 Web 应用程序设计的,但它的思想同样适用于嵌入式系统开发。

如嵌入式场景中:

  • 模型(Model):处理传感器数据采集与处理。
  • 视图(View):处理数据显示(如LCD屏渲染、LED状态指示)。
  • 控制器(Controller):协调输入(如GUI输入、中断处理、用户按键响应)。

MVC的核心优势:

1、结构图

  • 单向依赖:Controller操作Model,View监听Model。
  • 解耦设计:View和Controller不直接交互,Model独立于界面逻辑。

2、时序图

  • 用户输入(如按键)传递到Controller。
  • Controller修改Model数据(如更新传感器状态)。
  • Model通过notifyObservers()回调触发View更新(非Controller直接调用View)。
  • View从Model拉取最新数据并渲染(如刷新LCD显示)。

MVC思想应用实例

下面列举4个例子,一个是我们自己编写的最小MVC demo,另外3个是Github上嵌入式相关的使用到MVC思想的项目。

1、MVC demo

嵌入式中,带GUI界面的产品,会有这种场景:切换GUI界面,业务逻辑读取本地配置数据,刷新到对应GUI界面上。

下面我们针对这种简单的场景编写基于一个简单的基于pthread库的Linux多线程应用实例:

  • 控制器模块:接收用户输入的页面索引,根据映射关系获取对应的配置索引,并向模型模块发送读取配置的请求。
  • 模型模块:根据接收到的配置索引,从配置数组中获取相应的配置信息,并发送给视图模块。
  • 视图模块:接收到配置信息后,将其显示在对应的页面上。

(1)类图

类定义
  • Model 类负责处理配置数据的读取和存储,包含配置数组、线程和消息队列等成员。
  • View 类负责显示页面和配置信息,包含当前页面索引、线程和消息队列等成员。
  • Controller 类作为协调者,持有 ModelView 的指针,负责接收用户输入并控制它们的交互。
  • Config 类表示配置信息,包含配置名称和值。
关联关系
  • Controller 与 Model、View 之间是聚合关系(has),即 Controller 持有 Model 和 View 的实例。
  • Model 与 Config 之间是组合关系(contains),Model 包含多个 Config 实例。

(2)时序图

(3)运行

  1. 终端输入页面索引。
  2. Controller 接收到输入后,根据页面 - 配置映射关系获取对应的配置索引。
  3. Controller 向 Model 发送 READ_CONFIG 消息,请求读取指定配置。
  4. Model 从 Config 中获取相应的配置信息。
  5. Model 向 View 发送 CONFIG 消息,传递配置信息。
  6. View 接收到消息后,显示当前页面和配置信息。

(4)代码

#include <stdio.h>
#include "model.h"
#include "view.h"
#include "controller.h"

int main(void) 
{
    Model *model = create_model();
    View *view = create_view();
    Controller *controller = create_controller(model, view);

    start_model(model);
    start_view(view);
    start_controller(controller);

    pthread_exit(NULL);

    return 0;
}
  • model.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "model.h"

static void update_config(Model *model, int config_index) 
{
    const Config *config = get_config(model->configs, config_index, model->num_configs);

    if (config) 
    {
        char msg[MAX_MSG_SIZE] = {0};

        snprintf(msg, sizeof(msg), "CONFIG:%s:%d", config->name, config->value);
        send_message(model->mq, msg);
    }
}

void* model_thread_func(void *arg) 
{
    Model *model = (Model *)arg;
    char buf[MAX_MSG_SIZE] = {0};

    while (1) 
    {
        ssize_t bytes_received = receive_message(model->mq, buf);
        buf[bytes_received] = '\0';
        
        if (strncmp(buf, "READ_CONFIG:", 12) == 0) 
        {
            int config_index = atoi(buf + 12);
            update_config(model, config_index);
        }
    }

    return NULL;
}

Model* create_model(void) 
{
    Model *model = (Model *)malloc(sizeof(Model));

    if (model == NULL) 
    {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    model->num_configs = MAX_CONFIGS;
    init_configs(model->configs, model->num_configs);
    model->mq = init_message_queue();

    return model;
}

void start_model(Model *model) 
{
    if (pthread_create(&model->thread, NULL, model_thread_func, model) != 0) 
    {
        perror("pthread_create");
        exit(EXIT_FAILURE);
    }
}

void stop_model(Model *model) 
{
    pthread_join(model->thread, NULL);
    close_message_queue(model->mq);
    free(model);
}
  • view.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "view.h"

static void display_page(View *view, const char *config_name, int config_value) 
{
    printf("当前页面: %d\n", view->current_page);
    printf("业务配置: %s, 值: %d\n", config_name, config_value);
}

void* view_thread_func(void *arg) 
{
    View *view = (View *)arg;
    char buf[MAX_MSG_SIZE] = {0};

    while (1) 
    {
        ssize_t bytes_received = receive_message(view->mq, buf);
        buf[bytes_received] = '\0';

        if (strncmp(buf, "CONFIG:", 7) == 0) 
        {
            char config_name[32] = {0};
            int config_value = 0;
            sscanf(buf + 7, "%[^:]:%d", config_name, &config_value);
            display_page(view, config_name, config_value);
        }
    }

    return NULL;
}

View* create_view(void) 
{
    View *view = (View *)malloc(sizeof(View));

    if (view == NULL) 
    {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    view->current_page = 1;
    view->mq = init_message_queue();

    return view;
}

void start_view(View *view) 
{
    if (pthread_create(&view->thread, NULL, view_thread_func, view) != 0) 
    {
        perror("pthread_create");
        exit(EXIT_FAILURE);
    }
}

void stop_view(View *view) 
{
    pthread_join(view->thread, NULL);
    close_message_queue(view->mq);

    free(view);
}
  • controller.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "controller.h"
#include "message_queue.h"

#define PAGE_CONFIG_MAP_SIZE 10
static int page_config_map[PAGE_CONFIG_MAP_SIZE] = {0};

static void init_page_config_map(void) 
{
    for (int i = 0; i < PAGE_CONFIG_MAP_SIZE; i++) 
    {
        page_config_map[i] = i;
    }
}

void* controller_thread_func(void *arg) 
{
    Controller *controller = (Controller *)arg;
    char input[10] = {0};

    init_page_config_map();

    while (1) 
    {
        printf("输入页面索引 (0 - %d) 显示对应页面配置,输入 'q' 退出程序: ", PAGE_CONFIG_MAP_SIZE - 1);
        fgets(input, sizeof(input), stdin);
        if (input[0] >= '0' && input[0] <= '9') 
        {
            int page_index = atoi(input);

            if (page_index >= 0 && page_index < PAGE_CONFIG_MAP_SIZE) 
            {
                controller->view->current_page = page_index;
                int config_index = page_config_map[page_index];

                char msg[MAX_MSG_SIZE] = {0};

                snprintf(msg, sizeof(msg), "READ_CONFIG:%d", config_index);
                send_message(controller->model->mq, msg);
            } 
            else 
            {
                printf("无效的页面索引,请重新输入。\n");
            }
        } 
        else if (input[0] == 'q') 
        {
            stop_model(controller->model);
            stop_view(controller->view);
            close_message_queue(controller->mq);
            exit(0);
        }
    }

    return NULL;
}

Controller* create_controller(Model *model, View *view) 
{
    Controller *controller = (Controller *)malloc(sizeof(Controller));

    if (controller == NULL) 
    {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    controller->model = model;
    controller->view = view;
    controller->mq = init_message_queue();

    return controller;
}

void start_controller(Controller *controller) 
{
    if (pthread_create(&controller->thread, NULL, controller_thread_func, controller) != 0) 
    {
        perror("pthread_create");
        exit(EXIT_FAILURE);
    }
}

void stop_controller(Controller *controller) 
{
    pthread_join(controller->thread, NULL);
    close_message_queue(controller->mq);
    free(controller);
}

篇幅有限,为了不影响阅读体验。其它代码不再贴出。有兴趣的朋友可在本公众号聊天界面输入关键词:MVC例子,即可获取下载链接。

2、Q-Controllers

Q-Controllers是一个事件驱动的应用代码框架,适用于低端单片机无法跑操作系统,但又要处理越来越复杂的代码构架的情况。

https://github.com/q-iot/q-controllers

其借鉴MVC模式,提出D-IO-C分层架构(Data-IO-Controller),将代码分为:

  • Data:数据存储与管理(类似Model层)
  • IO:输入输出硬件操作(如传感器、显示屏驱动)
  • Controller:事件驱动的业务逻辑处理

3、IotSensorDetect

一个基于MVC模式 + 状态设计模式的物联网气体检测开源项目。

https://github.com/Yangyuanxin/IotSensorDetect

MVC模式:

  • Model:传感器数据采集与状态管理(如ModelSensorHandlerTask)
  • View:数据展示(通过云平台或LCD屏)
  • Controller:指令处理与状态协调(如ControllerTask)

4、awtk的计算器例子

基于MVC开发的计算器:

https://github.com/zlgopen/awtk-patterns/tree/master/src/calculator-mvc

Q & A

Q1: 业务逻辑应该写在Controller还是Model?

A:应该写在Model。

已上就是本次关于MVC模型的分享,如果觉得文章有帮助,麻烦帮忙转发,谢谢!



文章作者: 杂烩君
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 杂烩君 !
  目录