物联网开发:MQTT与传感器数据采集

物联网开发:MQTT与传感器数据采集

大家好,我是欧阳瑞(Rich Own)。今天想和大家聊聊物联网开发这个热门话题。作为一个全栈开发者,物联网是连接物理世界和数字世界的关键技术。今天就来分享一下MQTT协议和传感器数据采集的实战经验。

什么是物联网?

物联网(IoT)是指将物理设备连接到互联网,实现数据采集和远程控制。

MQTT协议

什么是MQTT?

MQTT(Message Queuing Telemetry Transport)是一种轻量级的消息协议,专为物联网设计。

MQTT特点

特点 说明
轻量级 适合资源受限设备
低带宽 适合网络不稳定环境
发布/订阅 灵活的消息模式
QoS支持 保证消息可靠性

安装MQTT Broker

bash 复制代码
# 使用Docker安装Mosquitto
docker run -d --name mosquitto \
  -p 1883:1883 \
  -p 9001:9001 \
  eclipse-mosquitto

发布者代码

python 复制代码
import paho.mqtt.client as mqtt
import time

client = mqtt.Client()
client.connect("localhost", 1883, 60)

while True:
    # 模拟传感器数据
    temperature = 25 + (time.time() % 5)
    humidity = 60 + (time.time() % 20)
    
    client.publish("sensor/temperature", temperature)
    client.publish("sensor/humidity", humidity)
    
    print(f"Published: temp={temperature:.1f}C, humidity={humidity:.1f}%")
    time.sleep(1)

订阅者代码

python 复制代码
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("sensor/#")

def on_message(client, userdata, msg):
    print(f"{msg.topic} {msg.payload.decode()}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 1883, 60)
client.loop_forever()

实战案例:智能家居系统

python 复制代码
# 传感器节点
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import time

client = mqtt.Client()
client.connect("mqtt.example.com", 1883, 60)

# 读取传感器
def read_temperature():
    return 25.5

def read_humidity():
    return 60.2

def read_motion():
    return GPIO.input(4) == GPIO.HIGH

while True:
    client.publish("home/bedroom/temperature", read_temperature())
    client.publish("home/bedroom/humidity", read_humidity())
    client.publish("home/livingroom/motion", read_motion())
    time.sleep(5)
python 复制代码
# 控制节点
import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
    if msg.topic == "home/bedroom/light":
        if msg.payload.decode() == "on":
            turn_on_light()
        else:
            turn_off_light()

client = mqtt.Client()
client.on_connect = lambda client, userdata, flags, rc: client.subscribe("home/#")
client.on_message = on_message
client.connect("mqtt.example.com", 1883, 60)
client.loop_forever()

QoS级别

python 复制代码
# QoS 0: 最多一次
client.publish("sensor/data", "value", qos=0)

# QoS 1: 至少一次
client.publish("sensor/data", "value", qos=1)

# QoS 2: 恰好一次
client.publish("sensor/data", "value", qos=2)

安全性

python 复制代码
# 使用TLS
client.tls_set(ca_certs="ca.crt")
client.connect("mqtt.example.com", 8883, 60)

# 使用用户名密码
client.username_pw_set("user", "password")

总结

MQTT是物联网开发的基础协议,简单高效。通过MQTT,可以轻松实现传感器数据采集和设备控制。

我的鬃狮蜥Hash对物联网也有自己的理解------它总是能感知周围环境的变化,这也许就是自然界的"传感器"吧!

如果你对物联网开发感兴趣,欢迎留言交流!我是欧阳瑞,极客之路,永无止境!


技术栈:MQTT · 物联网 · 传感器

相关推荐
ZDGJ609915 小时前
外盘期货与内盘期货交易时间核心区别
区块链
cd_9492172116 小时前
数据使用控制的工程实现:数字合约、策略引擎与沙箱环境
区块链
Bczheng119 小时前
三十六.区块链网络(7)--修复net与测试例子
区块链
LedgerNinja19 小时前
WEEX API 稳定性实战:限频、重试与风控的工程化清单
运维·区块链
IvorySQL1 天前
PG 日报|修复高 IO 并发场景,解决预读机制耗尽本地缓冲区缺陷
数据库·人工智能·sql·postgresql·区块链
人间凡尔赛3 天前
2026 年 React Server Components 完全指南:Next.js 16 全栈开发最佳实践
前端·typescript·react·全栈·next.js
北冥you鱼3 天前
OpenZeppelin Contracts 完全指南:从入门到精通,构建安全的智能合约
安全·区块链·智能合约
财迅通Ai4 天前
科源制药领投企业航脑科技布局梳理:北大实验室、EXROBOT与工作犬脑电课题
人工智能·科技·区块链·科源制药
名字还没想好☜4 天前
React setState 连续调用「丢更新」排查:批量更新与函数式更新
前端·javascript·react.js·react·usestate
sugar__salt4 天前
DeepSeek-R1 WebGPU (1):在浏览器里跑大模型
react.js·reactjs·react·端模型