Posted on
Artificial Intelligence

Artificial Intelligence IoT Projects

Author
  • User
    linuxbash
    Posts by this author
    Posts by this author

Artificial Intelligence IoT Projects: A Bash‑First Guide for Linux Tinkerers

If you’ve ever SSH’d into a Raspberry Pi at 2 a.m. to revive a sensor, you know the pain of fragile IoT systems. Now add AI—vision, anomaly detection, voice—and the stack can get overwhelming fast. The good news: with a few well‑chosen tools and solid Bash muscle memory, you can build AI‑powered IoT projects that are fast, private, and reliable on modest Linux hardware.

This guide shows you why AI at the edge matters and walks you through three practical, reproducible projects—plus a small dose of “production‑ready” hardening. Everything is driven from the shell with package‑manager‑friendly steps for apt, dnf, and zypper.


Why AI + IoT at the edge?

  • Latency and reliability: Decisions on-device (e.g., “person detected,” “machine vibrating abnormally”) don’t depend on flaky networks or cloud round‑trips.

  • Privacy and cost: Keep video/audio/sensor data local; reduce bandwidth and cloud fees.

  • Power and portability: Modern models can run on CPUs, ARM boards, or modest GPUs—no data center needed.

  • Composability: MQTT + Node‑RED + Python give you a clean, scriptable way to connect sensors, inference, and actions.


Prerequisites (Linux setup you can paste)

Run these once to get essentials on your distro.

  • Ubuntu/Debian/Raspberry Pi OS (apt):
sudo apt update
sudo apt install -y python3 python3-venv python3-pip git build-essential cmake pkg-config libgl1 libglib2.0-0 ffmpeg curl
  • Fedora/RHEL/CentOS Stream (dnf):
sudo dnf groupinstall -y "Development Tools"
sudo dnf install -y python3 python3-pip python3-virtualenv git cmake pkgconf-pkg-config mesa-libGL glib2 ffmpeg curl
  • openSUSE Leap/Tumbleweed (zypper):
sudo zypper refresh
sudo zypper install -y python3 python3-pip python3-virtualenv git gcc-c++ make cmake pkg-config Mesa-libGL1 glib2 ffmpeg curl

Tip: Create a workspace.

mkdir -p ~/ai-iot && cd ~/ai-iot

Project 1: Edge camera classifier with TFLite (CPU‑friendly)

A tiny, fast image classifier that runs entirely on your device—great for presence detection, product sorting, or quick proofs of concept.

1) Create a Python virtual environment and install packages.

python3 -m venv .venv
. .venv/bin/activate
pip install --upgrade pip
pip install tflite-runtime numpy pillow opencv-python

2) Download a small MobileNet model and labels.

curl -L -o mobilenet_v1_1.0_224_quant.tflite \
  https://storage.googleapis.com/download.tensorflow.org/models/tflite/gpu/mobilenet_v1_1.0_224_quant.tflite

curl -L -o labels.txt \
  https://storage.googleapis.com/download.tensorflow.org/models/tflite/gpu/labels.txt

3) Minimal Python script to classify webcam frames.

cat > cam_classify.py <<'PY'
import cv2, numpy as np
from tflite_runtime.interpreter import Interpreter

labels = [l.strip() for l in open("labels.txt", "r")]
interpreter = Interpreter("mobilenet_v1_1.0_224_quant.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

cap = cv2.VideoCapture(0)  # change to a file path if needed
if not cap.isOpened():
    raise SystemExit("No camera found")

def preprocess(img):
    img = cv2.resize(img, (224, 224))
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return img.astype(np.uint8)[None, ...]

while True:
    ok, frame = cap.read()
    if not ok:
        break
    x = preprocess(frame)
    interpreter.set_tensor(input_details[0]['index'], x)
    interpreter.invoke()
    out = interpreter.get_tensor(output_details[0]['index'])[0]
    idx = int(np.argmax(out))
    conf = int(out[idx])
    print(f"Top-1: {labels[idx]} ({conf}/255)")
    # Press Ctrl+C to stop
PY

4) Run it.

. .venv/bin/activate
python cam_classify.py

What you get: Top‑1 predictions printed to the terminal in real time. Swap in a different TFLite model when you’re ready (e.g., custom model via Edge Impulse).


Project 2: MQTT sensor hub + Node‑RED wiring

MQTT moves data; Node‑RED makes it easy to wire “sensor → AI → action” without glue code.

1) Install Mosquitto (MQTT broker) + clients.

  • apt:
sudo apt install -y mosquitto mosquitto-clients
sudo systemctl enable --now mosquitto
  • dnf:
sudo dnf install -y mosquitto mosquitto-clients
sudo systemctl enable --now mosquitto
  • zypper:
sudo zypper install -y mosquitto mosquitto-clients
sudo systemctl enable --now mosquitto

2) Install Node‑RED via npm.

  • apt:
sudo apt install -y nodejs npm
  • dnf:
sudo dnf install -y nodejs npm
  • zypper:
sudo zypper install -y nodejs npm

Then install Node‑RED globally and run it.

sudo npm install -g --unsafe-perm node-red
node-red

Node‑RED UI will be at:

http://localhost:1880

(If remote, use an SSH tunnel: ssh -L 1880:localhost:1880 user@edge-host.)

3) Test MQTT round‑trip from your shell.

# Terminal A
mosquitto_sub -t test/topic -v
# Terminal B
mosquitto_pub -t test/topic -m "hello from bash"

4) In Node‑RED, add:

  • mqtt in node (topic: sensors/temperature)

  • function node (e.g., convert string to float and check thresholds)

  • mqtt out or http/email/exec node for actions

This gives you a visual “bus” to connect AI outputs to alarms, webhooks, LEDs, etc.


Project 3: Predictive maintenance (anomaly detection via MQTT)

Use an Isolation Forest to flag abnormal vibration. Trains online with your stream’s first N samples, then scores new data.

1) Create a venv (or reuse Project 1’s) and install deps.

python3 -m venv .venv
. .venv/bin/activate
pip install --upgrade pip
pip install scikit-learn paho-mqtt numpy

2) Anomaly detector that learns from the first 300 samples on sensors/vibration and then reports anomalies.

cat > vib_anomaly.py <<'PY'
import os, sys, signal, numpy as np
from sklearn.ensemble import IsolationForest
import paho.mqtt.client as mqtt

BROKER = os.getenv("MQTT_HOST", "localhost")
TOPIC = os.getenv("MQTT_TOPIC", "sensors/vibration")
WARMUP = int(os.getenv("WARMUP", "300"))
model, X = None, []

def on_message(client, userdata, msg):
    global model, X
    try:
        v = float(msg.payload.decode().strip())
    except:
        return
    if model is None:
        X.append([v])
        if len(X) >= WARMUP:
            model = IsolationForest(contamination=0.02, random_state=42)
            model.fit(np.array(X))
            print(f"Model trained on {len(X)} samples", flush=True)
    else:
        score = model.decision_function([[v]])[0]  # higher is more normal
        pred = model.predict([[v]])[0]             # 1 normal, -1 anomaly
        status = "ANOMALY" if pred == -1 else "OK"
        print(f"{status}: value={v:.4f} score={score:.4f}", flush=True)

def main():
    c = mqtt.Client()
    c.on_message = on_message
    c.connect(BROKER, 1883, 60)
    c.subscribe(TOPIC, qos=0)
    print(f"Listening on mqtt://{BROKER}/{TOPIC} ...", flush=True)
    c.loop_forever()

if __name__ == "__main__":
    signal.signal(signal.SIGINT, lambda s,f: sys.exit(0))
    main()
PY

3) Run it.

. .venv/bin/activate
python vib_anomaly.py

4) No sensor yet? Simulate one from Bash.

while :; do
  v=$(python3 - <<'PY'
import math, random, time
t = time.time()
print(f"{math.sin(t/5)+random.uniform(-0.05,0.05):.4f}")
PY
)
  mosquitto_pub -t sensors/vibration -m "$v"
  sleep 0.5
done

You’ll see “Model trained on …” after warmup, then OK/ANOMALY messages as values deviate.


Bonus: Keep your AI scripts alive with systemd

Turn your ad‑hoc Python into services so they start at boot and restart on failure.

1) Create a user service for the anomaly detector.

mkdir -p ~/.config/systemd/user
cat > ~/.config/systemd/user/vib-anomaly.service <<'UNIT'
[Unit]
Description=Vibration Anomaly Detector
After=network-online.target

[Service]
Type=simple
Environment=MQTT_HOST=localhost
Environment=MQTT_TOPIC=sensors/vibration
WorkingDirectory=%h/ai-iot
ExecStart=%h/ai-iot/.venv/bin/python %h/ai-iot/vib_anomaly.py
Restart=on-failure
RestartSec=3

[Install]
WantedBy=default.target
UNIT

2) Enable linger so user services run without an active login, then enable + start.

sudo loginctl enable-linger "$USER"
systemctl --user daemon-reload
systemctl --user enable --now vib-anomaly.service
systemctl --user status vib-anomaly.service

3) Logs whenever you need them.

journalctl --user -u vib-anomaly.service -f

Repeat the pattern for cam_classify.py, or wrap Node‑RED in a service if you prefer it not to run in a terminal.


Real‑world tips

  • Start simple, measure, then optimize. CPU‑only TFLite or ONNXRuntime often suffices. Add accelerators (NVIDIA Jetson, Intel NPU, Coral TPU) later if needed.

  • Standardize on MQTT topics and payloads (JSON or newline‑delimited floats). It saves hours when wiring tools together.

  • Treat models like code: version them, checksum them, and store with your project history (Git).

  • Secure Mosquitto (passwords/TLS) once things work locally. Don’t expose 1883 to the internet without auth.


Conclusion and next steps

You now have:

  • A working edge AI classifier

  • A robust MQTT + Node‑RED backbone

  • An online‑learning anomaly detector with systemd supervision

Next, combine them: publish camera classifications to MQTT, build Node‑RED dashboards, and trigger actions (GPIO, webhooks, SMS). Containerize with Podman/Docker, or orchestrate a cluster with k3s if you’re scaling out.

Your move:

  • Fork this into your own repo, script the setup, and push to your edge devices.

  • Swap in your own models and real sensors.

  • Share what you build—the Linux/Bash/IoT community thrives on practical examples.

Happy hacking!