• 正文
    • 1、MVC编程模型简介
  • 相关推荐
申请入驻 产业图谱

嵌入式编程模型 | MVC模型

03/10 16:58
1066
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

大家好,我是杂烩君。

嵌入式 / 单片机项目开发中,我们常常会根据实际情况选择大方向的软件框架:裸机系统、前后台系统、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 类作为协调者,持有 Model 和 View 的指针,负责接收用户输入并控制它们的交互。

Config 类表示配置信息,包含配置名称和值。

关联关系

Controller 与 Model、View 之间是聚合关系(has),即 Controller 持有 Model 和 View 的实例。Model 与 Config 之间是组合关系(contains),Model 包含多个 Config 实例。

(2)时序图

(3)运行

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

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

intmain(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);

    return0;
}

model.c:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include"model.h"

staticvoidupdate_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] = '';
        
        if (strncmp(buf, "READ_CONFIG:", 12) == 0) 
        {
            int config_index = atoi(buf + 12);
            update_config(model, config_index);
        }
    }

    returnNULL;
}

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;
}

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

voidstop_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"

staticvoiddisplay_page(View *view, constchar *config_name, int config_value)
{
    printf("当前页面: %dn", view->current_page);
    printf("业务配置: %s, 值: %dn", 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] = '';

        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);
        }
    }

    returnNULL;
}

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;
}

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

voidstop_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
staticint page_config_map[PAGE_CONFIG_MAP_SIZE] = {0};

staticvoidinit_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");
            }
        } 
        elseif (input[0] == 'q') 
        {
            stop_model(controller->model);
            stop_view(controller->view);
            close_message_queue(controller->mq);
            exit(0);
        }
    }

    returnNULL;
}

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;
}

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

voidstop_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模型的分享,如果觉得文章有帮助,麻烦帮忙转发,谢谢!

点赞1
收藏
评论
分享
加入交流群
举报

相关推荐

登录即可解锁
  • 海量技术文章
  • 设计资源下载
  • 产业链客户资源
  • 写文章/发需求
立即登录

本公众号专注于嵌入式技术,包括但不限于C/C++、嵌入式、物联网、Linux等编程学习笔记,同时,公众号内包含大量的学习资源。欢迎关注,一同交流学习,共同进步!