Back to Documentation
Tutorial90 minutes

IoT Device Integration

Connect and manage IoT devices at scale with Munashe Tech Connect platform

Prerequisites
  • IoT devices with MQTT or HTTP connectivity
  • Munashe Tech Connect account with IoT access
  • Understanding of MQTT protocol and pub/sub patterns
  • Basic knowledge of device authentication and certificates

Step-by-Step Guide

1
Set Up IoT Project
12 min
  • Create a new IoT project in Munashe Tech Connect
  • Install required SDKs for device communication
  • Configure device authentication credentials
  • Set up device registry and groups
Code
# Install Munashe Tech IoT SDK
npm install @munashetech/iot @munashetech/mqtt

# Initialize IoT project
mt iot init my-iot-project \
  --region us-east \
  --protocol mqtt

# Create device registry
mt iot registry create home-devices \
  --description "Smart home devices" \
  --protocol mqtt \
  --auth-method certificate

# Generate device certificates
mt iot device create thermostat-01 \
  --registry home-devices \
  --cert-output ./certs/thermostat-01

# Set environment variables
cat > .env.local << EOF
IOT_PROJECT_ID=your_project_id
IOT_REGION=us-east
IOT_REGISTRY=home-devices
MQTT_BROKER=mqtt.munashetech.com
EOF
2
Configure Device Connectivity
15 min
  • Set up MQTT connection for real-time messaging
  • Implement device authentication
  • Configure message topics and QoS
  • Handle connection lifecycle events
Code
// lib/iot/client.ts
import { MunasheTechIoT, MQTTConfig } from '@munashetech/iot';
import fs from 'fs';

const mqttConfig: MQTTConfig = {
  host: process.env.MQTT_BROKER!,
  port: 8883,
  protocol: 'mqtts',
  clientId: `app-${Date.now()}`,
  username: process.env.IOT_PROJECT_ID!,
  password: process.env.IOT_API_KEY!,
  // Certificate-based authentication
  ca: fs.readFileSync('./certs/ca.crt'),
  cert: fs.readFileSync('./certs/device.crt'),
  key: fs.readFileSync('./certs/device.key'),
  rejectUnauthorized: true,
  // Connection options
  clean: true,
  reconnectPeriod: 1000,
  connectTimeout: 30 * 1000,
  keepalive: 60,
};

export const iotClient = new MunasheTechIoT({
  projectId: process.env.IOT_PROJECT_ID!,
  region: process.env.IOT_REGION!,
  mqtt: mqttConfig
});

// Connection lifecycle handlers
iotClient.on('connect', () => {
  console.log('Connected to IoT broker');
});

iotClient.on('disconnect', () => {
  console.log('Disconnected from IoT broker');
});

iotClient.on('error', (error) => {
  console.error('IoT connection error:', error);
});

iotClient.on('reconnect', () => {
  console.log('Reconnecting to IoT broker...');
});
3
Implement Device Communication
18 min
  • Send commands to devices
  • Receive telemetry data from devices
  • Implement request-response patterns
  • Handle message acknowledgments
Code
// lib/iot/device-manager.ts
import { iotClient } from './client';

export class DeviceManager {
  // Subscribe to device telemetry
  async subscribeToDevice(deviceId: string) {
    const topic = `devices/${deviceId}/telemetry`;
    
    await iotClient.subscribe(topic, { qos: 1 }, (message) => {
      const data = JSON.parse(message.toString());
      console.log(`Received from ${deviceId}:`, data);
      
      // Process telemetry data
      this.processTelemetry(deviceId, data);
    });
  }

  // Send command to device
  async sendCommand(deviceId: string, command: any) {
    const topic = `devices/${deviceId}/commands`;
    
    await iotClient.publish(topic, JSON.stringify(command), {
      qos: 1,
      retain: false
    });
    
    console.log(`Command sent to ${deviceId}:`, command);
  }

  // Request device state
  async requestDeviceState(deviceId: string): Promise<any> {
    const requestTopic = `devices/${deviceId}/state/request`;
    const responseTopic = `devices/${deviceId}/state/response`;
    
    return new Promise((resolve, reject) => {
      // Subscribe to response
      const timeout = setTimeout(() => {
        reject(new Error('Device state request timeout'));
      }, 5000);
      
      iotClient.subscribe(responseTopic, { qos: 1 }, (message) => {
        clearTimeout(timeout);
        const state = JSON.parse(message.toString());
        resolve(state);
      });
      
      // Send request
      iotClient.publish(requestTopic, JSON.stringify({
        timestamp: Date.now()
      }), { qos: 1 });
    });
  }

  private processTelemetry(deviceId: string, data: any) {
    // Store in database, trigger alerts, etc.
    // Implementation depends on your use case
  }
}

export const deviceManager = new DeviceManager();
4
Create Device Dashboard
20 min
  • Build real-time device monitoring UI
  • Display telemetry data with charts
  • Implement device control interface
  • Add device status indicators
Code
// app/dashboard/iot/page.tsx
'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { deviceManager } from '@/lib/iot/device-manager';

interface Device {
  id: string;
  name: string;
  type: string;
  status: 'online' | 'offline';
  lastSeen: Date;
  telemetry: {
    temperature?: number;
    humidity?: number;
    power?: boolean;
  };
}

export default function IoTDashboard() {
  const [devices, setDevices] = useState<Device[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Fetch devices and subscribe to updates
    async function initializeDevices() {
      const deviceList = await fetchDevices();
      setDevices(deviceList);
      
      // Subscribe to each device
      deviceList.forEach(device => {
        deviceManager.subscribeToDevice(device.id);
      });
      
      setLoading(false);
    }
    
    initializeDevices();
  }, []);

  const handleDeviceControl = async (deviceId: string, command: any) => {
    await deviceManager.sendCommand(deviceId, command);
  };

  return (
    <div className="container mx-auto p-6">
      <h1 className="text-3xl font-bold mb-6">IoT Device Dashboard</h1>
      
      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
        {devices.map((device) => (
          <Card key={device.id}>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-lg">{device.name}</CardTitle>
                <Badge variant={device.status === 'online' ? 'default' : 'secondary'}>
                  {device.status}
                </Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Type:</span>
                  <span>{device.type}</span>
                </div>
                
                {device.telemetry.temperature && (
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Temperature:</span>
                    <span>{device.telemetry.temperature}°C</span>
                  </div>
                )}
                
                {device.telemetry.humidity && (
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Humidity:</span>
                    <span>{device.telemetry.humidity}%</span>
                  </div>
                )}
              </div>
              
              {device.type === 'switch' && (
                <Button
                  className="w-full"
                  variant={device.telemetry.power ? 'destructive' : 'default'}
                  onClick={() => handleDeviceControl(device.id, {
                    action: 'toggle',
                    power: !device.telemetry.power
                  })}
                >
                  Turn {device.telemetry.power ? 'Off' : 'On'}
                </Button>
              )}
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}

async function fetchDevices(): Promise<Device[]> {
  // Fetch from your API
  const response = await fetch('/api/iot/devices');
  return response.json();
}
5
Implement Data Processing Pipeline
15 min
  • Set up cloud functions for data processing
  • Create rules for automated actions
  • Implement data aggregation
  • Configure data retention policies
Code
// Cloud function for processing IoT data
mt iot function create process-telemetry \
  --runtime nodejs20 \
  --trigger topic \
  --topic "devices/+/telemetry"

# functions/process-telemetry/index.ts
import { IoTMessage, CloudFunction } from '@munashetech/functions';

export const handler: CloudFunction = async (message: IoTMessage) => {
  const { deviceId, data, timestamp } = message;
  
  // Store in time-series database
  await storeTelemetry({
    device_id: deviceId,
    temperature: data.temperature,
    humidity: data.humidity,
    timestamp: timestamp
  });
  
  // Check thresholds and trigger alerts
  if (data.temperature > 30) {
    await sendAlert({
      device: deviceId,
      type: 'high_temperature',
      value: data.temperature,
      threshold: 30
    });
  }
  
  // Calculate rolling averages
  const avg = await calculateAverages(deviceId, '1h');
  
  // Update device twin/shadow
  await updateDeviceShadow(deviceId, {
    reported: {
      lastTemperature: data.temperature,
      averageTemp1h: avg.temperature
    }
  });
};

// Create automation rule
mt iot rule create temperature-alert \
  --condition "temperature > 30" \
  --action "send-notification" \
  --target "email:admin@example.com"

// Set data retention
mt iot data retention set \
  --hot-storage 7d \
  --warm-storage 30d \
  --cold-storage 365d \
  --auto-archive true
6
Add Device Firmware Updates (OTA)
10 min
  • Create firmware update packages
  • Implement OTA update mechanism
  • Monitor update progress
  • Handle rollback scenarios
Code
// Upload firmware package
mt iot firmware upload \
  --file firmware-v2.0.bin \
  --version 2.0.0 \
  --description "Bug fixes and improvements"

// Create deployment
mt iot firmware deploy \
  --version 2.0.0 \
  --devices thermostat-01,thermostat-02 \
  --schedule "2025-12-10T02:00:00Z" \
  --rollout progressive

// lib/iot/firmware.ts
export class FirmwareManager {
  async checkForUpdates(deviceId: string, currentVersion: string) {
    const response = await fetch(`/api/iot/firmware/check`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ deviceId, currentVersion })
    });
    
    return response.json();
  }

  async downloadFirmware(updateUrl: string): Promise<Buffer> {
    const response = await fetch(updateUrl);
    return Buffer.from(await response.arrayBuffer());
  }

  async applyUpdate(deviceId: string, firmware: Buffer) {
    // Send firmware to device in chunks
    const chunkSize = 1024;
    const totalChunks = Math.ceil(firmware.length / chunkSize);
    
    for (let i = 0; i < totalChunks; i++) {
      const chunk = firmware.slice(i * chunkSize, (i + 1) * chunkSize);
      
      await deviceManager.sendCommand(deviceId, {
        type: 'firmware-chunk',
        sequence: i,
        total: totalChunks,
        data: chunk.toString('base64')
      });
      
      // Wait for acknowledgment
      await this.waitForAck(deviceId, i);
    }
    
    // Trigger installation
    await deviceManager.sendCommand(deviceId, {
      type: 'firmware-install'
    });
  }

  private async waitForAck(deviceId: string, sequence: number) {
    // Implementation for acknowledgment waiting
  }
}

// Monitor deployment status
mt iot firmware status deployment-123
IoT Security Best Practices
  • Use certificate-based authentication: More secure than password-based auth
  • Encrypt all communications: Use TLS/SSL for MQTT connections
  • Implement device attestation: Verify device identity and integrity
  • Regular security updates: Keep firmware and certificates up to date
  • Monitor for anomalies: Detect unusual behavior and potential breaches
Testing Your IoT Integration

Verify your IoT setup is working correctly:

  1. 1.Test device connectivity with MQTT broker
  2. 2.Verify telemetry data is being received and processed
  3. 3.Send test commands to devices and verify response
  4. 4.Test connection recovery after network interruption
  5. 5.Verify data processing rules and alerts are triggered
  6. 6.Test firmware update deployment and rollback

Troubleshooting Tips

  • Connection failures: Verify certificates, check firewall rules, and network connectivity
  • Message loss: Increase QoS level, check network stability, verify broker capacity
  • High latency: Use edge computing, optimize message size, check network bandwidth
  • Device offline: Implement heartbeat mechanism, check power and network status

Next Steps

Edge Computing
Process data closer to devices for lower latency
Predictive Maintenance
Use ML to predict device failures before they occur

Building an IoT Solution?

Our IoT specialists can help you scale from prototype to production