2. 网关操作系统定制与裁剪
任务目标
为工业IoT边缘智能网关定制Linux操作系统镜像,通过Yocto Project裁剪内核与用户空间,生成一个仅包含网关核心功能的最小可启动镜像。本案例聚焦于构建流程与裁剪策略,而非从零编写完整发行版。
环境与依赖
- Ubuntu 20.04+ 主机,至少50GB磁盘空间
- Yocto Project 4.0 (Kirkstone) 或更高版本
- 已初始化的Yocto构建环境(
oe-init-build-env)
实现方案
基于Yocto的local.conf与image recipe实现系统裁剪。核心策略:
1. 使用IMAGE_FEATURES移除开发与调试包;
2. 通过PACKAGE_EXCLUDE排除不需要的运行时组件;
3. 自定义内核配置片段,禁用网关不需要的驱动与子系统;
4. 生成一个包含SSH服务、Modbus TCP网关程序及最小运行时依赖的ext4镜像。
关键完整代码
# 文件1: build/conf/local.conf (关键裁剪配置)
# 移除文档、开发包与调试工具
IMAGE_FEATURES_remove = "dbg-pkgs dev-pkgs tools-sdk tools-debug doc-pkgs"
# 排除不需要的包
PACKAGE_EXCLUDE = "bash perl python3-core vim tzdata"
# 使用Musl减小体积(可选,若需glibc兼容则注释)
# TCLIBC = "musl"
# 启用镜像压缩
IMAGE_FSTYPES = "ext4.gz"
# 减小内核模块数量
MACHINE_EXTRA_RRECOMMENDS_remove = "kernel-modules"
# 文件2: meta-custom/recipes-kernel/linux/linux-yocto_%.bbappend
# 内核裁剪配置片段
FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"
SRC_URI += "file://gateway-kernel.cfg"
# 文件3: meta-custom/recipes-kernel/linux/linux-yocto/gateway-kernel.cfg
# 禁用非网关所需子系统
# CONFIG_BT is not set
# CONFIG_WIRELESS is not set
# CONFIG_SOUND is not set
# CONFIG_USB_NET_DRIVERS is not set
# CONFIG_DRM is not set
# CONFIG_MEDIA_SUPPORT is not set
# CONFIG_HID is not set
# 保留工业以太网与串口
CONFIG_8139CPO=y
CONFIG_SERIAL_8250=y
CONFIG_IP_PNP_DHCP=y
# 文件4: meta-custom/recipes-core/images/gateway-image.bb
SUMMARY = "Minimal Industrial IoT Gateway Image"
LICENSE = "MIT"
inherit core-image
# 仅安装网关运行所需
IMAGE_INSTALL_append = " \
openssh-sshd \
modbus-tcp-gateway \
i2c-tools \
ethtool \
"
# 确保SSH服务开机启动
ENABLE_SERVICE_append = " sshd"
# 设置默认root密码(仅开发用,生产需替换)
inherit extrausers
EXTRA_USERS_PARAMS = "usermod -P 'gateway123' root;"
运行与构建
# 初始化Yocto环境(假设已下载poky与meta-custom层)
source poky/oe-init-build-env build
bitbake-layers add-layer ../meta-custom
# 构建定制镜像
bitbake gateway-image
验证方法
构建完成后,在build/tmp/deploy/images/<machine>/下生成gateway-image-<machine>.ext4.gz。验证步骤:
1. 检查镜像大小:应显著小于默认core-image-minimal(预期约30-50MB压缩后);
2. 使用runqemu或烧录至目标板启动;
3. 登录后执行df -h确认根文件系统挂载正常;
4. 执行ps aux确认无X11、蓝牙、音频等无关进程;
5. 启动网关程序并测试Modbus TCP连接:
systemctl start modbus-gateway && nc -zv <网关IP> 502,端口502应开放。
通过标准:镜像可正常启动,SSH可登录,网关服务运行且502端口可访问,且镜像体积较未裁剪版本减少50%以上。