OpenHarmony-Powered Smart Agriculture
— A Smart Greenhouse Control Terminal Based on Hi3861 & HarmonyOS
From sensor data acquisition to real-time mobile control — a complete smart agriculture IoT system.
Two dev boards each doing their job, MQTT message relay, a full-featured HarmonyOS terminal.
Project Overview
Course Design Report for 2025-2026 Spring Semester — Presented by Ray Chen (Chen Zirui)
What Is Smart Shed?
Smart Shed (Smart Greenhouse) is a smart agriculture IoT control system built on Open Source OpenHarmony and Huawei HarmonyOS NEXT. Simply put: two development boards handle sensing and controlling environmental parameters, communicating in real-time with a mobile app via MQTT, ultimately achieving automatic monitoring and intelligent regulation of temperature, humidity, light intensity, and soil moisture inside the greenhouse.
OpenHarmony + Hi3861 × 2
Sensor sampling & actuator control
EMQX MQTT Broker
Message relay & Topic routing dispatch
HarmonyOS NEXT (API23)
Mate 70 Pro+ / MatePad Pro
01 · Project Overview & Tech Stack
Overall architecture, challenges faced, and innovations made
System Architecture: Software-Hardware Co-Design, Vertical Integration
Embedded side collects data → Server side relays messages → Mobile side displays and controls
Embedded Side
OpenHarmony 1.0 Release
Rayawa/rgb @ HiSilicon-Hi3861
Rayawa/soi @ HiSilicon-Hi3861
Sensor sampling + OLED display
PWM/GPIO actuator control
Server Side
MQTT 5.0 WebSocket
wss://broker.emqx.io:8084
@MQTTX
Public network message relay
Topic routing dispatch
App Side
HarmonyOS 6.1.0 (API23)
Smart Shed @ Mate 70 Pro+
Smart Shed @ MatePad Pro 12.2
Real-time data display
Manual / Smart dual-mode
Technical Challenges
Problems actually encountered during development
Embedded Side
- Lots of driver interface version compatibility issues
- I2C bus concurrent multi-device access causes conflicts
- LiteOS-M thread stack size and priorities need constant tweaking
App Side
- The original docs were based on API7 JavaUI — way too outdated
- The old code only ran on specific tablets; switching devices broke the layout completely
- The original design had four separate systems for one expansion board's components — massive refactoring needed
Communication Layer
- MQTT transmission isn't very stable, and error messages are vague
- The Hi3861 WiFi module is aging — poor load capacity
- The app-side send/receive mechanism was bare-bones, almost no error handling, debugging by pure guesswork
Innovations
Dual-Board Separated Architecture
The environment sensing board (RGB) and soil actuation board (SOI) are physically isolated and logically decoupled — each handles its own duties while working together seamlessly.
Zero-Dependency MQTT Client
The HarmonyOS side builds MQTT packets entirely from scratch starting from TCP Socket — zero third-party library dependencies.
HDS Advanced Visual System
Integrated HarmonyOS official Design System component library: immersive navigation, gravity animations, light-field backgrounds.
Manual / Smart Dual Mode
Manual mode gives you free adjustment of levels; Smart mode makes automatic decisions based on thresholds, with a background thread running safely at all times.
Glass Form Factor Adaptation
Built an additional watch-side Glass app form factor with immersive materials and gaseous animation effects.
Reliability Guarantees
Auto offline detection (5s timeout), exponential backoff reconnection on disconnect, GlobalLogBus logging bus as a comprehensive safety net.
Tech Stack
Embedded (Hi3861)
Server (Communication)
App (HarmonyOS)
02 · MQTT Server
Pub/Sub architecture principles and data flow design
Publish/Subscribe (Pub/Sub) Architecture
MQTT is a lightweight messaging protocol purpose-built for low-bandwidth IoT scenarios
Three-Party Collaboration Mechanism
The embedded Hi3861 acts as publisher, packaging sensor data into JSON and sending it to designated Topics.
EMQX serves as the MQTT Broker, receiving messages and forwarding them to corresponding subscribers per Topic rules.
The HarmonyOS App receives sensor data after subscribing to relevant Topics, and can also issue control commands.
Data Flow Design
How data travels from hardware all the way to your phone, and how operations get sent back to hardware for execution
Upstream: Sensor Data → Mobile Display
① Sensor Sampling
Sensors on the expansion board collect raw data → ADC reads light/soil moisture, I2C reads AHT20 temp & humidity
② Package & Send
Hi3861 converts data to JSON format and sends it to EMQX Broker via MQTT PUBLISH packet
③ Route & Dispatch
Upon receiving the message, EMQX distributes it to subscribed clients according to Topic rules
④ Refresh UI
HarmonyOS receives and parses the message → @StorageLink updates state → UI numbers refresh / Smart mode evaluates thresholds
Downstream: User Action → Hardware Execution
① User Action or Auto Trigger
Drag sliders to adjust levels in manual mode, or threshold exceeded in Smart mode auto-generates control commands
② Package & Dispatch
HarmonyOS converts control commands into MQTT packets, dispatched through EMQX
③ Hardware Execution
Hi3861 parses topic and payload upon receiving the message → controls GPIO/PWM output → fan/water pump/grow light activates
03 · Hi3861 Embedded Side
OpenHarmony LiteOS-M + CMSIS-RTOS multi-threading, developed in pure C
Two Dev Boards, Each with Its Own Job
RGB Board (Environment Sensing)
Responsible for "seeing the environment" and "local display"
- AHT20 Temperature & Humidity Sensor — I2C reads temperature and humidity
- Photoresistor — ADC reads light intensity (0~4095)
- RGB Tri-color LED — GPIO10/11/12 ⇒ PWM1/2/3 controls brightness
SSD1306 OLED (128×64) refreshes temperature, humidity, and light data in real time
SOI Board (Soil Actuation)
Responsible for "sensing soil" and "getting work done"
- Soil Moisture Sensor (replacement install) — ADC reads soil water content
- OLED Display — local status printing
- Fan — PWM controls rotation speed
- Water Pump — GPIO controls on/off
Project Structure
Big picture split by function, details split by module — clean and maintainable
common/ Shared Layer
Wi-Fi connection, MQTT communication, OLED drivers all live here. I2C mutex lock is also managed here to prevent multiple threads from fighting over the bus.
modules/ Business Layer
Split into two subdirectories:
- sensors/ — headers and programs for AHT20, light intensity, soil moisture sensors
- actuators/ — control programs for fans, grow lights, water pumps
boards/ Build Layer
Unified management of .gn build files for both dev boards. Conditional compilation dynamically enables modules per board config — adding a new board just means adding one gn file.
Multi-Threading Architecture
CMSIS-RTOS manages parallel tasks under the LiteOS-M real-time kernel
Main Thread Entry Point
- After system boot, SYS_RUN creates the main thread from
smart_shed_all.c, stack size 8KB - The main thread initializes and spawns all sub-threads in sequence: sensor sampling, actuator control, MQTT communication, OLED display
- Conditional compilation dynamically enables corresponding modules per board configuration, unified scheduling entry point
Six Sub-Threads Running in Parallel
Each functional module runs independently inside the LiteOS kernel, each with its own stack space (4KB~8KB) and priority — none block each other:
AHT20 / I2C
ADC Sampling
ADC Sampling
GPIO/PWM Control
SSD1306 Rendering
Paho Publish/Subscribe
I2C Mutex Lock: Solving Bus Conflicts
The AHT20 temperature/humidity sensor and OLED display share the same I2C0 bus (GPIO13 & GPIO14). If two threads access it simultaneously, things break. The solution:
The temp/humidity sampling thread and OLED refresh thread read/write I2C0 simultaneously, causing data corruption
Use i2c0_lock/unlock mutex lock, acquire before every read/write and release after — guarantees only one device occupies the bus at any given moment
Hardware Connection Mapping
SOI Board (Soil Actuation)
I2C0-0x78 GPIO13&14
oled_ssd1306.c
ADC_CH4
soil_moisture_task.c
P06
water_pump_task.c
P08
fan_task.c
RGB Board (Environment Sensing)
I2C0-0x78 GPIO13&14
oled_ssd1306.c
I2C0-0x44
temp_and_hum_task.c
ADC_CH4
light_intensity_task.c
GPIO10/11/12=>PWM1/2/3
led_task.c
Network & Communication
Connect Wi-Fi → TCP established → MQTT sends/receives → actuators spring to action
Communication Flow
Connect Wi-Fi
Connect to SSID "Rayawa", get IP via DHCP then enter lwIP TCP communication
MQTT Encode/Decode
Paho library only handles packet encoding/decoding; the full TCP Socket lifecycle must be managed manually
Report Sensor Data
Sensor data reported to EMQX Broker in JSON format
Execute Control Commands
Upon receiving a PUBLISH packet, parse topic and payload using MQTTDeserialize_publish(), then set global variables via mqtt_apply_command(). Actuator threads continuously read these variables to control GPIO/PWM, driving fans, pumps, and other devices
04 · HarmonyOS App Side
ArkTS · Stage Model · HDS Advanced Visuals · Self-Implemented MQTT Client
Smart Shed App
A full-featured control terminal running on Mate 70 Pro+ and MatePad Pro
Feature Overview
Drag sliders to adjust fan (0-3 levels), water pump (0-3 levels), grow light (0-100%). Auto-syncs current levels to the dev board when entering the page, supports haptic feedback.
Set upper/lower threshold limits for temperature/humidity/light/soil moisture. Periodically polls sensor data and auto-triggers control when out of range. Background resident thread, safely destroyed on page exit to prevent leaks.
MQTT callback receives sensor data, @StorageLink state management drives ArkUI auto-refresh of displayed numbers.
GlobalLogBus event bus records communication status, user actions, and error info for easy troubleshooting.
App Project Structure (Stage Model)
Layered architecture built on ArkTS
AppScope/
Unified entry point for app-level global resources and Hvigor build scripts.
view/ & pages/
ArkTS-built UI layer, containing complete interfaces for manual/smart dual-mode and debug panel.
service/
Encapsulates MQTT client (MqttReceiverClient.ts), TCP Socket direct connection for bidirectional communication, zero third-party dependencies.
viewmodel/
Core data structures and state models ensuring reactive binding between UI and data.
MqttReceiverClient.ts — Building an MQTT Client From Scratch
Why Build It Yourself?
The HarmonyOS side uses zero third-party MQTT libraries — it hand-crafts packets entirely from scratch starting at TCP Socket level. This gives complete control over the entire communication process, making issues much easier to diagnose.
Protocol Layer
- Manually concatenates Fixed Header + Variable Header + Payload
- Implements core packets: CONNECT / PUBLISH / SUBSCRIBE / PINGREQ
- 60s KeepAlive heartbeat for connection persistence
- MQTT 5.0 over WSS direct connection to EMQX public Broker
Reliability Guarantees
- Auto-reconnect on disconnect + exponential backoff
- Single TCP connection with multi-Topic subscription & routing dispatch
- @StorageLink state management decoupled from ArkUI
- GlobalLogBus logging bus records complete communication trail
State & Methods
Centrally manages fan levels, pump levels, grow light brightness; @StorageLink shares state across pages.
Sensor data and control commands transmitted reliably over MQTT layer in unified format.
GlobalLogBus uniformly collects communication status, operation records, and exception info.
Create connection on page enter, destroy threads and release resources on page exit — zero memory leaks.
UI Design: HDS + ArkUI
Not just functional — it has to look good too
HDS Core Components
Immersive light-field top navigation with frosted glass blur effect
Elastic deformation on button press + light field diffusion feedback
Staggered delay entry, spring-curve animations for smooth onboarding experience
Visual Style
Flowing light background runs through the entire interface, dark mode atmosphere maxed out
Tablet-adaptive dual-column layout balancing information density and visual harmony
Animation: Gravity Field
Gravity field effects during page transitions, natural attraction-repulsion animations between elements.
Animation: Light Field
Flowing light background + dual-column dark global light field, dynamic light/shadow flows with interaction changes.
Animation: Transitions
Fade in/out + elastic animations, SpringMotion spring-curve silky transitions.
Responsive Layout
ArkUI responsive grid system automatically adapts to phone and tablet form factors:
Single-column vertical scroll, stacked card display
Dual-column side-by-side, making full use of widescreen space
Smart Shed Glass
Smartwatch form factor — immersive materials + gaseous animations
Glass Form Features
- Immersive Material — interface blends into watch face glass texture
- Gaseous Animations — light and airy transition effects
- Gravity Transitions — maintains consistent interaction language with the main App
- Dual-edge Flowing Light — dynamic decorative elements on both sides of the watch face
HdsButtons Custom Component
Custom button component system based on HDS specifications, unifying visual presentation and touch feedback for all interactive elements in Glass form. Supports multiple sizes and state styles (default/pressed/disabled), works great on small screens too.