11. IoT Protocol-Specific Integration
11.1 MQTT Protocol Integration
MQTT (Message Queuing Telemetry Transport) is the most common IoT protocol. Integration pattern:
Architecture:
IoT Device → MQTT Broker (Mosquitto/HiveMQ) → Subscriber Application → aePiot URLComplete Implementation (Python):
import paho.mqtt.client as mqtt
import json
from urllib.parse import quote
from datetime import datetime
import sqlite3
class MQTTaePiotBridge:
"""Bridge MQTT messages to aePiot URLs"""
def __init__(self, broker_address, broker_port=1883):
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.broker_address = broker_address
self.broker_port = broker_port
self.db = self.init_database()
def init_database(self):
"""Initialize SQLite database for URL tracking"""
conn = sqlite3.connect('iot_aepiot.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS url_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
device_id TEXT,
topic TEXT,
aepiot_url TEXT,
distributed BOOLEAN
)
''')
conn.commit()
return conn
def on_connect(self, client, userdata, flags, rc):
"""Subscribe to topics on connection"""
if rc == 0:
print("Connected to MQTT broker")
# Subscribe to all sensor topics
client.subscribe("sensors/#")
client.subscribe("alerts/#")
client.subscribe("devices/+/status")
else:
print(f"Connection failed with code {rc}")
def on_message(self, client, userdata, message):
"""Process incoming MQTT messages"""
try:
topic = message.topic
payload = json.loads(message.payload.decode())
# Route to appropriate handler
if topic.startswith("sensors/temperature"):
self.handle_temperature(topic, payload)
elif topic.startswith("sensors/motion"):
self.handle_motion(topic, payload)
elif topic.startswith("alerts"):
self.handle_alert(topic, payload)
elif "/status" in topic:
self.handle_status(topic, payload)
except json.JSONDecodeError:
print(f"Invalid JSON in message from {topic}")
except Exception as e:
print(f"Error processing message: {e}")
def handle_temperature(self, topic, payload):
"""Handle temperature sensor data"""
device_id = payload.get('device_id', 'unknown')
temperature = payload.get('temperature')
threshold = payload.get('threshold', 85)
if temperature and temperature > threshold:
title = f"Temperature Alert - {device_id}"
description = f"Temperature: {temperature}°F exceeded threshold {threshold}°F"
link = f"https://dashboard.example.com/sensors/{device_id}"
aepiot_url = self.create_aepiot_url(title, description, link)
self.distribute_and_log(aepiot_url, device_id, topic)
def handle_motion(self, topic, payload):
"""Handle motion detection"""
device_id = payload.get('device_id', 'unknown')
zone = payload.get('zone', 'Unknown Zone')
timestamp = payload.get('timestamp', datetime.now().isoformat())
title = f"Motion Detected - {zone}"
description = f"Motion sensor {device_id} triggered at {timestamp}"
link = f"https://dashboard.example.com/security/{device_id}"
aepiot_url = self.create_aepiot_url(title, description, link)
self.distribute_and_log(aepiot_url, device_id, topic)
def handle_alert(self, topic, payload):
"""Handle critical alerts"""
device_id = payload.get('device_id', 'unknown')
alert_type = payload.get('type', 'General Alert')
severity = payload.get('severity', 'MEDIUM')
message = payload.get('message', 'Alert triggered')
title = f"{severity} Alert - {device_id}"
description = f"{alert_type}: {message}"
link = f"https://dashboard.example.com/alerts/{device_id}"
aepiot_url = self.create_aepiot_url(title, description, link)
# Priority distribution for HIGH severity
if severity == 'HIGH':
self.distribute_urgent(aepiot_url, device_id)
else:
self.distribute_and_log(aepiot_url, device_id, topic)
def handle_status(self, topic, payload):
"""Handle device status changes"""
device_id = topic.split('/')[-2]
status = payload.get('status', 'unknown')
if status == 'offline':
title = f"Device Offline - {device_id}"
description = f"Device {device_id} went offline at {payload.get('timestamp')}"
link = f"https://dashboard.example.com/devices/{device_id}/diagnostics"
aepiot_url = self.create_aepiot_url(title, description, link)
self.distribute_and_log(aepiot_url, device_id, topic)
def create_aepiot_url(self, title, description, link):
"""Create properly encoded aePiot URL"""
encoded_title = quote(title)
encoded_description = quote(description)
encoded_link = quote(link)
url = f"https://aepiot.com/backlink.html?title={encoded_title}&description={encoded_description}&link={encoded_link}"
return url
def distribute_and_log(self, url, device_id, topic):
"""Distribute URL and log to database"""
# Log to database
cursor = self.db.cursor()
cursor.execute('''
INSERT INTO url_log (timestamp, device_id, topic, aepiot_url, distributed)
VALUES (?, ?, ?, ?, ?)
''', (datetime.now().isoformat(), device_id, topic, url, True))
self.db.commit()
# Distribute URL (implement your notification logic)
print(f"Generated aePiot URL: {url}")
# send_email(url)
# send_sms(url)
# post_to_slack(url)
def distribute_urgent(self, url, device_id):
"""Urgent distribution for critical alerts"""
# Implement multi-channel urgent notification
print(f"URGENT: {url}")
# send_sms_urgent(url)
# send_push_notification(url)
# call_escalation_list(url)
def start(self):
"""Start MQTT client"""
self.client.connect(self.broker_address, self.broker_port, 60)
self.client.loop_forever()
# Usage
if __name__ == "__main__":
bridge = MQTTaePiotBridge("mqtt.broker.address")
bridge.start()11.2 CoAP Protocol Integration
CoAP (Constrained Application Protocol) is used for resource-constrained devices.
Implementation (Python with aiocoap):
import asyncio
from aiocoap import *
from urllib.parse import quote
import json
class CoAPaePiotBridge:
"""Bridge CoAP observations to aePiot URLs"""
def __init__(self):
self.context = None
async def observe_resource(self, uri):
"""Observe a CoAP resource and generate URLs on changes"""
self.context = await Context.create_client_context()
request = Message(code=GET, uri=uri, observe=0)
observation = self.context.request(request)
observation_result = observation.observation
async for response in observation_result:
await self.process_coap_response(response, uri)
async def process_coap_response(self, response, uri):
"""Process CoAP response and generate aePiot URL"""
try:
payload = json.loads(response.payload.decode())
device_id = payload.get('device_id', 'unknown')
sensor_type = payload.get('type', 'sensor')
value = payload.get('value')
title = f"{sensor_type.title()} Reading - {device_id}"
description = f"{sensor_type}: {value}"
link = f"https://dashboard.example.com/coap/{device_id}"
aepiot_url = self.create_aepiot_url(title, description, link)
print(f"CoAP observation: {aepiot_url}")
except Exception as e:
print(f"Error processing CoAP response: {e}")
def create_aepiot_url(self, title, description, link):
"""Create aePiot URL"""
return f"https://aepiot.com/backlink.html?title={quote(title)}&description={quote(description)}&link={quote(link)}"
# Usage
async def main():
bridge = CoAPaePiotBridge()
await bridge.observe_resource("coap://[device-ip]/sensors/temperature")
asyncio.run(main())11.3 HTTP/REST API Integration
Many IoT devices use simple HTTP POST requests.
Implementation (Express.js):
const express = require('express');
const app = express();
app.use(express.json());
// Endpoint for IoT devices to POST data
app.post('/iot/data', (req, res) => {
const { deviceId, sensorType, value, threshold } = req.body;
// Validation
if (!deviceId || !sensorType || value === undefined) {
return res.status(400).json({ error: 'Missing required fields' });
}
// Check if action required
if (threshold && value > threshold) {
const title = encodeURIComponent(`${sensorType} Alert - ${deviceId}`);
const description = encodeURIComponent(`Value ${value} exceeded threshold ${threshold}`);
const link = encodeURIComponent(`https://dashboard.example.com/devices/${deviceId}`);
const aepiotUrl = `https://aepiot.com/backlink.html?title=${title}&description=${description}&link=${link}`;
// Distribute URL
notifyUsers(aepiotUrl);
return res.json({
status: 'alert',
url: aepiotUrl
});
}
res.json({ status: 'ok' });
});
app.listen(8080);11.4 LoRaWAN Integration
LoRaWAN devices typically send data through a network server.
Integration Pattern:
# Integration with ChirpStack or The Things Network
from urllib.parse import quote
import json
import base64
def handle_lorawan_uplink(payload):
"""Process LoRaWAN uplink message"""
# Decode LoRaWAN payload
device_eui = payload['devEUI']
data = base64.b64decode(payload['data'])
# Parse sensor data (example: temperature sensor)
temperature = int.from_bytes(data[0:2], byteorder='big') / 100.0
battery = data[2]
# Generate aePiot URL
title = quote(f"LoRaWAN Device {device_eui}")
description = quote(f"Temp: {temperature}°C, Battery: {battery}%")
link = quote(f"https://dashboard.example.com/lorawan/{device_eui}")
aepiot_url = f"https://aepiot.com/backlink.html?title={title}&description={description}&link={link}"
return aepiot_url12. QR Code Generation and Implementation
12.1 Why QR Codes for IoT-aePiot Integration
QR codes provide physical access points to IoT information:
Use Cases:
- Equipment maintenance technicians scan device label
- Facility managers access room sensor status
- Field workers access outdoor sensor data
- Security personnel check access control logs
- Warehouse staff check inventory sensor status
12.2 QR Code Generation Methods
Python (qrcode library):
import qrcode
from urllib.parse import quote
def generate_device_qr(device_id, device_type, location):
"""Generate QR code for IoT device access"""
# Create aePiot URL
title = quote(f"{device_type} - {location}")
description = quote(f"Device ID: {device_id}")
link = quote(f"https://dashboard.example.com/devices/{device_id}")
aepiot_url = f"https://aepiot.com/backlink.html?title={title}&description={description}&link={link}"
# Generate QR code
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data(aepiot_url)
qr.make(fit=True)
# Create image
img = qr.make_image(fill_color="black", back_color="white")
img.save(f"qr_device_{device_id}.png")
return aepiot_url
# Example usage
generate_device_qr("TEMP-001", "Temperature Sensor", "Warehouse B")JavaScript/Node.js (qrcode library):
const QRCode = require('qrcode');
async function generateDeviceQR(deviceId, deviceType, location) {
const title = encodeURIComponent(`${deviceType} - ${location}`);
const description = encodeURIComponent(`Device ID: ${deviceId}`);
const link = encodeURIComponent(`https://dashboard.example.com/devices/${deviceId}`);
const aepiotUrl = `https://aepiot.com/backlink.html?title=${title}&description=${description}&link=${link}`;
try {
// Generate QR code as file
await QRCode.toFile(`qr_device_${deviceId}.png`, aepiotUrl, {
errorCorrectionLevel: 'H',
type: 'png',
width: 300
});
// Or generate as data URL
const dataUrl = await QRCode.toDataURL(aepiotUrl);
return { url: aepiotUrl, qrCode: dataUrl };
} catch (error) {
console.error('QR code generation failed:', error);
}
}12.3 Bulk QR Code Generation for Fleet
Python Script for Multiple Devices:
import qrcode
import csv
from urllib.parse import quote
from PIL import Image, ImageDraw, ImageFont
def generate_fleet_qr_codes(csv_file):
"""Generate QR codes for entire IoT device fleet"""
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
device_id = row['device_id']
device_type = row['type']
location = row['location']
# Generate aePiot URL
title = quote(f"{device_type} - {location}")
description = quote(f"Device: {device_id} | Location: {location}")
link = quote(f"https://dashboard.example.com/devices/{device_id}")
aepiot_url = f"https://aepiot.com/backlink.html?title={title}&description={description}&link={link}"
# Generate QR code
qr = qrcode.QRCode(version=1, box_size=10, border=4)
qr.add_data(aepiot_url)
qr.make(fit=True)
# Create labeled image
qr_img = qr.make_image(fill_color="black", back_color="white")
# Add label below QR code
label_img = create_labeled_qr(qr_img, device_id, device_type, location)
label_img.save(f"labels/qr_{device_id}.png")
print(f"Generated QR for {device_id}")
def create_labeled_qr(qr_img, device_id, device_type, location):
"""Add text label below QR code"""
# Create new image with space for label
label_height = 100
new_img = Image.new('RGB', (qr_img.width, qr_img.height + label_height), 'white')
new_img.paste(qr_img, (0, 0))
# Add text
draw = ImageDraw.Draw(new_img)
try:
font = ImageFont.truetype("arial.ttf", 16)
except:
font = ImageFont.load_default()
text_lines = [
f"Device: {device_id}",
f"Type: {device_type}",
f"Location: {location}"
]
y_position = qr_img.height + 10
for line in text_lines:
draw.text((10, y_position), line, fill='black', font=font)
y_position += 25
return new_img
# Usage
generate_fleet_qr_codes('device_fleet.csv')Sample CSV Format:
device_id,type,location
TEMP-001,Temperature Sensor,Warehouse A
HUMID-002,Humidity Sensor,Storage Room 3
MOTION-003,Motion Detector,Entrance Hall
PRESS-004,Pressure Sensor,Tank 712.4 Dynamic QR Codes (URL Updates)
For scenarios where destination URLs change but physical QR codes cannot be replaced:
Implementation Strategy:
# Use a redirect service on your domain
def generate_permanent_qr(device_id):
"""Generate QR with permanent redirect URL"""
# This URL never changes
permanent_url = f"https://yourdomain.com/device/{device_id}"
# Generate QR for permanent URL
qr = qrcode.make(permanent_url)
qr.save(f"permanent_qr_{device_id}.png")
return permanent_url
# Server-side redirect handler
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/device/<device_id>')
def device_redirect(device_id):
"""Redirect to current aePiot URL for device"""
# Fetch current device info from database
device_info = get_device_info(device_id)
# Generate current aePiot URL
title = quote(f"{device_info['type']} - {device_info['location']}")
description = quote(f"Current status: {device_info['status']}")
link = quote(f"https://dashboard.example.com/devices/{device_id}")
aepiot_url = f"https://aepiot.com/backlink.html?title={title}&description={description}&link={link}"
return redirect(aepiot_url)13. Physical Device Labeling and Access
13.1 Label Design Best Practices
Essential Elements:
- QR Code (300x300px minimum for easy scanning)
- Device ID (human-readable)
- Device Type
- Installation Location
- Installation Date
- Emergency Contact (optional)
Label Template (HTML for printing):
<!DOCTYPE html>
<html>
<head>
<style>
.device-label {
width: 10cm;
height: 7cm;
border: 2px solid black;
padding: 10px;
font-family: Arial, sans-serif;
}
.qr-code {
float: left;
width: 4cm;
height: 4cm;
}
.device-info {
margin-left: 4.5cm;
font-size: 14px;
}
.device-info h2 {
margin: 0;
font-size: 18px;
}
@media print {
.device-label {
page-break-after: always;
}
}
</style>
</head>
<body>
<div class="device-label">
<img src="qr_TEMP-001.png" class="qr-code" alt="QR Code">
<div class="device-info">
<h2>TEMP-001</h2>
<p><strong>Type:</strong> Temperature Sensor</p>
<p><strong>Location:</strong> Warehouse A</p>
<p><strong>Installed:</strong> 2026-01-15</p>
<p><strong>Scan for Status</strong></p>
</div>
</div>
</body>
</html>13.2 Weatherproof QR Code Labels
For outdoor or industrial environments:
Material Recommendations:
- Polyester labels with UV-resistant laminate
- Anodized aluminum plates with laser etching
- Ceramic labels for extreme temperatures
QR Code Size Recommendations:
- Indoor: 3cm x 3cm minimum
- Outdoor: 5cm x 5cm minimum
- High-placement (above 2m): 8cm x 8cm minimum
13.3 NFC Tags as Alternative
For devices in difficult-to-scan locations:
import ndef
from urllib.parse import quote
def program_nfc_tag(device_id, device_type, location):
"""Program NFC tag with aePiot URL"""
title = quote(f"{device_type} - {location}")
description = quote(f"Device ID: {device_id}")
link = quote(f"https://dashboard.example.com/devices/{device_id}")
aepiot_url = f"https://aepiot.com/backlink.html?title={title}&description={description}&link={link}"
# Create NDEF record
record = ndef.UriRecord(aepiot_url)
return [record]End of Part 3
Continue to Part 4 for real-time vs. periodic generation strategies, fleet management, and use case scenarios.
Support Resources:
- For detailed implementation guidance: ChatGPT
- For complex integration scripts: Claude.ai
Part 4: Implementation Strategies and Real-World Use Cases
Real-Time vs. Periodic Generation, Fleet Management, and Industry-Specific Applications
Table of Contents - Part 4
- Real-Time vs. Periodic URL Generation Strategies
- Multi-Device and Fleet Management
- Industry-Specific Use Cases
- Scaling Considerations
- Performance Optimization