Skip to content

12.1 Precision Agriculture and Environmental Sensor Networks

12.1.1 Sensing Requirements and Sensor Selection for Precision Agriculture

The engineering starting point of precision agriculture (PA) is turning "watering and fertilizing by experience" into "making decisions from data". What does a farm need to sense? Most projects cut in from three dimensions: soil, weather, and crop physiology. The parameter choices within each dimension directly determine monitoring accuracy and system cost, and they also bound how far the later irrigation strategies and disease models can go.

Soil parameters: the quantitative basis for irrigation and fertilization

Three parameters form the foundation of soil sensing: volumetric water content (VWC), soil temperature, and electrical conductivity (EC). VWC decides when to irrigate; temperature affects root activity and nutrient-uptake efficiency; the EC value reflects the concentration of soluble salts. With these three known, the irrigation decision can be stated as: when soil water content drops below a set threshold, open the solenoid valve and irrigate up to the configured volume; when EC runs high, apply clear water only.

When planning sensor placement, engineers must face the spatial variability of soil texture. There is no copy-ready constant for placement density: it must be calibrated jointly from plot area, soil texture, and budget, and the concrete numbers given in this book are example experience only and must not be transplanted directly. Uniform plots can use sparser placement; in transition zones where texture varies (for example, where sandy loam gives way to clay), probes should be added. Applying different measurement principles to the same parameter yields significantly different results. Frequency Domain Reflectometry (FDR) is low-cost and fast-responding but strongly affected by soil texture; without site-specific calibration, its readings can shift across different soils enough to distort irrigation judgments. Time Domain Reflectometry (TDR) is more accurate, but its circuitry is complex and its power draw higher, making it better suited to research settings or saline-alkali land projects that need high-precision calibration. Capacitive sensors sit in between and suit budget-sensitive projects — on the condition that the engineer accepts this offset and reserves a dead band in the control logic. For mainstream commercial models such as METER Group's EC-5 (whose predecessor brand, Decagon Devices, has been absorbed into METER Group), usable accuracy should be determined from the vendor datasheet together with on-site calibration results; note also that the EC-5 measures volumetric water content only and does not provide soil temperature.

Weather parameters: external driving forces and disease early warning

Air temperature, humidity, light, wind speed, and rainfall form the crop's "weather diary". The temperature-humidity combination correlates directly with disease probability — sustained cold, humid conditions markedly raise the risk of a gray mold outbreak. Photosynthetically Active Radiation (PAR, the 400–700 nm band) constrains the rate of dry-matter accumulation in the crop. Wind speed and rainfall matter especially for open-field cultivation: spraying needs calm weather, and irrigation should be postponed after rain. A complete weather station typically includes a louvered radiation shield, an anemometer with vane, a rain gauge, and a radiometer. One engineering detail that is often ignored: air temperature and humidity sensors must be placed inside a radiation shield, otherwise direct sunlight can push temperature readings several degrees Celsius high — a problem confirmed repeatedly in comparison tests across multiple vendors, and one that engineering teams should treat as a mandatory check at acceptance.

Crop physiological parameters: a plant "checkup"

Sap-flow sensors measure the rate of water ascent in the stem, revealing whether root water uptake is blocked; leaf-wetness sensors detect the water film on leaves and are a core indicator for disease early warning. Mature commercial solutions already exist for these parameters in research-grade monitoring, but because of high on-site maintenance frequency and sensor cost, typical projects start from soil and weather parameters and consider introducing these later, once the system runs stably — this is usually a phase-two or phase-three task for the project.

The main trade-offs in sensor selection

Four dimensions must be weighed together: whether accuracy meets agronomic requirements, whether the interface matches the gateway, whether power draw supports battery supply, and whether cost stays within the project budget. Interface choice is easily underestimated but has a large engineering impact: RS-485 resists interference well and suits long cable runs; SDI-12 is the most widely used low-power serial protocol for agricultural sensors, letting one bus carry multiple probes; I²C suits short board-level connections, with line loss and electromagnetic interference to consider when wiring outdoors. On accuracy, irrigation decisions generally require the absolute error of VWC to be held within a small range — a technical requirement widely accepted in engineering practice; the specific error tolerance should be pinned down with a brief calibration test early in the project, according to crop and soil type.

Table 12-1 Comparison of common agricultural sensors (typical model parameters)

Sensor typeTypical modelMeasured parametersMeasurement rangeAccuracy classInterfaceOperating powerPrice class
Air temperature/humiditySensirion SHT30Temperature/humidity-40–125 °C / 0–100%RHTemperature ±0.3 °C, humidity ±2%RHI²CStandby <1 μA, ~1.5 mA while measuringLow
Soil moistureMETER Group EC-5 (formerly Decagon)VWC (water content only)0–100% VWC±3% VWC in mineral soil (typical)Analog/digital~15 mA while measuringMedium
Soil moistureCapacitive Soil MoistureVWC0–100% VWC±5% VWC (typical)Analog~5 mA while measuringLow
PARApogee SQ-500PAR0–4000 μmol m⁻² s⁻¹±5% (typical)Analog/digital~0.2 mAHigh
Wind speedThree-cup anemometerInstantaneous/average wind speed0–50 m/s±0.5 m/s (typical)Pulse/4–20 mAExtremely low (mechanical)Low–medium
Soil electrical conductivityStevens HydraProbeEC/temperature/moisture0–3000 μS/cm±10% (typical)SDI-12~38 mA while measuringHigh

Note: the accuracies listed are typical engineering parameter ranges; consult the manufacturer's public datasheet for each model. Actual accuracy is affected by installation method, soil type, and ambient temperature, and any volume deployment should perform on-site calibration. Soil EC and irrigation-water EC serve different purposes: the former reflects soil salinity, the latter monitors the concentration of the fertigation solution in drip irrigation; the two are not interchangeable.

Sensor combination for a standard greenhouse node

For a typical greenhouse environment-monitoring node, choose the SHT30 for air temperature and humidity: its I²C interface connects directly to common MCUs, and combined with an intermittent wake-up strategy it can markedly extend battery life. Choose the EC-5 for soil moisture (it measures VWC only), which meets the accuracy that irrigation decisions demand; if the agronomy also calls for a soil-temperature profile, add the same vendor's TEROS 11 or a three-in-one probe. For light, if the budget allows, a PAR quantum sensor carries more agronomic meaning than an ordinary lux sensor — crop photosynthesis is driven mainly by the red and blue light within the visible band. For wind speed, choose a three-cup mechanical anemometer, stable and requiring no extra power supply. This combination covers the key data sources across the three dimensions of "sky–soil–crop" and lays the foundation for later irrigation decisions and disease early warning. If the budget is tight, capacitive probes and the low-cost BH1750 light sensor can substitute, but under strong light their readings deviate considerably from the crop's actual photosynthetic demand — a compromise that suits demonstration projects and is not recommended for direct use in production.

Engineering judgment: a phased path for sensor selection

Sensor selection is not a one-time final decision but a process that upgrades step by step as the IoT platform iterates. A common engineering path: in the first year, use low-cost probes to get the data link and cloud platform working end to end; in the second year, judge from data quality whether it is worth switching to higher-accuracy soil-moisture or PAR sensors. What truly determines the value of a sensor system is often not the absolute accuracy of a single probe but whether placement density matches the soil's spatial variability — on a uniform plot, densifying low-cost probes to four points per hectare may explain more of the in-field variation than sparsely placed expensive probes. Under budget constraints, uniform densification carries more engineering value than high-accuracy sparseness.

Figure 12-1 Precision Agriculture: Three Sensing Dimensions & Sensor Selection Trade-offsSoil, weather, and crop physiology jointly constrain four selection trade-offs: accuracy, interface, power, and cost.Figure 12-1 Precision Agriculture: Three Sensing Dimensions & Sensor Selection Trade-offsThree dimensions supply data · four axes constrain sensor choice · data drives irrigation & disease decisionsThree Sensing Dimensions"Sky–ground–plant" data sources determine monitoring accuracy and system costSoil (ground)Volumetric water content VWCSets "when to irrigate" — the core threshold of irrigation decisionsSoil temperatureAffects root activity and nutrient uptakeConductivity ECReflects soluble salts; high EC → clear water onlyWeather (sky)Air temp & humidityCold + humid sharply raises gray-mold riskLight PAR · wind · rainfallPAR limits dry-matter gain; spray in calm, delay irrigation after rainRadiation shieldMust-check for temp/humidity probes; blocks sun-inflated readingsCrop physiology (plant)Stem-flow sensorMeasures sap-rise rate in stems, revealing blocked root uptakeLeaf wetnessLeaf water film is a core disease-early-warning indicatorIntroduce in phasesHigh maintenance and cost — defer to project phases 2/3Four-Axis Sensor Selection Trade-offWeigh all four at once; interface choice is the most underestimated yet the most consequential1AccuracyMeets agronomic needs?Irrigation decisions need controlled VWC errorFDR lower accuracy / TDR higher accuracy2InterfaceRS-485 · noise-immune, long cable runsSDI-12 · low-power agricultural serial busI2C · short on-board links3PowerSupports battery power?Intermittent wake extends battery lifeSense current: a few mA ~ tens of mA4CostWithin the project budget?Sensors often cost more than comm modulesEvenly spaced low-accuracy beats sparse high-accuracySoil dimensionWeather dimensionCrop physiology dimensionThree dimensions jointly constrain the trade-offsFigure 12-1 Soil, weather, and crop physiology form the "sky–ground–plant" data sources, jointly constraining sensor selection trade-offs on accuracy, interface, power, and cost.
Figure 12-1 Precision Agriculture: Three Sensing Dimensions & Sensor Selection Trade-offs

12.1.2 Topology Design and Deployment Strategy for Environmental Sensor Networks

With the sensors chosen, the next step is keeping these devices working stably in the field — not for a day or two, but on the scale of crop seasons or even years. How to structure the network topology, how to sustain the power supply, and how to make the devices survive outdoor conditions are the three hurdles no deployment stage can avoid.

Star topology: the pragmatic choice for agricultural sensor networks

The typical agricultural picture: tens of sensor nodes scattered over a few to a few dozen hectares, each uploading a temperature or soil-moisture reading every dozen or so minutes. Low node density, mostly uplink data, very little downlink control — for scenarios like this, the star topology is the pragmatic choice.

A standard star network contains two kinds of entities: one or more gateways, and a large number of end nodes. All terminals communicate directly with the gateway, and the nodes maintain no data relay among themselves. A terminal wakes only in its fixed time slot, sends one packet, and goes straight back to sleep — it neither keeps a routing table nor carries any forwarding duty, so the embedded software stays simple and power draw is pressed to the minimum.

Then why is a mesh network rarely used in farmland? Because relaying means a terminal may need to stay in receive mode to forward a neighbor's packets even when it has nothing to send, and this "extra listening" markedly raises average power consumption. Mesh works for Zigbee indoors because mains sockets are everywhere; but a soil-moisture node on a field ridge lives on battery or solar power alone, and any extra reception overhead shortens its life. The conclusion is clear: as long as the gateway's single-hop coverage reaches every node, the star is always the better choice. Only when fields are badly split by hills or tree belts and the gateway simply cannot reach the farthest nodes should relay nodes be added, forming a tree topology — relay nodes alternate between sleep and forwarding, still essentially a variant of the star.

Matching node spacing to communication radius

Once the topology is settled, the real battle is placement spacing. The answer depends entirely on the link budget of the chosen wireless technology and the on-site penetration loss. The link budget estimates the maximum allowable path loss of a wireless link and is the basic parameter for judging whether communication can be reliable.

Take LoRa (Long Range), a common agricultural LPWAN technology: operating in unlicensed Sub-GHz bands, its typical communication radius under line-of-sight conditions can reach several kilometers in open environments. In actual fields, however, once the crop heads out, the stems and leaves absorb and scatter electromagnetic waves markedly more, and the effective communication radius often shrinks substantially. Before deployment, I recommend an on-site penetration test with node and gateway in hand: have a colleague carry the node to the expected farthest position and watch the Received Signal Strength Indicator (RSSI) and Signal-to-Noise Ratio (SNR) received at the gateway. If the margin is insufficient, tighten the grid spacing, or mount the antenna above the crop canopy. The water content of plant leaves attenuates electromagnetic waves significantly, and coverage design in particular needs margin reserved for this.

Gateway siting also matters. The ideal mounting position is the center of the field or its highest point, keeping terminals within line of sight as much as possible. If the terrain is uneven or surrounding buildings block the view, multiple gateways may need to be added to stitch the coverage together.

Power supply: the logic of photovoltaic plus battery

What a farm never lacks is sunlight, and that is exactly the best power source for IoT nodes. Photovoltaic panel plus battery is the de facto standard power combination for today's agricultural sensor nodes.

A typical standalone power module contains a solar panel, a charge-management circuit, and a rechargeable battery. Capacity calculations must begin with the complete load profile, including transmit peaks, sleep leakage, conversion losses, battery temperature derating, self-discharge, and aging, and then validate availability against local monthly solar irradiation and the distribution of consecutive overcast days. Larger panels and batteries only increase the energy margin; they do not solve shading, dust accumulation, low-temperature charging limits, controller failure, or battery-safety problems. Required autonomy days should be set by the data gap the business can tolerate and the maintenance SLA.

Nodes close to facility greenhouses could also consider wired power, but for open fields the trenching cost of buried cabling and the risk of rodent damage are both high. Unless the sensor itself draws too much power (a high-power camera running continuously, for example), photovoltaics plus battery, combined with the extremely low power draw of LPWAN, usually solves the power problem for several growing seasons at once.

Protection rating and installation method

Agricultural equipment must face high temperature, high humidity, salty moist air, insect pests, and mechanical impact. Following industrial practice, outdoor agricultural nodes are usually required to meet no less than IP65 (dust-tight, protected against low-pressure water jets). If the node will be immersed in water — a paddy-field water-level sensor, for example — the rating must rise to IP67.

Beyond the enclosure sealing, several engineering details are often overlooked:

  • Connector waterproofing: the connectors between sensor and main board are the weak link. Even with the whole unit at IP67, if cable joints are not sealed or potted, moisture seeps in by capillary action and causes board-level corrosion. In engineering practice, IP67-rated M12 connectors or epoxy potting of the terminals is the norm.
  • Insect protection: small ants and spiders like to nest on the back of circuit boards and can cause short circuits. Fitting insect screens over the enclosure vent holes, or coating the interior with conformal coating, is reliable insurance in many early-stage projects.
  • Fixing design: nodes in open fields must withstand strong wind, so pole bases need adequate ballast or ground anchors. For soil sensors, burial depth matters as well — too shallow and direct solar heating disturbs the readings; too deep and the sensor no longer reflects moisture changes in the root zone. Sensors are usually buried in the crop's main root distribution layer (for example, 10–30 cm below the surface), with the exact depth depending on the crop.

A well-designed agricultural sensor node typically runs several crop seasons from deployment to its first maintenance. The main later maintenance tasks are cleaning dust off the solar panel surface and replacing aged batteries.

To make the deployment logic above easier to grasp visually, Figure 12-2 shows the topology of a typical environmental sensor network.

Figure 12-2 Environmental Sensor Network Deployment TopologyStar topology: end nodes reach the LoRaWAN gateway in one hop, and the gateway backhauls to the cloud via 4G/wired links.Figure 12-2 Environmental Sensor Network Deployment TopologyStar topology · end nodes one hop to the gateway · data converges upward to the cloudData Asset DomainData retention & governance boundaryCloud Platform / Data HubDB · AI models · dashboards · alertsDevice & Edge DomainField heterogeneous resource boundaryLoRaWAN GatewayField-center pole · 4G/wired backhaulStar one-hop = the root of low powerEnd nodes keep no relay routes and talk only to the gateway;long sleep duty cycles let batteries run for years.4G / Wired BackhaulEnd nodes (multi-sensor)Soil moisture · leaf wetness · light · temp & humiditySoil moistureTemp & humidityLeaf wetnessLightSoil moistureTemp & humidityLeaf wetnessLightDashed · LoRa star uplink (one hop to gateway)Solid · 4G/wired backhaul (gateway→cloud)Purple · data asset domainGreen · device & edge domainGreen dot · end node (sensor)Cylinder · cloud data storageFigure 12-2 The star one-hop design frees end nodes from relay routing, enabling long sleep and multi-year battery life; data rises over LoRa to the gateway, is backhauled via 4G/wired links, and converges upward into the cloud data asset domain.
Figure 12-2 Environmental Sensor Network Deployment Topology

Engineering checklist: key points for agricultural sensor network deployment

Check dimensionVerification itemCommon problem
Topology verificationAre all end nodes within the gateway's single-hop coverage?Crop blocking shortens the communication range; nodes drift or drop off the network.
On-site link testWas a penetration test carried out at different crop heights, such as in wheat and corn fields?Canopy changes (for example, at heading stage) intensify signal attenuation.
Power reliabilityAfter consecutive overcast and rainy days (3–7 days), can the remaining battery capacity still keep the node running?Insufficient winter sunshine lowers battery discharge efficiency; nodes shut down on undervoltage.
Protection ratingDoes the enclosure meet IP65 or above? Are the connectors potted?Condensation or rainwater seeps in through the connectors, causing board-level corrosion.
Insect protectionDo the vent holes have insect screens? Is the circuit board coated with conformal coating?Small insects nest on the back of the board, causing short circuits.
Fixing and installationIs the pole base sturdy enough to resist strong wind? Are soil sensors buried at root-zone depth?Strong wind tilts or dislodges sensors; improper burial depth distorts readings.
Data verificationRun a continuous 24-hour data-reporting test on all nodes before deployment.Individual nodes cannot join the network stably due to firmware issues, leaving gaps in data acquisition.

Once deployment is complete, data starts flowing back, but the data itself cannot directly guide farming. How to compute, from raw values such as soil moisture and leaf wetness, whether a corn field needs irrigation and how much — this is the core question of precision agriculture, and it is where the data center begins to deliver real value.

12.1.3 Agricultural Big-Data Acquisition and Preprocessing

With the sensor network laid out, data begins to converge from the field ridges — but engineers soon face a core contradiction: what sampling frequency is appropriate? Sample too densely, and the battery and bandwidth cannot sustain it; sample too sparsely, and the key turning points of crop growth are missed. Agricultural scenes run far slower than industrial environments, and a lost data point, unlike a production-line fault, is not immediately visible — but that does not mean the acquisition strategy can be casual. The value of agricultural big data lies in being "sufficient" — covering the key turning points of change while placing no strain on the on-site power supply or the uplink channel.

12.1.3.1 Tiered Setting of Acquisition Frequency

Field parameters change at different rates, and the sampling period should be set from the crop stage, soil hydraulic properties, control objective, and power budget. Hourly soil measurements and 15-minute weather measurements can serve as prototype starting points, but they are not universal conclusions. Sample more frequently during initial deployment, compare how different downsampling intervals affect event detection and irrigation decisions, and then use the data to choose the production interval.

Quantifying the actual power consumption requires estimation from module parameters and on-site configuration. Take a typical LoRa module: its transmit current differs from its idle current by one to two orders of magnitude. If the sampling interval is set to 15 minutes and a single transmission lasts about one second, the node spends most of its time in deep sleep. Combined with a low-power MCU's microamp-level standby current, battery-life estimates in real projects routinely come out in months to years. Of course, different crops and growth stages demand different densities — a tomato's root water uptake is most active at fruit set, and CO₂ concentration drops sharply within an hour after sunrise. The prudent approach is to tighten the sampling period early in deployment, run it for one or two complete day-night cycles, and then relax it.

Notably, as on-device AI capability improves (a trend discussed in Chapters 3 and 7), some nodes have begun attempting simple local trend recognition, raising the upload frequency only when abnormal fluctuation is detected. This "event-driven plus periodic sampling" pattern is replacing the rigid fixed-cycle approach, but it demands more MCU compute and more stable algorithms, and for now it remains frontier exploration.

12.1.3.2 Transport Protocol: The Advantages of MQTT in Agriculture

As data travels from node to cloud, the choice of transport protocol directly affects reliability and power consumption. In agricultural scenarios, MQTT (Message Queuing Telemetry Transport) is already the de facto standard — but first its place must be stated correctly: MQTT runs on the gateway-to-cloud backhaul link, not inside LoRa's air interface. The node-to-gateway hop travels as LoRa proprietary frames or the MAC frames defined by the LoRaWAN specification — a payload of only a few dozen bytes cannot fit the overhead of a TCP-plus-MQTT protocol stack; only after the gateway restores the radio frames into sample values does it publish them to the cloud platform over MQTT. MQTT's minimum header is just 2 bytes, it supports the publish/subscribe model, and a session resumes seamlessly after a disconnect and reconnect — advantages that are exactly what the backhaul's IP link (4G or Ethernet) needs.

For nodes that reach the cloud directly over NB-IoT or 4G, the choice between MQTT and CoAP depends on connection persistence, UDP/TCP reachability, the carrier network, power consumption, broker infrastructure, and the security design; it cannot be reduced to "prefer MQTT whenever the library fits." Even with QoS 1, an agricultural alarm receives only at-least-once message delivery and still needs local buffering, application idempotency, timeout escalation, and an offline-alarm strategy.

12.1.3.3 Three-Step Cleaning Before Data Reaches the Cloud

Raw sensor data inevitably picks up noise, packet loss, and disordered timestamps in transit; fed to an AI model unprocessed, the quality of the results drops sharply. The full practice of the three cleaning steps — outlier detection, missing-value imputation, and timestamp alignment: sliding-window 3σ anomaly judgment plus physical-bound filtering, the trade-off between linear interpolation and forward filling, and resampling multi-source data onto "on-the-hour or every-15-minutes" anchor points for alignment — is identical to the framework of industrial data-quality governance in Section 10.3.3 and is not expanded item by item here; the execution order follows the same principle: the gateway applies upper/lower-limit filtering first, the cloud then runs sliding-window checks on the continuous series, and imputation is performed when an alignment anchor lacks data.

What agriculture genuinely needs to settle separately is the difference in interpolation thresholds. Industrial production lines are dominated by second-scale processes, and a gap longer than a few minutes should be flagged as an invalid interval; soil moisture and soil temperature, by contrast, are governed by hour-scale processes — the transition from saturation to drainage after irrigation usually takes more than half an hour — so the applicability threshold of linear interpolation can be relaxed to the hour scale accordingly. Conversely, fast-changing weather parameters such as leaf wetness, light, and wind speed do not enjoy this grace period: a gap longer than one sampling period should be marked as suspect, otherwise the disease early-warning model will take an interpolated stretch of "persistent leaf wetness" for a real disease condition.

Below is an example of acquisition and MQTT publishing on the sensor node side, corresponding to the node form that connects directly to the cloud over Wi-Fi or 4G, written for the ESP8266 (an ESP32 can also run it, but its WiFi library and ADC accuracy differ — adjust per the code comment):

cpp
// Code 12-1 Sensor data acquisition and MQTT publishing example (Arduino framework, ESP8266 as the example;
// on ESP32 the WiFi library is <WiFi.h> and the ADC is 12-bit (0-4095), so the analogRead mapping needs adjusting)

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

#define DHTPIN  D4
#define DHTTYPE DHT22
#define SOILPIN A0
#define SEND_INTERVAL 900000    // 15 minutes

const char* ssid       = "Your_SSID";
const char* password   = "Your_PASSWORD";
const char* mqttServer = "mqtt.yourcloud.com";
const char* mqttTopic  = "farm/field1/soil";

WiFiClient wifiClient;
PubSubClient client(wifiClient);
DHT dht(DHTPIN, DHTTYPE);
unsigned long lastSend = 0;

void connectMQTT() {
  while (!client.connected()) {
    if (client.connect("ESP-node-01")) return;
    delay(5000);
  }
}

void sendData() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  int soilRaw = analogRead(SOILPIN);
  float soilMoisture = map(soilRaw, 0, 1024, 100, 0); // illustrative: map the ADC value to a percentage
  
  char buf[160];
  int len = snprintf(buf, sizeof(buf),
    "{\"type\":\"soil\",\"moisture\":%.1f,\"temperature\":%.1f,\"humidity\":%.1f,\"ts\":%lu}",
    soilMoisture, t, h, millis() / 1000);
  
  if (client.publish(mqttTopic, buf, true)) {
    Serial.println("Published: " + String(buf));
  }
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  
  client.setServer(mqttServer, 1883);
  dht.begin();
}

void loop() {
  if (!client.connected()) connectMQTT();
  client.loop();
  
  if (millis() - lastSend >= SEND_INTERVAL) {
    sendData();
    lastSend = millis();
  }
}

The code logic is straightforward: wake every 15 minutes, read the DHT22 and the soil-moisture sensor, assemble JSON, and publish to the MQTT topic. client.publish(..., true) sets the retain flag, ensuring the last message can still be read by later subscribers after the device goes offline — useful in alarm and reporting scenarios. For routine acquisition, dropping retain is recommended to reduce the broker's storage load.

Only after these three cleaning steps does the data truly qualify for consumption by downstream AI models. In the next section we discuss how this data is used for crop pest and disease recognition, yield prediction, and intelligent irrigation control.

Figure 12-3 Tiered Agricultural Data Collection & Three-Step CleaningAfter tiered collection and MQTT transport, sensor data pass outlier detection, missing-value imputation, and timestamp alignment before AI models consume them.Figure 12-3 Tiered Agricultural Data Collection & Three-Step CleaningTiered collection → MQTT → three-step cleaning → AI models · "good enough" covers key inflection pointsSensor nodeSoil moisture / temp / ECAir temp & humidity / light / CO₂Wind speed / rainfallLow-power MCU · deep sleepTiered collection strategySoil · every 1 hourChanges over minutes~hoursWeather · every 15 minWind/light/CO₂ change fasterMQTT TransportPub/sub · 2-byte minimum headerQoS 0 · at most oncePeriodic soil temperature readsQoS 1 · at least onceThreshold alerts must not be lostThree-Step Cleaning① Outlier detectionSliding-window 3σ · limit filtering② Missing-value imputationLinear interpolation · forward fill③ Timestamp alignmentResample to fixed anchorsAI ModelsDisease recognitionYield predictionIrrigation decisionsKey point: event-driven + periodic samplingOn-device AI spots simple trends locally and raises the upload rate only on anomalous swings;the "good enough" principle — cover key inflection points without straining field power or the backhaul.Collection / transportData cleaningModel consumptionData flowFigure 12-3 Sensor data are collected in tiers by rate of change (soil hourly, weather every 15 minutes); after MQTT transport they go through three cleaning steps — outlier detection, missing-value imputation, and timestamp alignment — before downstream AI models can consume them.
Figure 12-3 Tiered Agricultural Data Collection & Three-Step Cleaning

From Industrial Software to AI Agents · Building a multi-protocol, cloud-native, open-source industrial IoT platform ready to evolve toward AI agents