物联网开发: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 · 物联网 · 传感器

相关推荐
葫三生6 小时前
《论三生原理》对《周易》《道德经》的一次根本性重写?
人工智能·算法·计算机视觉·区块链·量子计算
Richown9 小时前
性能优化:前端加载性能优化指南
区块链·react
Richown9 小时前
后端性能:Node.js性能优化与调优
区块链·react
Richown9 小时前
无服务器架构:AWS Lambda与Serverless最佳实践
区块链·react
Richown11 小时前
数据可视化:交互式图表与大屏展示
区块链·react
Richown1 天前
区块链预言机:Chainlink与去中心化数据获取
区块链·react
打小就很皮...1 天前
基于 Python + LangChain + React 的 AI 流式对话与历史存储实战(拓展图片上传)
langchain·react·sse·图片解析
打小就很皮...1 天前
基于 Python + LangChain + React 的 AI 流式对话与历史存储实战
人工智能·langchain·flask·react·sse