Smart Manufacturing

Predictive Maintenance with IoT: A Practical Guide from Sensor to Model

What predictive maintenance with IoT really takes: the sensors that matter, features to compute at the edge, how condition data moves over MQTT to analytics, and the modelling steps from thresholds to anomaly detection.

Predictive maintenance IoT illustration with vibration and temperature sensors on a motor and pump streaming condition data over MQTT to an anomaly chart
Run this on your own MQTT brokerGet a private, managed MQTT broker on the Free plan and start from ready-made code samples.
Try it free Code samples No card required

Predictive maintenance IoT projects succeed or fail on unglamorous details: the right sensor on the right asset, sensible features computed at the edge and a data flow that keeps working for years. This guide walks through each layer, from choosing sensors to moving condition data over MQTT and building models that warn before a failure. You will finish with a reference architecture, working edge code and a step-by-step plan for your first asset.

What Predictive Maintenance Actually Means

Maintenance strategies sit on a spectrum. Reactive maintenance fixes things when they break. Preventive maintenance replaces parts on a fixed schedule whether they need it or not. Condition-based maintenance acts when a measured value crosses a limit. Predictive maintenance goes one step further: it uses trends and patterns in condition data to estimate that a failure is developing, ideally early enough to plan the repair into a scheduled stop.

The value comes from timing. A bearing replaced during a planned weekend stop costs a part and a few hours. The same bearing failing during production costs the part, the unplanned downtime, possibly the shaft or the motor, and the scrap produced while the machine degraded. The difference between condition monitoring and prediction is explained further in condition monitoring vs predictive maintenance.

Choosing Assets and Failure Modes First

Do not start with sensors. Start with a short list of assets where an unexpected failure hurts, and for each one write down how it fails. The failure mode determines the measurement.

Failure mode Early indicator Sensor
Bearing wear Rising high-frequency vibration, later temperature Accelerometer, temperature probe
Imbalance or misalignment Vibration at running speed and its multiples Accelerometer
Pump cavitation Broadband vibration, pressure fluctuation Accelerometer, pressure transmitter
Motor winding or load problems Current change, phase imbalance Current transformers
Gearbox wear Vibration at gear mesh frequencies, oil condition Accelerometer, oil sensor
Belt slip or wear Speed difference, vibration Speed sensor, accelerometer
Overheating Gradual temperature rise at same load Temperature probe, thermal camera
Hydraulic leaks Pressure drop, longer cycle times Pressure transmitter, cycle data

Rotating equipment with vibration-sensitive failure modes is usually the best first target: motors, pumps, fans and gearboxes. See vibration monitoring sensors for choosing accelerometers and motor current monitoring for electrical signatures.

The Predictive Maintenance IoT Architecture

A reliable architecture has four layers:

  1. Sensing. Accelerometers, temperature probes and current sensors mounted on the asset, plus operating context from the PLC (speed, load, running state).
  2. Edge processing. A gateway or microcontroller samples raw signals at high rate and reduces them to features: RMS velocity, peak acceleration, crest factor, kurtosis, band energies, temperature. Raw vibration waveforms are large; features are a few hundred bytes.
  3. Transport. Features and context are published over MQTT to a broker. Analytics, historians, dashboards and alerting each subscribe independently.
  4. Analytics. A service stores the time series, establishes baselines, detects anomalies and estimates trends. Results flow back over MQTT as health scores and alerts.

The broker in the middle is what makes this extensible. You can start with a simple threshold check and add a machine learning service later without touching sensors. If the broker's role is unfamiliar, start with what an MQTT broker does.

Edge Features: Compute Locally, Publish Summaries

Sending raw 10 kHz vibration over the network all day is rarely necessary. Compute features at the edge on a fixed schedule, for example a one-second capture every minute, and publish the summary. The script below runs on a Raspberry Pi or industrial PC with an accelerometer reading function you supply. It uses NumPy for the maths.

import json
import time

import numpy as np
import paho.mqtt.client as mqtt

TOPIC = "connectmq/demo/v4c9e2/plant1/utilities/pump03/condition"
SAMPLE_RATE = 10_000   # Hz
CAPTURE_SECONDS = 1.0


def read_accelerometer(n_samples):
    """Replace with your ADC / sensor driver. Returns acceleration in g."""
    t = np.arange(n_samples) / SAMPLE_RATE
    signal = 0.3 * np.sin(2 * np.pi * 49.5 * t) + 0.05 * np.random.randn(n_samples)
    return signal


def features(acc_g):
    acc = acc_g - acc_g.mean()
    rms = float(np.sqrt(np.mean(acc ** 2)))
    peak = float(np.max(np.abs(acc)))
    kurt = float(np.mean(acc ** 4) / (np.mean(acc ** 2) ** 2))
    spectrum = np.abs(np.fft.rfft(acc)) / len(acc)
    freqs = np.fft.rfftfreq(len(acc), 1 / SAMPLE_RATE)
    def band(lo, hi):
        mask = (freqs >= lo) & (freqs < hi)
        return float(np.sqrt(np.sum(spectrum[mask] ** 2)))
    return {
        "rms_g": round(rms, 4),
        "peak_g": round(peak, 4),
        "crest": round(peak / rms, 2) if rms else None,
        "kurtosis": round(kurt, 2),
        "band_10_1k": round(band(10, 1000), 4),
        "band_1k_5k": round(band(1000, 5000), 4),
        "dominant_hz": round(float(freqs[np.argmax(spectrum[1:]) + 1]), 1),
    }


client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="pump03-edge-v4c9e2")
client.connect("broker.connectmq.com", 1883, keepalive=60)
client.loop_start()

while True:
    acc = read_accelerometer(int(SAMPLE_RATE * CAPTURE_SECONDS))
    payload = features(acc)
    payload.update({"running": True, "temp_c": 41.8, "ts": int(time.time())})
    client.publish(TOPIC, json.dumps(payload), qos=1)
    time.sleep(60)

Why these features: RMS tracks overall vibration energy and responds to imbalance and looseness; kurtosis and crest factor rise early with impacting faults such as bearing defects; the high band captures bearing and gear activity while the low band reflects running-speed effects. Always publish the running flag and load context, because vibration at idle and at full load are not comparable.

From Thresholds to Models

Work up the ladder; each step needs more data and delivers earlier warnings.

  1. Absolute limits. Use vibration severity guidance from relevant standards or the equipment manufacturer as an initial alarm level. Simple, explainable, and catches gross problems.
  2. Baseline deviation. Record a few weeks of healthy data per asset and operating state, then alert when features drift several standard deviations from that baseline. This adapts to each machine's normal.
  3. Multivariate anomaly detection. Models such as isolation forests or autoencoders look at all features together and flag unusual combinations even when no single value is extreme. The predictive maintenance machine learning article covers these in depth.
  4. Remaining useful life. With enough run-to-failure history, regression models estimate time to failure. This is the most valuable and the most data-hungry step, and many sites never need it.

A minimal baseline subscriber looks like this:

import json
import statistics
from collections import deque

import paho.mqtt.client as mqtt

TOPIC = "connectmq/demo/v4c9e2/plant1/utilities/+/condition"
baseline = {}  # asset -> deque of rms values while running


def on_connect(client, userdata, flags, reason_code, properties):
    client.subscribe(TOPIC, qos=1)


def on_message(client, userdata, msg):
    asset = msg.topic.split("/")[-2]
    data = json.loads(msg.payload)
    if not data.get("running"):
        return
    window = baseline.setdefault(asset, deque(maxlen=2000))
    if len(window) > 200:
        mean, sd = statistics.fmean(window), statistics.pstdev(window) or 1e-9
        z = (data["rms_g"] - mean) / sd
        if z > 4:
            alert = {"asset": asset, "feature": "rms_g", "value": data["rms_g"], "z": round(z, 1)}
            client.publish(msg.topic.replace("/condition", "/health"), json.dumps(alert), qos=1)
    window.append(data["rms_g"])


client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="pm-baseline-v4c9e2")
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.connectmq.com", 1883, keepalive=60)
client.loop_forever()

In production, freeze the baseline after the learning period rather than updating it continuously, or slow degradation will be absorbed into "normal".

Pitfalls That Sink Predictive Maintenance Projects

  • Mounting. A magnet on a painted, curved housing gives poor high-frequency response. Stud mounting or a properly prepared flat surface matters more than sensor price.
  • No operating context. Without speed and load, a feature change caused by a different product looks like a fault.
  • No feedback loop. Every alert must end with a maintenance finding recorded against it. Without that, models cannot be validated or improved.
  • Too many assets at once. Start with a handful of critical assets, prove one avoided failure, then scale.
  • Ignoring connectivity. Gateways go offline. Use MQTT Last Will messages and monitor sensor health, so a silent sensor is not read as a healthy machine.

A Step-by-Step Plan for the First Asset

  1. Pick one critical rotating asset with a known history of failures.
  2. List its failure modes and choose sensors accordingly.
  3. Install sensors and an edge gateway; publish features every minute to a test topic on the free public MQTT broker while you validate the pipeline.
  4. Move to a private broker before connecting production assets.
  5. Collect two to four weeks of baseline data with operating context.
  6. Enable limit and baseline alerts; route them to the maintenance team.
  7. Record findings for every alert and review monthly.
  8. Expand to similar assets and add more advanced models only where they add warning time.

Running the Data Flow on ConnectMQ

Condition data is a long-lived stream: sensors publish for years, and new consumers appear as the program matures. A managed MQTT broker from ConnectMQ handles that hub without your team running servers. Gateways connect over TLS on port 8883 with issued credentials, the devices view groups assets by ISA-95 level, and portal threshold alert rules can cover the simple absolute limits while your own services run baselines and models. Analytics tools, historians and Node-RED flows connect as ordinary MQTT clients. For the wider program, read the smart manufacturing guide.

Get Started with ConnectMQ

Sign up at app.connectmq.com, create a free Serverless broker with no credit card, connect one edge gateway and start building the baseline for your first predictive maintenance asset.

Frequently Asked Questions

What is the best first sensor for predictive maintenance?

For rotating equipment, a vibration sensor (accelerometer) gives the earliest warning for the most common mechanical failures. Add temperature and current as supporting signals.

Should I send raw vibration data over MQTT?

Usually no. Compute features at the edge and publish summaries; capture raw waveforms only on demand or when an anomaly is detected, and keep them within your plan's message size limit.

How much history do I need before predictions work?

Baseline and anomaly detection can start after a few weeks of healthy data. Remaining useful life models need run-to-failure history, which takes much longer to collect.

Can predictive maintenance work without machine learning?

Yes. Well-chosen limits and baseline deviation alerts deliver much of the value. Machine learning adds earlier and more nuanced detection once the basics are in place.

Related articles

OEE vs TEEP vs OOE: Which Metric Should You Use?

OEE, OOE and TEEP share the same performance and quality factors but measure against different time bases. This comparison works through one example and lists the MQTT signals each metric needs.

7 min read

All articles →

Your private MQTT broker is a few clicks away

Create an account, get your broker credentials and connect your first device — no servers to install, patch or scale.