Course Design Report · 2025-2026 Spring Semester

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.

At a glance

SmartShed is an IoT system for smart agriculture covering the full chain from greenhouse sensing to phone control. Two Hi3861 boards running OpenHarmony handle sensor acquisition and actuator control respectively, relaying messages through an EMQX MQTT service; a HarmonyOS application displays temperature, humidity, light and soil moisture, and provides remote management.

About this project

What it addresses

Greenhouse management requires a stable message chain between acquisition and control, along with the ability to switch between manual and automatic modes. This project connects environmental sensing, soil actuation and phone-side operation into one end-to-end system.

How the two boards divide work

The RGB board handles environmental data acquisition and the SOI board handles actuator control; each runs OpenHarmony and connects to the same MQTT service. Upstream data and downstream commands are separated by agreed topics.

What it uses

The boards run OpenHarmony LiteOS-M with C. The message layer is EMQX MQTT publish/subscribe. The application is a HarmonyOS app written in ArkTS / ArkUI, including a self-implemented MQTT client and an HDS interface.

Current status

Both the embedded and application repositories, along with the course report, are public. The page documents the data flow, hardware mapping, threading design and Glass form adaptation. Physical reproduction requires the corresponding sensors, actuators, network and broker configuration.

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.

Embedded Side

OpenHarmony + Hi3861 × 2
Sensor sampling & actuator control

Server Side

EMQX MQTT Broker
Message relay & Topic routing dispatch

App Side

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)

Hi3861 HiSilicon OpenHarmony 1.0 LiteOS-M CMSIS-RTOS C GPIO PWM I2C ADC AHT20 SSD1306 Paho MQTT lwIP Wi-Fi STA

Server (Communication)

MQTT 5.0 WebSocket Secure EMQX Broker TCP Socket JSON Pub/Sub Topic Routing

App (HarmonyOS)

HarmonyOS 6.1.0 API23 ArkTS ArkUI Stage Model @StorageLink @ObjectLink HDS UIDesignKit Glass Form

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

Publisher

The embedded Hi3861 acts as publisher, packaging sensor data into JSON and sending it to designated Topics.

Broker Relay

EMQX serves as the MQTT Broker, receiving messages and forwarding them to corresponding subscribers per Topic rules.

Subscriber

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"

Sensors
  • AHT20 Temperature & Humidity Sensor — I2C reads temperature and humidity
  • Photoresistor — ADC reads light intensity (0~4095)
Actuators
  • RGB Tri-color LED — GPIO10/11/12 ⇒ PWM1/2/3 controls brightness
Local Display

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"

Sensors
  • Soil Moisture Sensor (replacement install) — ADC reads soil water content
Actuators
  • 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:

Air Temp & Humidity Sampling

AHT20 / I2C

Light Intensity Detection

ADC Sampling

Soil Moisture Reading

ADC Sampling

Fan / LED / Water Pump

GPIO/PWM Control

OLED Display Refresh

SSD1306 Rendering

MQTT Network Communication

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:

Conflict Scenario

The temp/humidity sampling thread and OLED refresh thread read/write I2C0 simultaneously, causing data corruption

Solution

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)

OLED Status printout I2C0-0x78 GPIO13&14 oled_ssd1306.c
Soil Moisture External probe ADC_CH4 soil_moisture_task.c
Water Pump External pump P06 water_pump_task.c
Fan External fan P08 fan_task.c

RGB Board (Environment Sensing)

OLED Status printout I2C0-0x78 GPIO13&14 oled_ssd1306.c
Temp/Humidity Sensor Detect air parameters I2C0-0x44 temp_and_hum_task.c
Photoresistor Detect light intensity ADC_CH4 light_intensity_task.c
Tri-color LED RGB Greenhouse lighting control 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

Manual Mode

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.

Smart Mode

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.

Real-time Monitoring

MQTT callback receives sensor data, @StorageLink state management drives ArkUI auto-refresh of displayed numbers.

Debug Panel

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

Control State

Centrally manages fan levels, pump levels, grow light brightness; @StorageLink shares state across pages.

Parameter Passing

Sensor data and control commands transmitted reliably over MQTT layer in unified format.

Log Sync

GlobalLogBus uniformly collects communication status, operation records, and exception info.

Lifecycle

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

HdsNav Navigation Bar

Immersive light-field top navigation with frosted glass blur effect

PressShadow Gravity Animation

Elastic deformation on button press + light field diffusion feedback

SpringMotion Spring Animation

Staggered delay entry, spring-curve animations for smooth onboarding experience

Visual Style

Dark Light Field

Flowing light background runs through the entire interface, dark mode atmosphere maxed out

Dual-Column Layout

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:

Phone

Single-column vertical scroll, stacked card display

Tablet

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.

Back to projects

05 · FAQ & Conclusion

What you might be wondering, and what this project gave me

Frequently asked questions

Why OpenHarmony rather than Arduino / ESP32?

OpenHarmony gives you a real RTOS (LiteOS-M) with preemptive scheduling, native multithreading and a mature Huawei hardware ecosystem. Arduino / ESP32 is fine for prototyping; this project is about multitasking, mutexes, configurable stacks and conditional compilation. And working with a full operating system rather than a framework is a completely different learning experience.

How long did development take?

About 6 weeks in total: 2 weeks on the embedded side (drivers, multithreading, MQTT), 3 weeks on the HarmonyOS app (a full rewrite from JavaUI API7 to ArkTS API23, an MQTT client written from scratch, HDS design), and 1 week for integration, testing and the report. The app rewrite took the longest — the legacy code was genuinely hard to migrate.

What was the biggest technical challenge?

The I2C bus conflict, without hesitation. The AHT20 and the SSD1306 share the same I2C0 bus, and when the sampling thread and the display thread hit it at the same time it turns into chaos. The fix looks trivial (add a mutex), but finding the cause took nearly two days with a logic analyser. Writing a complete MQTT client from scratch in ArkTS came second — reconnection and thread lifecycle especially.

Which debugging tools did you use?

Embedded side: a USB logic analyser to trace the I2C bus, serial print over UART0 for logs, and MQTTX to watch messages live. HarmonyOS side: DevEco Studio’s built-in debugger, HiLog for system logs, and the GlobalLogBus panel built into the app to follow all MQTT activity in real time. Most valuable? Probably MQTTX — seeing exactly what passes over the broker in real time saved quite a few evenings.

Could this actually be deployed for real?

As a course prototype it is fairly complete. For real deployment a few things are missing: MQTT authentication (there is no password right now), persistence for the smart-mode thresholds (currently held in volatile memory), and an initial setup UI (the WiFi SSID and password are hard-coded). On the hardware side, the Hi3861 is not industrially certified and the low-cost sensors lack calibration. The software architecture is solid though — these would slot in fairly easily.

What did you learn from this project?

Much more than expected. Technically: embedded systems programming, RTOS, IoT protocols, modern mobile app development. Methodologically: how to architect a distributed system end to end, how to manage complexity with clean layers, and how to document it properly. And above all: patience with hardware bugs that make no sense, and the satisfaction of seeing a complete system run end to end — from the sensor to the phone screen.

Project summary

A project from start to finish

From the first line of code to the final defence, SmartShed was a complete journey through the HarmonyOS / OpenHarmony ecosystem. I touched almost every layer of an IoT system: hardware drivers, RTOS, network protocols, mobile app development, interface design, and even a bit of build-chain (GN / Ninja) engineering.

If I had to keep one lesson, it is that complexity is managed through architecture. At first I tried to put everything in a single file — the result was a maintenance nightmare. After refactoring into layers (common / modules / boards) and adopting the Stage model on the app side, every change became targeted and predictable.

Thanks for reading this far. If the project inspires you or you have questions, feel free to get in touch, or explore the source on GitHub — it is fully open-source.